In telebot @bot.message_handler() running even if it is kept inside a if statement

Viewed 792

I am relatively new to coding and to python. I am trying to make a telegram bot using telebot. I have a flow in which I have to go. eg: after /start, I should get a text. So I created a running_work_list in which my workflow is arranged in order and after completion, I delete the index 0 elements. 'start' is the first element in the array. So I tried to implement something like this so that I can comfortably code each step rather than looking at input and deciding.

But despite putting inside an if statement, '@bot.message_handler()' is running even if the condition fails.

    if running_work_list[0]=='start':
        print('inside if')
        @bot.message_handler(commands=['start','new test'])
        def start(message):
            print('user sent start')
            bot.send_message(message.chat.id,welcome_message)
            running_work_list.pop(0)
            print(f'work flow deciding list {running_work_list}')
        @bot.message_handler(content_types=['text','photo','poll'])
        def bot_intro(message):
            print('here')
            print(f'user sent {message.text}')
            bot.send_message(message.chat.id,BOT_INTRO_MSG)

Below are the outputs I got. The user had sent /start first and then some other random text.

    inside if
    user sent start
    work flow deciding list ['test_name', 'test_description', 'test_time', 'test_image', 'test_poll']
    here
    user sent fdf

Is it like the '@bot.message_handler()' will run even if we put it inside an if statement?

1 Answers

Executing @bot.message_handler decorator marks the function to be called when the message matches the filters that you've passed as arguments (content_types or commands). They are called by the telebot library directly and do not execute the if statement after they have been registered.

The proper way to do this is to invert the logic: define the message handler functions at the top level of the program and decide what you should do in the if within the function.

Related