"async with" 如果事件循环是 运行 但没有事件循环

"async with" if the event loop is running but no event loop

我在尝试 运行 Telethon documentation 提供的这个基本代码时收到以下错误。我很困惑为什么我还没有建立循环。

RuntimeError: You must use "async with" if the event loop is running (i.e. you are inside an "async def")

我在 spyder 4.0.1

中使用 python 3.7.7
from telethon.sync import TelegramClient
from telethon import functions, types

def channel_info(username, api_id, api_hash):
    with TelegramClient(username, api_id, api_hash,channel) as client:
        result = client(functions.channels.GetFullChannelRequest(
            channel=channel
        ))
        return(result)

out = channel_info(username, api_id, api_hash)

根据 telethon 文档的 FAQ section

Can I use Anaconda/Spyder/IPython with the library?

Yes, but these interpreters run the asyncio event loop implicitly, which interferes with the telethon.sync magic module. If you use them, you should not import sync.

所以避免使用 sync 模块。

您可以尝试这样做:

from telethon import TelegramClient, functions, types
from asyncio import run

API_ID= ...
API_HASH=" ... "

async def channel_info(username, api_id, api_hash):
    async with TelegramClient('session', api_id, api_hash) as client:
        result = await client(functions.channels.GetFullChannelRequest(
            channel=username
        ))
        return(result)


out = run(channel_info('durov', API_ID, API_HASH))
print(out)