GitJorgo
GitJorgo

Reputation: 93

How to run multiple sessions using telethon?

I need to run multiple Telegram accounts (that all use the same message handler) using telethon. Exactly, I need to:

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

Upvotes: 2

Views: 3580

Answers (2)

Hamidreza
Hamidreza

Reputation: 746

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

Upvotes: 2

0xdeface
0xdeface

Reputation: 259

I have a quick look at the library you are using, it is based on asynio. I think you should to do something like this

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

P.S i found answer here stackoverflow

Upvotes: 0

Related Questions