如何在aiogram(v3.9.0)中获取与用户的私聊对话历史?
解决方法:获取私聊对话历史
可以通过Telegram Bot API提供的历史消息获取能力,结合aiogram v3.9.0的封装方法实现,不需要提前维护消息数据库或保存消息ID。
核心实现方式
使用aiogram中的bot.get_chat_history方法,传入用户的私聊ID(即用户的user_id)即可拉取对话历史。该方法支持异步迭代,可指定返回消息的数量上限,还能通过offset_message_id参数分批获取更早的消息。
示例代码
from aiogram import Bot from config import BOT_TOKEN # 替换为你的机器人token async def get_user_private_history(user_id: int): bot = Bot(token=BOT_TOKEN) history_records = [] # 先拉取最近100条消息(API单次最大限制) async for msg in bot.get_chat_history(chat_id=user_id, limit=100): record = { "消息ID": msg.message_id, "内容": msg.text, "发送时间": msg.date, "发送者ID": msg.from_user.id if msg.from_user else "系统消息" } history_records.append(record) # 如果需要获取更早的消息,可循环调用,传入最后一条消息的ID作为offset # 示例:获取接下来的100条更早消息 if history_records: last_msg_id = history_records[-1]["消息ID"] async for msg in bot.get_chat_history(chat_id=user_id, limit=100, offset_message_id=last_msg_id): record = { "消息ID": msg.message_id, "内容": msg.text, "发送时间": msg.date, "发送者ID": msg.from_user.id if msg.from_user else "系统消息" } history_records.append(record) await bot.session.close() return history_records
关键限制说明
- 权限要求:机器人必须与用户有过至少一次对话(用户发送过/start或其他消息),否则无法调用该接口获取历史
- 数量限制:单次调用最多返回100条消息,若需更多需循环分批拉取
- 保存期限:Telegram服务器不会永久保存所有消息,过旧的消息可能已被清理,无法拉取到
- 内容限制:只能获取文本消息及部分媒体消息的元数据,部分敏感或已被删除的消息无法获取
建议
如果需要长期留存对话历史,建议搭建本地数据库(如SQLite、PostgreSQL),在接收消息时实时存储,避免依赖Telegram服务器的临时存储。
内容的提问来源于stack exchange,提问作者alexeyprog
相关产品推荐
相关产品推荐

