sfarzoso
sfarzoso

Reputation: 1600

How to display a message when clicking on a button?

I'm using TelegrafJS with NodeJS for create a Telegram bot, I'm actually finding the documentation of TelegrafJS really poor and I'm in difficult.

Essentially I would like to know how can I print a message when the user press the button 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();

actually when I press Add project nothing happen. Sorry for the stupid question, but I'm a newbie on telegram and I have a lot of thing to learn

Upvotes: 2

Views: 1302

Answers (1)

sfarzoso
sfarzoso

Reputation: 1600

Found the answer here, essentially when you click on a button telegram send a query, you can trigger that event using this code:

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

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

the .data contains the label that you have inserted after the button title, so in my case is Hello world, but of course you can add all you want.

Upvotes: 1

Related Questions