Telegraf.js add buttons with markup on sendPhoto

15.3k Views Asked by At

I've a bot.telegram.sendPhoto() with this code:

bot.telegram.sendPhoto(
  channel_id,
  {source: filepath},
  { 
    caption: description.join("\n"), 
    parse_mode: 'MarkdownV2'
  }
)

(description is an array with some text.

So i would to add some buttons and then perform an action but how can i do? I've tried in this way:

const buttons = Markup.keyboard([
            ["Test", "Test2"]
        ]).oneTime().resize().extra()

and then added it into the {...} after parse_mode:

{ 
  caption: description.join("\n"), 
  parse_mode: 'MarkdownV2',
  buttons
}

but it doesn't work. And i tried also after the {...}

{ 
  caption: description.join("\n"), 
  parse_mode: 'MarkdownV2'
},
buttons

but it still doesn't work. So how can i do? Thank you

1

There are 1 best solutions below

3
On

Markup.keyboard represents custom-keyboard (see here) for replying text - which can't possibly be used in channels (since members can't send messages in channels).

You probably are looking for inline-keyboards (buttons that are attached at the bottom of messages members can interact with).

Here is how you send inline keyboard in telegraf (example with callback_data buttons):

const buttons = Telegraf.Extra.markup((m) =>
  m.inlineKeyboard([
      [ m.callbackButton('Test', 'test') ],
      [ m.callbackButton('Test 2', 'test2') ]
  ])
)

bot.action('test', async (ctx) => {
  console.log(ctx)
  try {
    await ctx.answerCbQuery();    
  } catch (error) {
  }
})


bot.telegram.sendPhoto(
  channel_id,
  {source: filepath},
  { 
    caption: description.join("\n"), 
    parse_mode: 'MarkdownV2',
    reply_markup: buttons.reply_markup
  }
)

bot.launch()

If you want to use the telegraf/markup module instead, update the code as follows:

const Markup = require('telegraf/markup')

const buttons = Markup.inlineKeyboard([
  [Markup.callbackButton('Test', 'test')],
  [Markup.callbackButton('Test 2', 'test2')]
])

bot.telegram.sendPhoto(
  channel_id, {
    source: filepath
  }, {
    caption: description.join("\n"),
    parse_mode: 'MarkdownV2',
    reply_markup: buttons
  }
)

sample output:

enter image description here

Further Resources: