python 如何在Google Colab上使用公益电视节目的NewMessage事件

nzk0hqpo  于 2023-02-11  发布在  Python
关注(0)|答案(1)|浏览(79)

我有这个代码,我想在谷歌colab上运行它。它在我的电脑上工作得很好,但在colab上我总是得到这样的错误:
语法错误:'async with'在异步函数外部

运行时错误:如果事件循环正在运行,则必须使用"async with"(即您在"async def"内部)
有时它不等待获得新消息,并且在一次运行之后完成。

import json
import time
import telethon as tlt
import asyncio
from telethon import events,TelegramClient

chat_name = "sample"

telegram_session="sample_1"
api_id = "0000000"
api_hash = ""

client = TelegramClient(None , api_id, api_hash)

@client.on(events.NewMessage(chats=chat_name))
async def handler(event):
    get_message = event.message.to_dict()
    get_message['date'] = get_message['date'].strftime("%Y-%m-%d %H:%M:%S")
    message_json = json.dumps(get_message)
    print(message_json)
      
      
async with client:
    client.run_until_disconnected()
ni65a41a

ni65a41a1#

您需要将async with放入async def中:

...

async def main():
    async with client:
        await client.run_until_disconnected()

client.loop.run_until_complete(main())

相关问题