需要在 Python 上使用 telethon 同时解析两个会话
Need to parse two sessions at the same time with telethon on Python
我在使用 telethon 同时解析两个或多个会话时遇到了一些麻烦。我试过这个:
class NewSession:
def __init__(self, session_name):
self.client = TelegramClient(session_name, api_id, api_hash)
self.session_name = session_name
async def pool(self):
print("working with:", self.session_name)
@self.client.on(events.NewMessage(outgoing=True))
async def main(event):
message = event.message.to_dict()
msg_text = message['message']
print(msg_text)
try:
await self.client.start()
await self.client.run_until_disconnected()
finally:
await self.client.disconnect()
async def main():
user = NewSession("321")
user2 = NewSession("123")
await user.pool()
await user2.pool()
if __name__ == '__main__':
asyncio.run(main())
但只有一个在工作。需要帮助:)
问题出在您的 main
函数中。当您 await
将协程设为 return 时,并不意味着执行会继续到下一个表达式。因此,在您的代码中,仅当 user.poll()
协程 return 是一个值时,才会执行行 await user2.pool()
,这是会话“321”断开连接时。
您需要运行 任务并发;你可以使用函数asyncio.gather。重做你的 main
:
async def main():
user = NewSession("321")
user2 = NewSession("123")
await asyncio.gather(user.pool(), user2.pool())
我在使用 telethon 同时解析两个或多个会话时遇到了一些麻烦。我试过这个:
class NewSession:
def __init__(self, session_name):
self.client = TelegramClient(session_name, api_id, api_hash)
self.session_name = session_name
async def pool(self):
print("working with:", self.session_name)
@self.client.on(events.NewMessage(outgoing=True))
async def main(event):
message = event.message.to_dict()
msg_text = message['message']
print(msg_text)
try:
await self.client.start()
await self.client.run_until_disconnected()
finally:
await self.client.disconnect()
async def main():
user = NewSession("321")
user2 = NewSession("123")
await user.pool()
await user2.pool()
if __name__ == '__main__':
asyncio.run(main())
但只有一个在工作。需要帮助:)
问题出在您的 main
函数中。当您 await
将协程设为 return 时,并不意味着执行会继续到下一个表达式。因此,在您的代码中,仅当 user.poll()
协程 return 是一个值时,才会执行行 await user2.pool()
,这是会话“321”断开连接时。
您需要运行 任务并发;你可以使用函数asyncio.gather。重做你的 main
:
async def main():
user = NewSession("321")
user2 = NewSession("123")
await asyncio.gather(user.pool(), user2.pool())