You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重复运行Telethon脚本时持续出现消息ID异常错误且程序无法终止

Telethon重复运行session文件出现消息ID错误且程序不停止的解决方法

问题场景

我正在学习Telethon,编写了如下脚本:

from telethon import TelegramClient

api_id = 1234567
api_hash = ''
client = TelegramClient('anon', api_id, api_hash)


async def main():
    me = await client.get_me()
    print(me.username)
    

with client:
    client.loop.run_until_complete(main())

首次运行完成授权验证后一切正常,但使用同一个.session文件再次运行时,持续输出以下错误信息:

Server sent a very new message with ID 7144059125492611077, ignoring
Server sent a very new message with ID 7144059125964561409, ignoring

并且程序出现该错误后不会自动停止运行。

原因分析

这个错误是因为服务器向客户端推送了会话中未记录的新消息ID,Telethon会自动忽略这些消息。但默认情况下,客户端在完成任务后不会主动断开连接,导致程序一直处于运行状态。

解决方法

方法1:任务完成后主动断开连接

在main函数末尾添加await client.disconnect(),确保执行完逻辑后主动断开客户端连接:

async def main():
    me = await client.get_me()
    print(me.username)
    await client.disconnect()  # 主动断开连接,程序正常退出

方法2:使用Telethon推荐的start()方法管理连接

替换with client:为with client.start(),start()方法会自动处理连接的建立与销毁,更符合Telethon的最佳实践:

from telethon import TelegramClient

api_id = 1234567
api_hash = ''
client = TelegramClient('anon', api_id, api_hash)


async def main():
    me = await client.get_me()
    print(me.username)
    

with client.start():
    client.loop.run_until_complete(main())

方法3:过滤日志(可选)

如果不想看到这类“ignoring”的日志信息,可以调整日志级别,只显示警告及以上级别的内容:

import logging
logging.basicConfig(level=logging.WARNING)

from telethon import TelegramClient

api_id = 1234567
api_hash = ''
client = TelegramClient('anon', api_id, api_hash)

# 后续代码不变

内容的提问来源于stack exchange,提问作者Such a stupid Me

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:20:27