用Python+aiogram开发Telegram Bot:如何捕获用户删聊天的错误信息?
可行解决方案
核心问题说明
Telegram 不会主动推送用户删除聊天会话的更新通知,且即使用户删除聊天,Bot 仍能正常发送消息(除非用户拉黑/屏蔽Bot),所以发消息无法触发错误检测。需要通过主动调用特定API来验证用户状态。
方案1:使用send_chat_action检测
send_chat_action是轻量化的检测方式,当用户删除聊天会话或屏蔽Bot时,调用该方法会抛出TelegramForbiddenError(403错误),以此判断用户状态。
示例代码:
from aiogram import Bot from aiogram.exceptions import TelegramForbiddenError async def is_user_chat_deleted(bot: Bot, user_id: int): try: # 发送"正在输入"动作,无实际内容,仅用于权限检测 await bot.send_chat_action(chat_id=user_id, action="typing") return False except TelegramForbiddenError: # 触发403错误,说明用户已删除聊天或屏蔽Bot return True
你可以在定时任务中批量检查用户,或者在用户长时间无交互后触发检测,一旦返回True,即可执行后续异常处理逻辑。
方案2:使用get_chat验证
调用get_chat获取用户聊天信息,同样会在用户删除聊天时抛出TelegramForbiddenError,适合需要额外聊天信息的场景:
示例代码:
from aiogram import Bot from aiogram.exceptions import TelegramForbiddenError async def check_chat_exists(bot: Bot, user_id: int): try: await bot.get_chat(chat_id=user_id) return False except TelegramForbiddenError: return True
注意事项
- 避免过于频繁调用API,遵守Telegram的API频率限制,防止被限流。
- 两种方法均依赖Telegram的权限校验,返回的错误可直接作为用户已删除聊天的判定依据。
内容的提问来源于stack exchange,提问作者Tomas Angelo
相关产品推荐
相关产品推荐

