【发布时间】:2020-12-12 19:36:48
【问题描述】:
我想在多线程、多线程中运行 Telethon 事件。
对于下面的代码,我期望的是多线程、并发的独立事件。 await asyncio.sleep( 3 ) 将休眠 3 秒。因此,如果您在电报上向该帐户发送任何文本,它将等待 3 秒,然后给我发回“嗨”。我预计如果我一次发送多个文本,比如说 5 次,它应该等待大约 3 秒,然后立即给我发送“hi”,但不像等待 3 秒,发送“hi”,等待 3 秒,发送“嗨”。 .. 5 次,大约需要 15 秒。这不是我所期望的。
那么,如何修改代码以按预期运行代码?还是在电视马拉松上是不可能的?
我阅读了 google、stackoverflow、github 问题,但我自己找不到解决方案。所以我在这里需要你的帮助。谢谢。
import time
from pathlib import Path
import re
import random
import asyncio
from telethon import TelegramClient, events
from telethon.sessions import StringSession
from telethon import utils
import logging
logging.basicConfig(level=logging.ERROR)
api_id = ""
api_hash = ''
phone = ''
string = Path('./string').read_text()
message = "hi."
if __name__ == '__main__':
client = TelegramClient(StringSession(string), api_id, api_hash, sequential_updates=True)
@client.on(events.NewMessage(incoming=True))
async def handle_new_message(event):
print('message:', event.message.message)
# // not working here, the sleep blocks next events but not only current event.
print('wait for 3 seconds...')
await asyncio.sleep( 3 )
await event.respond(message)
print('Auto-replying...')
client.start(phone)
client.run_until_disconnected()
# client.loop.run_forever()
# string = StringSession.save(client.session)
# Path('./string').write_text(string)
【问题讨论】:
-
@TheKill-996 你的意思是代码按预期工作?我的 python 版本是 3.6.7,而 Telethon==1.18.2,告诉我,你的版本是什么?谢谢。
-
FWIW Telethon 不是多线程的,它只是默认使用多个任务来处理更新。
标签: python-3.x python-asyncio telethon