我愿意根据时间使用电传子发送一些消息,我的方法是编写一个函数并在一个新线程中启动它,并检查我每秒钟要发送哪些消息。例如,如下所示:
async def function():
while True:
time = datetime.datetime.now()
await send_some_messages(time)
但是电传需要我在它运行的同样的回路上等待。我知道我可以用client.run_until_disconnected()
获得当前循环,但我很困惑如何做到这一点。
如果您能给我一种在不同线程中运行此函数的方法,但仍然能够使用telethon客户端发送消息,那就太好了。
发布于 2020-04-04 07:57:23
您在使用asyncio
时不需要使用线程,也不必使用client.run_until_disconnected()
。所做的就是让事件循环继续运行,直到客户端断开为止。只要您运行事件循环,Telethon就能正常工作。
# 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简介
不用说,有更好的方法来检查何时是发送消息的时间(使用堆和事件,直到下一次到期或另一次最大时间,而不仅仅是一秒钟),但这应该会让您开始工作。
发布于 2022-09-12 11:12:46
如果您需要同时使用handler
和main
函数,请执行如下操作:
# 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()
https://stackoverflow.com/questions/61022878
复制相似问题