Search code examples
pythonpython-telegram-bot

Telegram bot ConversationHandler ignores fallbacks


I have an issue with the Telegram bot (python-telegram-bot). I've made ConversationHandler, but the "fallbacks" won't work. Bot just ignores the "/stop " command. When I send "/stop" the bot sends me "First handler" instead of "GoodBye". What's wrong?

import os

import telegram
from telegram.ext import (ConversationHandler,
                          CommandHandler,
                          MessageHandler,
                          Filters,
                          Updater
)
from dotenv import load_dotenv

load_dotenv()

TELEGRAM_TOKEN = os.environ['TELEGRAM_TOKEN']
USER_ID = os.environ['USER_ID']
bot = telegram.Bot(token=TELEGRAM_TOKEN)
updater = Updater(token=TELEGRAM_TOKEN)


def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='hi')
    return 1


def stop(update, context):
    context.bot.send_message('Good Bye')
    return ConversationHandler.END


def first_handler(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text='First handler')
    return 1


conv_handler = ConversationHandler(
    entry_points=[CommandHandler('Start', start)],
    states={
        1: [MessageHandler(Filters.text, first_handler,
                           pass_user_data=True)],
    },
    fallbacks=[CommandHandler('stop', stop)]
)

dispatcher = updater.dispatcher
dispatcher.add_handler(conv_handler)

updater.start_polling()
updater.idle()

Solution

  • According to the documentation, the MessageHandler(Filters.text, ...) is handling all text messages, including the /stop command. However, fallbacks are only being triggered if none of the above handlers were able to deal with the message.

    You may exclude commands from the MessageHandler:

    MessageHandler(
        Filters.text & (~ Filters.command),
        first_handler,
    )
    

    The syntax for combining filters is documented here.