【问题标题】:Running a loop while using telethon使用 Telethon 时运行循环
【发布时间】:2021-04-13 16:34:46
【问题描述】:

我正在制作一个需要循环检查频道的电报频道管理控制脚本。我还想要一些消息处理程序检查消息。这是我的代码的一部分:

async def main():
    while True:
        .... (some code)
        log=await client.get_admin_log(await client.get_entity(chat),limit=1)
        .... (some code here)
@client.on(telethon.events.NewMessage)
async def message_handler(m):
    .... (handle messages)
client.start()

如果我使用 client.loop.run_until_complete(main()),消息处理程序将无法工作,但 main 运行良好。如果我使用client.run_until_disconnected() 并使用另一个线程在另一个循环中运行main,它会停留在get_admin_log。现在我该怎么办? (当特定消息到达时,我尝试在消息处理程序中运行 main(我在运行时手动发送) .它运行 main 但不再处理消息)

【问题讨论】:

  • 尝试client.loop.create_task(main()),然后是client.run_until_disconnected()。这应该在同一个事件循环中运行,这就是你想要的。
  • 您应该在您的main 中添加一个await asyncio.sleep(10),以便让其他代码有机会运行。但是不要使用time.sleep

标签: python python-asyncio telethon


【解决方案1】:

尝试异步while,如果可能尝试使用另一个代码(不要使用while),因为它没有尽头。

【讨论】:

  • async while 不是有效的 Python 语法(至少目前还不是)。
猜你喜欢
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-22
相关资源
最近更新 更多