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

如何连接并使用aiogram与telethon库解决事件循环错误

问题描述

开发Telegram Bot时,需要部分消息通过Telethon Client发送,部分通过Aiogram发送,但运行时触发如下错误:

RuntimeError: The asyncio event loop must not change after connection (see the FAQ for details)

尝试的代码实现:

bot = Bot(token=bot_token)
dp = Dispatcher()
client = TelegramClient("session", api_id, api_hash).start(bot_token=bot_token)


@dp.message(CommandStart())
async def start(message: types.Message):
    await message.answer("text aiogram")
    await client_send(message)


async def client_send(message: types.Message):
    async with client:
        await client.send_message(message.chat.id, "text telethon")


async def main():
    await dp.start_polling(bot)

if __name__ == '__main__':
    asyncio.run(main())

关键报错栈信息:

RuntimeError: The asyncio event loop must not change after connection (see the FAQ for details)
...
File "testcode.py", line 23, in client_send
    async with client:
...
File "telethon\client\users.py", line 34, in _call
    raise RuntimeError('The asyncio event loop must not change after connection (see the FAQ for details)')
解决方案

错误根源

  1. client.start()是异步方法,直接同步调用会导致Telethon客户端在错误的事件循环中完成初始化
  2. client_send函数中用async with client会重复尝试启动客户端,此时客户端已在其他循环中建立连接,引发事件循环不匹配的错误

修复后的代码

import asyncio
from aiogram import Bot, Dispatcher, types
from aiogram.filters.command import CommandStart
from telethon import TelegramClient

# 替换为你的实际参数
bot_token = "YOUR_BOT_TOKEN"
api_id = YOUR_API_ID
api_hash = "YOUR_API_HASH"

bot = Bot(token=bot_token)
dp = Dispatcher()
# 先初始化Telethon客户端,暂不启动
client = TelegramClient("session", api_id, api_hash)

@dp.message(CommandStart())
async def start(message: types.Message):
    await message.answer("text aiogram")
    # 直接使用已启动的客户端发送消息
    await client.send_message(message.chat.id, "text telethon")

async def main():
    # 在同一个事件循环中启动Telethon客户端和Aiogram服务
    await client.start(bot_token=bot_token)
    await dp.start_polling(bot)

if __name__ == '__main__':
    asyncio.run(main())

注意事项

  • client.start()只需调用一次,客户端会保持在线状态,无需每次发送消息都重新启动
  • 确保所有异步操作都在asyncio.run()启动的同一个事件循环中执行,避免跨循环操作
  • 验证api_id、api_hash与bot token属于同一Telegram开发者账号

内容的提问来源于stack exchange,提问作者Artyxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 21:42:47