如何解决Telethon报错:Connection to Telegram failed 5 time(s)
问题:Telegram机器人连接失败报错原因分析
我开发了一个机器人,以持续模式监听3个Telegram频道。该机器人有时可正常运行一周无需重启并接收新消息,但有时运行数小时后会出现报错。
报错信息
Automatic reconnection failed 5 time(s)Future exception was never
retrievedfuture: <Future finished
exception=ConnectionError('Connection to Telegram failed 5
time(s)')>ConnectionError: Connection to Telegram failed 5 time(s)
报错前通常会出现如下提示:
Attempt to connect 1, Attempt to connect 2 and etc
机器人代码
import config from telethon import events, TelegramClient from datetime import date, datetime client = TelegramClient("NEW", config.TELEGRAM_ID, config.TELEGRAM_HASH) def start(): client.start() client.run_until_disconnected() @client.on(events.NewMessage(chats=("names_of_channels"))) async def normal_handler_coinbase(event): data = event.message.message start()
报错原因分析
- 网络波动/不稳定:这是最常见的诱因。机器人运行环境的网络出现间歇性中断(比如ISP临时故障、路由波动、防火墙/代理临时阻断Telegram连接),导致客户端无法和Telegram服务器维持长连接。Telethon默认会尝试自动重连,但连续5次失败后就会抛出该错误。
- Telegram服务器端限制:如果机器人短时间内请求过于频繁,或者IP被Telegram反垃圾机制临时限制,也可能引发连接失败。不过你的情况是间歇性出现,这种概率相对较低,但仍需排查。
- 默认重连策略局限性:当前代码依赖
client.run_until_disconnected()的自动重连,但默认策略无法应对部分复杂网络场景(比如长时间断网后恢复),一旦连续5次重连失败,程序直接终止,没有额外重试机制。 - 会话文件异常:如果会话文件(
NEW.session)损坏,可能导致连接不稳定,但这种情况一般会在启动阶段就报错,而非运行数小时后出现。
修复建议
- 排查运行环境的网络稳定性,检查是否存在频繁丢包、延迟过高的情况;若使用代理,确认代理服务是否可靠。
- 添加自定义重连逻辑,在连接失败后主动重试:
import time import config from telethon import events, TelegramClient from datetime import date, datetime def create_client(): return TelegramClient("NEW", config.TELEGRAM_ID, config.TELEGRAM_HASH) def start(): while True: try: client = create_client() @client.on(events.NewMessage(chats=("names_of_channels"))) async def normal_handler_coinbase(event): data = event.message.message client.start() client.run_until_disconnected() except Exception as e: print(f"连接失败,错误信息:{e}") print("10秒后尝试重新连接...") time.sleep(10) start()
- 避免在消息处理函数中执行耗时操作,防止阻塞事件循环,影响客户端与服务器的心跳检测。
内容的提问来源于stack exchange,提问作者AskingForAnswers
相关产品推荐
相关产品推荐

