Using bot.register_next_step_handler in telegram bot I get TypeError: 'NoneType' object is not callable

Viewed 1990

The idea is to get telegram bot that receives from user some data, handles it, displays the result and then repeats the whole cycle not waiting a command from user. Here is the code:

from telebot import TeleBot

TOKEN = ""

bot = TeleBot(TOKEN)

@bot.message_handler(commands=['start'])
def regata(message):
    bot.send_message(message.chat.id, 'Enter tmfs separated with space: ')
    bot.register_next_step_handler(message, bla)


def bla(message):
    data_from_tg = message.text.split()
    tmf_1 = data_from_tg[0]
    tmf_2 = data_from_tg[1]
    bot.send_message(message.chat.id, f'Result: {tmf_1 + tmf_2}')
    bot.register_next_step_handler(message, regata(message))


bot.polling()

So the bot is working, but unfortunately after the second result is sent to user it fails with:

Traceback (most recent call last):
  File "D:\python\bot\testbot.py", line 21, in <module>
    bot.polling()
  File "C:\Python39\lib\site-packages\telebot\__init__.py", line 664, in polling
    self.__threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates)
  File "C:\Python39\lib\site-packages\telebot\__init__.py", line 726, in __threaded_polling
    raise e
  File "C:\Python39\lib\site-packages\telebot\__init__.py", line 686, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "C:\Python39\lib\site-packages\telebot\util.py", line 135, in raise_exceptions
    raise self.exception_info
  File "C:\Python39\lib\site-packages\telebot\util.py", line 87, in run
    task(*args, **kwargs)
TypeError: 'NoneType' object is not callable

Do I need to use some another pytelegrambotapi methods to implement the idea? Why does it work two times, but fails in the end? Thank you in advance for any ideas.

1 Answers

Try this:

@bot.message_handler(commands=['start'])
def regata(message):
    msg = bot.send_message(message.chat.id, 'Enter tmfs separated with space: ')
    bot.register_next_step_handler(msg, bla)


def bla(message):
    data_from_tg = message.text.split()
    tmf_1 = data_from_tg[0]
    tmf_2 = data_from_tg[1]
    msg = bot.send_message(message.chat.id, f'Result: {tmf_1 + tmf_2}')
    regata(message)


bot.polling()

Anyway, I suggest to not use register_next_step_handler. You can easily do the same in this way:

@bot.message_handler(commands=['start'])
def regata(message):
    bot.send_message(message.chat.id, 'Enter tmfs separated with space: ')

@bot.message_handler():
def bla(message):
    data_from_tg = message.text.split()
    tmf_1 = data_from_tg[0]
    tmf_2 = data_from_tg[1]
    bot.send_message(message.chat.id, f'Result: {tmf_1 + tmf_2}')
    regata(message)

bot.polling()
Related