Search code examples
pythonpy-telegram-bot-api

Can I have multiple message handlers called on one command?


I want to contribute to a telegram bot, which has its functionality split into modules. This bot shows schedule of classes in my university. I want to add my own module that displays other events. Also I want to have minimal intervention to other modules besides mine.

Schedule for current day is shown with /today command and handler for it is already defined. I want to add my own handler that will also send user a message with my events.

The question is, can I have two different message handlers declared like this:

# module1.py
@bot.message_handler(commands=['today'])
def show_classes():
    ...

# my_module.py
@bot.message_handler(commands=['today'])
def show_events():
    ...

Will this approach work? If not, what is right way to do it?


Solution

  • Finally reached my PC. No, this won't work. Message handler filters are checked until first match. With such a code only test() will be invoked when /con arrives.

    @bot.message_handler(commands=['con'])
    def test(message: Message):
        bot.send_message(message.chat.id,"test1")
    
    @bot.message_handler(commands=['con'])
    def test2(message: Message):
        bot.send_message(message.chat.id,"test2")