pythonpy-telegram-bot-apitelebot

How to prevent Python Telebot from duplicating messages?


I've got a problem with Python Telebot, here is my code:

import telebot
token = 'token'
bot = telebot.TeleBot(token)

@bot.message_handler(func=lambda message: True)
def start(message):
    bot.send_message(message.chat.id,"message")
    bot.register_next_step_handler(message, nextstep)

def nextstep(message):
    bot.send_message(message.chat.id,"anothermessage")
    bot.register_next_step_handler(message, finalstep)

def finalstep(message):
    bot.send_message(message.chat.id,"in previous step you sent: " + str(message.text) + ". Now let's start again")
    start(message)

print ("running")
bot.infinity_polling(skip_pending=True)

This code is running ok and looks like this in Telegram chat:

initial

But if I send two messages it starts looking like this:

after two messages

And ends up like this:

final

After this the bot keeps to duplicate answers to my messages, as well as multiply triggering the functions. Like the code is double-running itself from the point when bot receives two or more messages. After restart it's ok again, until the next double message.

What is causing duplicate messages? How to prevent it?


Solution

  • Because your code does double-runs itself: at the end of the first turn finalstep calls start but then bot's message handler calls start again. And further: bot.register_next_step_handler() just adds a callable object to the bot's list of handlers, so that list grows after each message and bot runs all that handlers at every next step. I think your nextstep and finalstep should by like:

    def nextstep(message):
        bot.send_message(message.chat.id,"anothermessage")
        bot.clear_step_handler(message)    
        bot.register_next_step_handler(message, finalstep)
    
    def finalstep(message):
        bot.send_message(message.chat.id,"in previous step you sent: " + 
                          str(message.text) + ". Now let's start again")
        bot.clear_step_handler(message)