我需要使用 telethon 运行多个 Telegram 帐户(所有帐户都使用相同的消息处理程序)。 确切地说,我需要:
- 运行一个函数(每个帐户一次)
- 运行处理程序(永远)
这就是现在的代码,我只需要在多个客户端上运行它。我有一个帐户列表,我必须使用它。
async def main(client):
me = await client.get_me()
print("Working with", me.first_name)
await client.send_message("@example", "example")
client = TelegramClient(f'telegram_session', account["API_ID"], account["API_HASH"])
client.add_event_handler(handler, events.NewMessage())
with client:
client.start()
client.loop.run_until_complete(main(client))
client.run_until_disconnected()
最佳答案
你可以做这样的事情。
def get_or_create_eventloop():
try:
return asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop()
def run(account):
loop = get_or_create_eventloop()
future = asyncio.ensure_future(work(account))
loop.run_until_complete(future)
accounts= [dict(session = 'user1', api_id=api_id, api_hash=api_hash)]
for account in accounts:
threading.Thread(target = run, args = [account ]).start()
关于python - 如何使用马拉松比赛运行多个 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69055475/