如何 运行 与 telethon 客户端一起发帖
How to run a thread alongside telethon client
我愿意根据时间使用 telethon 发送一些消息,我的方法是编写一个函数并在新线程中启动它并检查我每秒必须发送哪些消息。即如下所示:
async def function():
while True:
time = datetime.datetime.now()
await send_some_messages(time)
但是电视节目需要我在 运行ning 的同一个循环中等待。我知道我可以用 client.run_until_disconnected()
获取当前循环,但我很困惑我该怎么做。
如果你能给我一个在不同线程中使用 运行 这个函数的方法,但仍然能够使用 telethon 客户端发送消息,那就太好了。
您在使用 asyncio
, and you also don't have to use client.run_until_disconnected()
时不需要使用线程。所做的只是保持事件循环 运行ning 直到客户端断开连接。只要你 运行 事件循环,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())
保持事件循环 运行ning 的其他方法是使用 loop.run_forever
, and don't forget you can asyncio.create_task
或等待其中的许多方法……我鼓励您阅读 asyncio
文档。就像 threading
一样,文档值得查看以了解如何使用它。
附带说明一下,如果您 确实 需要线程(例如,您正在进行 CPU 密集型工作),asyncio
也有您的背面覆盖。但是 none 这确实是 Telethon 特有的。
如果您想更好地了解 asyncio
的工作原理(也许对您有帮助),请参阅 An Introduction to Asyncio
不用说,有更好的方法来检查何时发送消息(使用堆和事件,休眠直到下一次到期或另一个最大值而不仅仅是一秒),但这应该让你开始了。
我愿意根据时间使用 telethon 发送一些消息,我的方法是编写一个函数并在新线程中启动它并检查我每秒必须发送哪些消息。即如下所示:
async def function():
while True:
time = datetime.datetime.now()
await send_some_messages(time)
但是电视节目需要我在 运行ning 的同一个循环中等待。我知道我可以用 client.run_until_disconnected()
获取当前循环,但我很困惑我该怎么做。
如果你能给我一个在不同线程中使用 运行 这个函数的方法,但仍然能够使用 telethon 客户端发送消息,那就太好了。
您在使用 asyncio
, and you also don't have to use client.run_until_disconnected()
时不需要使用线程。所做的只是保持事件循环 运行ning 直到客户端断开连接。只要你 运行 事件循环,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())
保持事件循环 运行ning 的其他方法是使用 loop.run_forever
, and don't forget you can asyncio.create_task
或等待其中的许多方法……我鼓励您阅读 asyncio
文档。就像 threading
一样,文档值得查看以了解如何使用它。
附带说明一下,如果您 确实 需要线程(例如,您正在进行 CPU 密集型工作),asyncio
也有您的背面覆盖。但是 none 这确实是 Telethon 特有的。
如果您想更好地了解 asyncio
的工作原理(也许对您有帮助),请参阅 An Introduction to Asyncio
不用说,有更好的方法来检查何时发送消息(使用堆和事件,休眠直到下一次到期或另一个最大值而不仅仅是一秒),但这应该让你开始了。