如何记录Python开发的Telegram机器人与用户的全部对话?求简便方案
提取Telegram机器人对话内容的简便方法
除了getUpdates和Webhooks,还有几个更简便的方案:
实时本地存储
在你的Python机器人代码里,处理每一条用户消息/交互时,直接把对话内容(包括用户ID、消息内容、时间戳、机器人回复等)写入本地文件(比如JSON、CSV)或者轻量数据库(比如SQLite)。这种方式零额外配置,完全可控。
示例代码片段:import sqlite3 from telegram import Update from telegram.ext import CallbackContext # 初始化数据库 conn = sqlite3.connect('bot_conversations.db') c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS conversations (user_id INTEGER, message_text TEXT, sender TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''') conn.commit() # 消息处理函数中保存对话 def handle_message(update: Update, context: CallbackContext): user_id = update.effective_user.id message_text = update.effective_message.text # 保存用户消息 c.execute("INSERT INTO conversations VALUES (?, ?, ?, CURRENT_TIMESTAMP)", (user_id, message_text, 'user')) conn.commit() # 机器人回复逻辑 reply_text = "收到你的消息了" update.message.reply_text(reply_text) # 保存机器人回复 c.execute("INSERT INTO conversations VALUES (?, ?, ?, CURRENT_TIMESTAMP)", (user_id, reply_text, 'bot')) conn.commit()使用Pyrogram库批量拉取历史对话
Pyrogram是一个易用的Telegram API封装库,支持直接拉取特定聊天的历史消息。你可以先通过get_dialogs获取所有和机器人有过交互的对话列表,再逐个调用get_history拉取完整对话。这个方法适合事后批量导出,不需要修改原有机器人的实时逻辑。
示例代码片段:from pyrogram import Client api_id = "你的API ID" api_hash = "你的API Hash" bot_token = "你的机器人Token" app = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token) async def export_conversations(): async with app: # 获取所有对话 dialogs = await app.get_dialogs() for dialog in dialogs: # 拉取该对话的历史消息 messages = await app.get_history(chat_id=dialog.chat.id) # 保存到文件 with open(f"conversation_{dialog.chat.id}.txt", "w", encoding="utf-8") as f: for msg in messages: sender = "用户" if not msg.from_user.is_self else "机器人" f.write(f"{sender} [{msg.date}]: {msg.text}\n") app.run(export_conversations())注意:使用Pyrogram需要提前在Telegram开发者平台获取API ID和API Hash,注册账号后即可获取,步骤简单。
直接调用Telegram API的
getChatHistory接口
如果你不想用第三方库,也可以直接通过HTTP请求调用getChatHistory接口:先通过getUpdates获取所有用户的chat ID,再循环对每个chat ID调用该接口拉取历史。注意要遵守API的频率限制,避免被限流。
请求示例:GET https://api.telegram.org/bot{token}/getChatHistory?chat_id={user_id}&limit=100可通过
offset参数分页拉取更多历史消息。
内容的提问来源于stack exchange,提问作者Riley Zhuo
相关产品推荐
相关产品推荐

