Search code examples
pythonbotstelegram

how to get callback from inline keyboard telegram


I know how to send inline keybard button message but i want to know how to recive callbackdata when user press on it

 keyboard = [
                [InlineKeyboardButton("Click button 1", callback_data='callback_1')],
                [InlineKeyboardButton("Click button 1", callback_data='callback_2')]
            ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    message_reply_text = 'Click one of these buttons'
    user_message.message.reply_text(message_reply_text, reply_markup=reply_markup)

Solution

  • You can use CallbackQueryHandler to assign function which will be executed when you click button.

    dp.add_handler(CallbackQueryHandler(keyboard_callback))
    

    and you can get it as

    update.callback_query.data
    

    from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
    from telegram import InlineKeyboardButton, InlineKeyboardMarkup
    import os
    
    TOKEN = os.getenv('TELEGRAM_TOKEN')
    
    def start(update, context):
        keyboard = [
                    [InlineKeyboardButton("Click button 1", callback_data='callback_1')],
                    [InlineKeyboardButton("Click button 1", callback_data='callback_2')]
                   ]
        reply_markup = InlineKeyboardMarkup(keyboard)
        message_reply_text = 'Click one of these buttons'
        update.message.reply_text(message_reply_text, reply_markup=reply_markup)
    
    def keyboard_callback(update, context):
        query = update.callback_query
        #print('query:', query)
        
        print('query.data:', query.data)
        query.answer(f'selected: {query.data}')
    
    if __name__=='__main__':
        update = Updater(TOKEN, use_context=True)
        dp = update.dispatcher
    
        dp.add_handler(CommandHandler("start", start))
       
        dp.add_handler(CallbackQueryHandler(keyboard_callback))
       
        print('Starting ...')
        update.start_polling()
        update.idle()