Forums

Telegram bot. Problems with the register_next_step_handler() function on the paid account.

The problem is that on a paid account the function does not work from the first entry of the message. Sometimes you have to enter the message several times.

I found a similar problem on the Toaster forum, but there was no answer: link

from flask import Flask
from flask_sslify import SSLify
import telebot

token = 'your_token'

bot = telebot.TeleBot(token, threaded=False)
bot.remove_webhook()
bot.set_webhook(url="https://yourName.pythonanywhere.com/{}".format(token))

app = Flask(__name__)

sslify = SSLify(app)

@app.route('/{}'.format(token), methods=["POST"])
def webhook():
    bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
    return "ok", 200

@bot.message_handler(content_types=['text'])
def text(message):
    if (message.text == 'test'):
        msg = bot.send_message(message.chat.id, '<b>Enter any message</b>', parse_mode="HTML")
        bot.register_next_step_handler(msg , test)

def test(message):
    try:
        bot.reply_to(message, 'It's working')
    except Exception as e:
        bot.reply_to(message, 'oooops')

if __name__ == '__main__':
    app.run()

hi- what is the telebot library you are using?

I took a look at this repo but could not find any code for register_next_step_handler.

Hi. It's pyTelegramBotAPI.

To clarify, are you running this as a PythonAnywhere webapp? Or as a console script/scheduled task?

According to the documentation, if you set telebot.TeleBot(threaded=False), it "does not execute message handlers on it's polling thread".

If you are doing a bot.polling() from within the webapp, it will probably block and never return.

Looking at the pyTelegramBotAPI code for register_next_step_handler, I'm also not 100% sure if it deals with multiple web worker processes correctly...

I'm runing this as a PythonAnywhere webapp.

And note. For a free account, it works right away, but on a paid account it's not always right away.

The issue is then, as conrad said, pyTelegramBotAPI assumes you're running in a single process. With a paid account, you have a number of workers. Your first message could be going to one worker and setting the callback, but the next one goes to a worker that has not had the callback registered, so it doesn't respond. That's why it works sometimes.

Oh. I understand. Thanks for the explanation!

Oh. I understand. Thanks for the explanation!

I have same problem. Problem was resolved by adding

bot.enable_save_next_step_handlers(delay=2)

I have same problem and i added

bot.enable_save_next_step_handlers(delay=2)

but It didn't fix,can anybody help?

See this. You could switch back to a single web workers, but note that that would mean that your webapp might respond slower.