首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何与telethon客户端一起运行线程

如何与telethon客户端一起运行线程
EN

Stack Overflow用户
提问于 2020-04-04 01:55:24
回答 2查看 5.1K关注 0票数 4

我愿意根据时间使用电传子发送一些消息,我的方法是编写一个函数并在一个新线程中启动它,并检查我每秒钟要发送哪些消息。例如,如下所示:

代码语言:javascript
运行
复制
async def function():
  while True:
    time = datetime.datetime.now()
    await send_some_messages(time)

但是电传需要我在它运行的同样的回路上等待。我知道我可以用client.run_until_disconnected()获得当前循环,但我很困惑如何做到这一点。

如果您能给我一种在不同线程中运行此函数的方法,但仍然能够使用telethon客户端发送消息,那就太好了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-04-04 07:57:23

您在使用asyncio时不需要使用线程,也不必使用client.run_until_disconnected()。所做的就是让事件循环继续运行,直到客户端断开为止。只要您运行事件循环,Telethon就能正常工作。

代码语言:javascript
运行
复制
# Create client
client = ...

# Do whatever with the client
@client.on(...)
async def handler(event):
    ...

async def main():
    while True:
        # Do whatever (check if now is time to send messages, for example)
        ...

        # Yielding control back to the event loop here (with `await`) is key.
        # We're giving an entire second to it to do anything it needs like
        # handling updates, performing I/O, etc.
        await asyncio.sleep(1)

client.loop.run_until_complete(main())

保持事件循环运行的其他方法是使用loop.run_forever,不要忘记可以使用asyncio.create_task或等待其中的许多方法(…)我鼓励您阅读asyncio文档。就像threading一样,这些文档值得检查以学习如何使用它。

另外,如果您确实需要线程(例如,您正在做CPU密集型工作),asyncio也会保护您。但这些都不是特蕾森特有的。

如果您想更好地了解asyncio是如何工作的(也许这对您有帮助),请参阅Asyncio简介

不用说,有更好的方法来检查何时是发送消息的时间(使用堆和事件,直到下一次到期或另一次最大时间,而不仅仅是一秒钟),但这应该会让您开始工作。

票数 7
EN

Stack Overflow用户

发布于 2022-09-12 11:12:46

断开()块!

如果您需要同时使用handlermain函数,请执行如下操作:

代码语言:javascript
运行
复制
# Get event loop
loop = asyncio.get_event_loop() 

# Create client
client = TelegramClient(..., loop=loop)
client.start()

# Do whatever with the client
@client.on(...)
async def handler(event):
    ...

async def main():
    while True:
        # Do whatever (check if now is time to send messages, for example)
        ...

        # Yielding control back to the event loop here (with `await`) is key.
        # We're giving an entire second to it to do anything it needs like
        # handling updates, performing I/O, etc.
        await asyncio.sleep(1)

loop.create_task(main())

client.run_until_disconnected()
loop.close()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61022878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档