使用Telethon实现Webhook时遇RuntimeError问题求助
Telethon Webhook 实现时的 RuntimeError 解决方法
你遇到的异常为:
raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)') RuntimeError: The asyncio event loop must not change after connection (see the FAQ for details)
问题根源
Telethon 客户端初始化并建立连接后,会绑定一个固定的异步事件循环。若启动 Web 服务器时创建新循环,或在不同循环中复用客户端,就会触发该异常。
简便解决方案:共享同一事件循环
让 Telethon 客户端与 Web 服务器共用同一个异步事件循环,是最直接的解决方式,无需复杂的跨循环通信逻辑。
实现步骤与示例代码
from telethon import TelegramClient from fastapi import FastAPI import uvicorn # 替换为你的实际参数 API_ID = 123456 API_HASH = "abcdef1234567890abcdef1234567890" BOT_TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" # 初始化Telethon客户端 client = TelegramClient("bot_session", API_ID, API_HASH) # 创建FastAPI应用 app = FastAPI() # Webhook接收路由,直接将更新交给Telethon处理 @app.post("/webhook") async def webhook_handler(update: dict): await client._handle_update(update) async def main(): # 先启动Telethon客户端连接 await client.start(bot_token=BOT_TOKEN) # 复用客户端的事件循环启动uvicorn config = uvicorn.Config(app, host="localhost", port=8001, loop=client.loop) server = uvicorn.Server(config) await server.serve() if __name__ == "__main__": # 使用客户端绑定的循环运行整个程序 client.loop.run_until_complete(main())
关键注意事项
- 禁止使用
asyncio.run(),它会每次创建新的事件循环,必然引发冲突 - 必须先启动 Telethon 客户端,再启动 Web 服务器,确保两者绑定同一循环
client._handle_update(update)是 Telethon 内部处理更新的方法,可直接复用你已编写的@client.on(...)装饰器逻辑
框架适配提示
若使用 Flask 等非异步 Web 框架,需借助 asgiref 等工具将其转为 ASGI 应用,但更推荐使用 FastAPI/Starlette 这类原生异步框架,与 Telethon 兼容性更佳。
内容的提问来源于stack exchange,提问作者Miguel Valente
相关产品推荐
相关产品推荐

