同步项目中Telethon触发There is no current event loop in thread错误求助
问题解决建议
错误原因
你从telethon.sync导入的TelegramClient本质是对异步API的同步封装,它依赖asyncio事件循环执行底层操作。单独运行时主线程会自动创建事件循环,但消息处理器函数由bot框架在独立线程中调用,这个线程默认未初始化asyncio事件循环,因此触发"There is no current event loop in thread"错误。
解决方案
方案1:手动为处理器线程创建事件循环
修改create_chat函数,在创建客户端前检查并初始化当前线程的事件循环:
import asyncio from telethon import functions from telethon.sync import TelegramClient def create_chat(): # 初始化当前线程的事件循环 try: loop = asyncio.get_running_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) with TelegramClient('chat', API_ID, API_HASH) as client: result_chat_creating = client( functions.messages.CreateChatRequest(users=[USERNAME, BOT_NAME], title='title'))
方案2:统一使用异步调用(推荐)
如果你的bot框架支持异步(如python-telegram-bot v13+),建议直接使用Telethon的异步API,避免线程与事件循环冲突:
from telethon import functions from telethon import TelegramClient # 不使用sync版本 async def create_chat(): async with TelegramClient('chat', API_ID, API_HASH) as client: result_chat_creating = await client( functions.messages.CreateChatRequest(users=[USERNAME, BOT_NAME], title='title')) # 将处理器改为异步函数 async def handle_message_to_support(message: Message): await create_chat() # 注册异步处理器(确保bot框架支持异步调用) bot.register_message_handler( handle_message_to_support )
额外注意事项
- 确保
API_ID、API_HASH、USERNAME、BOT_NAME等变量已正确赋值,且Telethon的session文件(chat.session)具备读写权限。 - 若使用方案2,需确认bot框架已配置为异步运行(如python-telegram-bot需用
asyncio.run(bot.polling())启动)。
内容的提问来源于stack exchange,提问作者Alexandra
相关产品推荐
相关产品推荐

