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

标签 python telegram py-telegram-bot-api

我的解决方案中的用户通过在 Telegram 中输入消息来逐步进行。问题是服务器重新启动后他的状态没有保存,他需要重新开始。

例如,如果用户处于“process_mid”步骤,则重新启动后,他无法转到“process_end”。用户只能通过输入“开始”命令来开始新阶段。

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)

最佳答案

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

尝试创建类似的东西

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

此外,创建从数据库获取状态的函数:

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):
    ...

关于python - pyTelegramBotAPI。如何在 next_step_handler 解决方案中保存状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405369/

相关文章:

python - pyTelegramBotAPI 禁用链接预览

python - 通过 pyTelegramBotAPI 在电报机器人中获取照片

python - 当字符串更改时,如何在不同的数据框中写入初始日期和最终日期?

python - 如何使用 numpy 提高 python 代码性能

telegram - 通过 Telegram Bot 通过 message_id 链接消息

telegram - 当它是一个组的一部分时如何隐藏 Telegram BOT 命令?

python - 如何获取python的firefox地址栏url(pywin32)

Python 矩阵给出与最后一条记录相同的结果

proxy - 通过 Dante socks5 代理服务器的 Telegram 调用不起作用

python - SQLAlchemy + pyTelegramBotAPI : SQLite objects created in a thread can only be used in that same thread