
本文介绍了如何在使用 python-telegram-bot 库创建的 Telegram Bot 中,实现重启后保持用户状态的功能。默认情况下,ConversationHandler 的状态存储在内存中,重启会导致状态丢失。本文将指导你如何利用 python-telegram-bot 的持久化设置,将用户状态保存到磁盘,从而在重启后恢复用户之前的交互状态。
在使用 python-telegram-bot 库构建 Telegram Bot 时,ConversationHandler 是一个强大的工具,用于管理复杂的对话流程。然而,默认情况下,ConversationHandler 的状态信息存储在内存中。这意味着,一旦你的 Bot 进程重启,所有用户的当前状态都会丢失,用户必须重新输入 /start 命令才能重新开始交互。
为了解决这个问题,python-telegram-bot 提供了持久化机制,允许你将 Bot 的状态数据保存到磁盘或其他持久化存储介质中。这样,即使 Bot 重启,也可以从保存的数据中恢复用户之前的状态,从而提供更流畅的用户体验。
以下步骤展示了如何使用 python-telegram-bot 的内置持久化功能:
立即学习“Python免费学习笔记(深入)”;
导入必要的模块:
from telegram.ext import Application, ConversationHandler, PicklePersistence
创建 PicklePersistence 实例:
PicklePersistence 类使用 Python 的 pickle 模块将数据序列化到磁盘。你需要指定一个文件路径来存储数据。
persistence = PicklePersistence(filepath="bot_data.pkl")
这里 bot_data.pkl 是用于存储数据的文件的名称。你可以根据需要更改此名称。
创建 Application 实例时传入 persistence:
application = Application.builder().token("YOUR_BOT_TOKEN").persistence(persistence).build()将 persistence 对象传递给 Application.builder() 的 persistence() 方法,以启用持久化功能。
在 ConversationHandler 中使用 persistent=True:
确保在创建 ConversationHandler 时,将 persistent 参数设置为 True。
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
# 定义你的状态
},
fallbacks=[CommandHandler("cancel", cancel)],
persistent=True, # 启用持久化
name='my_conversation' # 给你的会话起一个名字,方便后续恢复
)name 参数是可选的,但建议使用,因为它允许你稍后按名称恢复特定的会话。
添加 ConversationHandler 到 Application:
application.add_handler(conv_handler)
运行 Bot:
application.run_polling()
from telegram import Update
from telegram.ext import Application, CommandHandler, ConversationHandler, ContextTypes, PicklePersistence
# 定义状态
FIRST, SECOND = range(2)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text("请告诉我你的名字:")
return FIRST
async def first(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
context.user_data['name'] = update.message.text
await update.message.reply_text(f"你好, {context.user_data['name']}! 请告诉我你的年龄:")
return SECOND
async def second(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
context.user_data['age'] = update.message.text
await update.message.reply_text(f"好的,你的名字是 {context.user_data['name']},年龄是 {context.user_data['age']}。")
return ConversationHandler.END
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text("会话已取消。")
return ConversationHandler.END
def main() -> None:
# 创建持久化对象
persistence = PicklePersistence(filepath="bot_data.pkl")
# 创建 Application 实例
application = Application.builder().token("YOUR_BOT_TOKEN").persistence(persistence).build()
# 创建 ConversationHandler
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
FIRST: [CommandHandler("first", first)],
SECOND: [CommandHandler("second", second)],
},
fallbacks=[CommandHandler("cancel", cancel)],
persistent=True,
name="my_conversation"
)
# 添加 Handler
application.add_handler(conv_handler)
# 运行 Bot
application.run_polling()
if __name__ == "__main__":
main()注意事项:
通过使用 python-telegram-bot 的持久化功能,你可以轻松地在 Bot 重启后保持用户状态,从而提供更佳的用户体验。 PicklePersistence 是一种简单易用的方案,适用于大多数基本场景。对于更复杂的应用,可以考虑使用更高级的持久化方案。 记住,在 ConversationHandler 中启用 persistent=True,并在创建 Application 实例时传入 persistence 对象。
以上就是Python Telegram Bot:重启后保持用户状态的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号