简体   繁体   English

如何使用 Telethon 运行多个会话?

[英]How to run multiple sessions using telethon?

I need to run multiple Telegram accounts (that all use the same message handler) using telethon.我需要使用 Telethon 运行多个 Telegram 帐户(都使用相同的消息处理程序)。 Exactly, I need to:确切地说,我需要:

  • run a function (one time per account)运行一个函数(每个帐户一次)
  • run the handler (forever)运行处理程序(永远)

This is the code now, I just need to run it with more than one client.这是现在的代码,我只需要在多个客户端上运行它。 I have a list of accounts, and I must use that.我有一个帐户列表,我必须使用它。

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()

you can do something like this.你可以做这样的事情。

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() 

I have a quick look at the library you are using, it is based on asynio.我快速浏览了您正在使用的库,它基于 asynio。 I think you should to do something like this我认为你应该做这样的事情

  asyncio.wait([one_task(), two_task()])

PS i found answer here stackoverflow PS我在这里找到了答案stackoverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM