Telethon 版本 1.11.3 与 python 3.7.3 似乎不起作用

Pus*_*kar 3 python telegram telethon

在 Telethon 1.11.3 、 python 3.7.3 上尝试以下代码后

from telethon import TelegramClient

api_id = xxx #i give my id
api_hash = xxx##i give my 
client = TelegramClient(name, api_id, api_hash)

async def main():

    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello to myself!')

with client:
    client.loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)

我收到错误 RuntimeError: You Must use "async with" 如果事件循环正在运行(即您位于“async def”内部)

The*_*996 6

问题不在于代码本身,而在于您使用的 shell。IPython 和类似的运行asyncio事件循环打破了 Telethon 的sync魔力。

要解决此问题,您可以使用普通pythonshell 或在正确的位置编写async和:await

from telethon import TelegramClient

api_id = ...
api_hash = ...
client = TelegramClient(name, api_id, api_hash)

async def main():
    # Now you can use all client methods listed below, like for example...
    await client.send_message('me', 'Hello to myself!')

# Note the async and await keywords
async with client:
    await main()
Run Code Online (Sandbox Code Playgroud)

当然,在这种情况下,main()也没有必要:

async with client:
    await client.send_message('me', 'Hello to myself!')
Run Code Online (Sandbox Code Playgroud)