pyTelegramBotAPI。如何在next_step_handler解决方案中保存状态?

时间:2017-07-30 22:34:43

标签: python telegram

我的解决方案中的用户一步一步地在电报中键入消息。问题是服务器重启后他的状态没有保存,他需要重新开始。

例如,如果用户在'process_mid'步骤,重新启动后,他就无法进入'process_end'。用户只能通过键入“start”命令开始新的阶段。

bot = telebot.TeleBot(TOKEN)


@bot.message_handler(commands=['start'])
def process_start(message):
    text = 'start'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_mid)


def process_mid(message):
    text = 'mid'
    bot.send_message(message.chat.id, text)
    bot.register_next_step_handler(message, process_end)


def process_end(message):
    text = 'end'
    bot.send_message(message.chat.id, text)

bot.polling(none_stop=True)

3 个答案:

答案 0 :(得分:0)

根据我对这个机器人的经验,如果你想从你离开的地方接收,你需要将所有数据保存到文件(或数据库)。

您可以保存您的进度,并在process_start函数中在函数入口处使用message.chat.id标识用户,如果该值存在于文件(数据库)中,则注册相应的下一步。

答案 1 :(得分:0)

尝试将用户的状态以及用户的聊天ID存储在数据库中,然后从那里验证状态。

为此,尝试创建类似的内容

class States(enumerate):
    # Enter all states like numbers
    S_START = 0
    ...

此外,创建用于从db获取状态的函数:

def get_current_state(user_id):
    # getting state by user's chat ID from DB
    ...

之后,只需为每个用户的聊天ID状态写入数据库(在所需的每个处理程序中更改它),然后在处理程序func中对其进行验证:

@bot.message_handler(func=lambda message: get_current_state(message.chat.id) == config.States.S_START.value)
def some_function(message):
    ...

答案 2 :(得分:0)

此示例将向您展示如何使用 register_next_step处理程序 https://github.com/eternnoir/pyTelegramBotAPI/blob/master/examples/step_example.py