Search code examples
pythontelegramtelegram-botpython-telegram-bot

Telegram Python ConversationHandler Remember Old Answers


I am using This ConversationHandler Script as a basis for my program.

How can I retrieve a users answer from a previous state? For example, when the user is asked about their Bio, how can I print their Gender (that was the first thing that was asked)?

It looks like each function returns the next steps (GENDER->PHOTO->LOCATION->BIO) but is there a way to see what a previous input was?


Solution

  • I faced exactly the same issue where I needed to keep previous user answers for a conversation. Take a look at Handler documentation which is a base class for all handlers. It has parameter called pass_user_data. When set to True it passes user_data dictionary to your handler and it's related to the user the update was sent from. You can utilize it to achieve what you are looking for.

    Let's say I have a conversation with an entry point and two states:

    def build_conversation_handler():
        conversation_handler = ConversationHandler(
            entry_points=[CommandHandler('command', callback=show_options)],
            states={
                PROCESS_SELECT: [CallbackQueryHandler(process_select, pass_user_data=True)],
                SOME_OTHER: [MessageHandler(filters=Filters.text, callback=some_other, pass_user_data=True)],
            },
        )
    

    Here are the handlers for the conversation:

    def show_options(bot, update):
        button_list = [
            [InlineKeyboardButton("Option 1", callback_data="Option 1"),
             InlineKeyboardButton("Option 2", callback_data="Option 2")]]
    
        update.message.reply_text("Here are your options:", reply_markup=InlineKeyboardMarkup(button_list))
        return PROCESS_SELECT
    
    def process_select(bot, update, user_data):
        query = update.callback_query
        selection = query.data
        # save selection into user data
        user_data['selection'] = selection
        return SOME_OTHER
    
    def some_other(bot, update, user_data):
        # here I get my old selection
        old_selection = user_data['selection']
    

    In the first handler I show user keyboard to choose an option, in the next handler I grab selection from callback query and store it into user data. The last handler is a message handler so it has no callback data, but since I added user_data to it I can access the dictionary with the data that I added previously. With this approach you can store and access anything between the handlers that will be related to a user.