单击按钮时如何显示消息?

How to display a message when clicking on a button?

我正在使用 TelegrafJS 和 NodeJS 创建一个 Telegram 机器人,我发现 TelegrafJS 的文档真的很差,我很难。

基本上我想知道当用户按下按钮时如何打印消息 Add project:

require('dotenv').config({ path: `.env` });
const Telegraf = require('telegraf');
const bot = new Telegraf(process.env.BOT_TOKEN);
const Markup = require('telegraf/markup');

bot.start((ctx) => ctx.replyWithMarkdown(
  `Welcome to my bot.`,
  Markup.inlineKeyboard([
    Markup.callbackButton('Add project...', 'Hello world')
  ]).extra()
));

bot.startPolling();

实际上当我按下 Add project 时什么也没有发生。抱歉这个愚蠢的问题,但我是电报的新手,我有很多东西要学

找到答案 here,基本上当您单击按钮电报发送 query 时,您可以使用此代码触发该事件:

bot.on('callback_query', (ctx) => {
  const action = ctx.update.callback_query.data;

  switch (action) {
    case 'Hello world':
      console.log("works!");
      break;
  }
});

.data 包含您在按钮标题后插入的标签,所以在我的例子中是 Hello world,当然您可以添加任何您想要的。