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

使用asyncio、aiosqlite与Telethon时遭遇RuntimeError(无运行事件循环)的问题求助

asyncio、aiosqlite与Telethon时遭遇RuntimeError(无运行事件循环)的问题求助

我的代码:

from telethon import TelegramClient, sync, events
import asyncio
import aiosqlite

api_id = 111111
api_hash = "sksk9449"

client = TelegramClient("main_session", api_id, api_hash)

bot_id = 12345
chat_id = -1234567

async def aiosqlite_connect_db():
    return await aiosqlite.connect("DataBase.db")


@client.on(events.NewMessage(chat_id))
async def normal_handler(event):
    user_id = event.message.to_dict()['from_id']['user_id']
    if user_id == bot_id:
        print(True)

client.start()

db = asyncio.run(aiosqlite_connect_db())

client.run_until_disconnected()

错误信息:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/telethon/helpers.py", line 430, in get_running_loop
    return asyncio.get_running_loop()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 27, in <module>
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/telethon/client/updates.py", line 93, in run_until_disconnected
    if self.loop.is_running():
       ^^^^^^^^^
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/telethon/client/telegrambaseclient.py", line 487, in loop
    return helpers.get_running_loop()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/site-packages/telethon/helpers.py", line 432, in get_running_loop
    return asyncio.get_event_loop_policy().get_event_loop()
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.11/asyncio/events.py", line 677, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.

我把代码里的一些敏感信息替换成了随机的数字和字母。

我感觉问题出在asyncio这块,想请教下怎么解决这个问题?另外,启动异步函数一定要用asyncio吗?有没有其他替代方案?

我之前试过创建并启用新的线程,但没起到作用。

备注:内容来源于stack exchange,提问作者袘芯谐写邪薪

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 17:37:56