0

I have dynamically created buttons in an array

keyboard = InlineKeyboardMarkup()
keyboard.row_width = 2
for i in range(0, len(adress)):
    keyboard.add(InlineKeyboardButton(adress[i].text, callback_data="address_"))
bot.send_message(cid, 'Выберите адрес парковки', reply_markup=keyboard)

How do I track the click of one of the buttons and get the text from it? I set all the buttons the same callback_data. Perhaps you can do this if call. data = = "address_":, but how do I get the button text?

Ilya
  • 343
  • 3
  • 10
  • '*I set all the buttons the same callback_data*': don't ? The idea of `callback_data` is to know what button is pressed. – 0stone0 May 10 '21 at 22:56

1 Answers1

1

When a users clicks on an InlineKeyboardButton with callback_data, that results in an CallbackQuery. A CallbackQuery does not contain info about the text of the button that was clicked, but only about the callback_data the button had. So if you want to know the text associated with that button I recommend to make the callback_data unique per button. You could

  • put that text directly into the callback_data
  • make the callback_data some unique identifier and store a mapping identifier → text
  • make the callback_data some unique identifier and extract the text by checking which of the buttons in callback_query.message.reply_markup.keyboard has that callback_data. Note that this doesn't work for callback queries from inline messages, is those don't bring along the callback_query.message

Personally I'd recommand the second solution.

CallMeStag
  • 5,467
  • 1
  • 7
  • 22
  • How can this be done? I can make the `callback_data` unique, but then how do I create a handler and how do I get the message? `callback_data` will always be different because it is generated dynamically – Ilya May 11 '21 at 07:47
  • 1
    > how do I create a handler Can't answer that, as I'm not familiar with pyTelegramBotApi > how do I get the message if it's not an inline message, it will be contained in the update sent by Telegram – CallMeStag May 11 '21 at 07:53