Search code examples
telegram-botpy-telegram-bot-api

pyTelegramBotAPI - How can I create a message that updates with buttons?


I recently tried to create a message that updates when a button in the inline keyboard is pressed, but without success.

I'm using pyTelegramBotAPI, I can get the bot to send the message with the keyboard, but I can't get the various buttons to work.

Can you help me? :<


Solution

  • In order to create a multi-option choice (ie buttons) you use InlineKeyboardButton object

        options = []
    
        # buttons
        options.append(InlineKeyboardButton('One', callback_data='1'))
        options.append(InlineKeyboardButton('Two', callback_data='2'))
        options.append(InlineKeyboardButton('Three', callback_data='3'))
    
        reply_markup = InlineKeyboardMarkup([options])
    
        update.message.reply_text(response.message, reply_markup=reply_markup)
    

    Make sure to set the corresponding CallbackQueryHandler to process the user choice

        updater.dispatcher.add_handler(CallbackQueryHandler(main_handler, pass_chat_data=True, pass_user_data=True))
    

    In the example above the method main_handler(update, context) will be responsible to process the user input.

    Feel free to check the TelegramBotDemo GitHub repository to see a full implementation