How To Change Conversation Handler State with a CallbackQueryHandler Button function

Viewed 962

I have a python telegram bot that sends messages with Buttons on them like this:

keyboard = [[telegram.InlineKeyboardButton("Finish", callback_data='1'),
             telegram.InlineKeyboardButton("Edit", callback_data='2')]]
update_obj.message.reply_text(message_text, reply_markup=reply_markup,
                              parse_mode=telegram.ParseMode.MARKDOWN)

Image of a Telegram Message with two buttons

Now when the user hits the "Edit" button I want the ConversationHandler to move to another state. Here is a part of my ConversationHandler:

WELCOME = 0
SEARCH = 2
EDITTITLE = 3
[...]
handler = telegram.ext.ConversationHandler(
    entry_points=[telegram.ext.CommandHandler('start', start)],
    states={
        WELCOME: [
            telegram.ext.MessageHandler(filters=telegram.ext.Filters.all, callback=welcome),
            updater.dispatcher.add_handler(telegram.ext.CallbackQueryHandler(button))
        ],
        SEARCH: [
            telegram.ext.MessageHandler(filters=telegram.ext.Filters.all, callback=search),
            updater.dispatcher.add_handler(telegram.ext.CallbackQueryHandler(button))
        ], EDITTITLE: [
            telegram.ext.MessageHandler(filters=telegram.ext.Filters.all, callback=editTitle)
        ]
[...]

Now normally I can just return the new state in the callback function from the MesageHandler like so:

def search(update_obj, context):
    [...]
    return WELCOME

But if I return the new state in my button function it does not switch to that state. Here's the code:

def button(update_obj, context):
    [...]
    return EDITTITLE

How can I make the button change the ConversationHandler state or is there something I am missing? Am I using the Buttons the right way?

Thanks :)

1 Answers

You're adding the CallbackQueryHandlers wrongly to the conversation. updater.dispatcher.add_handler(telegram.ext.CallbackQueryHandler(button)) returns None, so None will be added to the list of handlers in the states WELCOME and SEARCH. Instead it should be just telegram.ext.CallbackQueryHandler(button). It could be that there are additional issues, but I'd have to see a full minimal working example to judge that.


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

Related