Michael ten Den
Michael ten Den

Reputation: 391

Telegram Bot InlineKeyboardButton, How to know which dynamically button is pressed?

I'm using Python Telegram Bot and I'm struggling with handling callback query handlers.

The problem

I've created a list of inlinekeyboard buttons (see image below), and they all trigger the same callback query. However, I'm unable to extract which inline keyboard button has been pressed and triggered the callback query.

How it looks in Telegram

inlinekeyboard_in_telegram

Background info

In my code I've created this inline keyboard which grows depending on the number of items in the List 'drawdates' (see the def below).

def drawdate_keyboard(drawdates):
    keyboard = []

    for idx, drawdate in enumerate(drawdates):
         keyboard.append([InlineKeyboardButton(drawdate, callback_data=str(SET_DRAWDATE))])
  
    keyboard.append([InlineKeyboardButton('Cancel', callback_data=str(CANCEL))])

    return InlineKeyboardMarkup(keyboard)

I'm using a conversation handlers which looks like this:

conv_handler = ConversationHandler(
        entry_points=[CommandHandler("start", start)],
        states={
                CALLBACKS_ROUTES: [
                    CallbackQueryHandler(add_ticket, pattern=str(ADD_TICKET)),
                    CallbackQueryHandler(get_drawdates, pattern=str(GET_DRAWDATES)),
                    CallbackQueryHandler(check_tickets, pattern="^" + str(CHECK_TICKETS) + "$"),
                    CallbackQueryHandler(clear_tickets, pattern="^" + str(CLEAR_TICKETS) + "$"),
                ],
                TICKET: [
                    MessageHandler(Filters.text & ~Filters.command, ticket),
                    CallbackQueryHandler(start_over, pattern="^" + str(CANCEL) + "$"),
                ],
                DRAWDATE: [
                    CallbackQueryHandler(set_drawdate, pattern=str(SET_DRAWDATE)),
                    CallbackQueryHandler(start_over, pattern="^" + str(CANCEL) + "$"),
                ],
        },
        fallbacks=[CommandHandler("start", start)],
        #per_message=True,
    )
    updater.dispatcher.add_handler(conv_handler)

and the callback is catched by this:

def set_drawdate(update: Update, context) -> int:
    query = update.callback_query  
    query.answer()

Upvotes: 0

Views: 1644

Answers (1)

CallMeStag
CallMeStag

Reputation: 7030

As Ouroborus already implied, the callback_data parameter is there to allow you to identify the button. You should make sure that each button has a unique callback_data which identifies the button.

Since you're using the python-telegram-bot library, let me also point out that this library includes convenience functionality that allows you to pass arbitrary objects as callback_data. In your case, you could e.g. pass datetime.datetime objects. See here for more info.


Disclaimer: I'm currently the maintainer of python-telegram-bot.

Upvotes: 1

Related Questions