Search code examples
python-telegram-bot

How build a conversation handler with CllbackQueryHandler in it


NB: I use version 12 of python-telegram-bot package.

I would like to build a conversation handler: when a user chooses \charts command, the bot shows them an inline list of choices, and depending on their choice, return them a chart.

charts_handler = ConversationHandler(
    entry_points=[CommandHandler('chart', chart_start)],
    states={
        ChartChoices.choosing_user: [CallbackQueryHandler(
            individual_chart,
            pass_user_data=True)
        ],
    },
    fallbacks=[done_handler],
)

But if I do not set per_message=False then it results in this error:

If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message.

If I do set per_message=True, then it results in the error:

If 'per_message=True', all entry points and state handlers                                      
must be 'CallbackQueryHandler', since no other handlers have a message context.

So it seems that the only way to build a conversation handler with CallBackQueryHandler (or in other words to show inline keyboard during chat) is to set all handlers to CallbackQueryHandler. Is it correct?


Solution

  • First of all, this is not an error, it's a warning you can safely ignore: If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message.

    Second, you don't need a ConversationHandler for described use case. Example user interaction: User: /charts Bot: Here is the list of available charts: Bar chart 1 /chart_1 Bar chart 2 /chart_2 Pie chart /chart_3

    And this kind of flow you can implement with simple MessageHandler and Filters

    Docs: MessageHandler

    Docs: Filters

    Namely you can use the regex filter.

    ConversationHandler is useful when you need a multistep iteraction with the user (like filling out a long form step by step). If you can identify user requests by other means, like generated commands, inline buttons, message text — prefer doing it this way.