skip to Main Content

I need to run multiple Telegram accounts (that all use the same message handler) using telethon.
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()

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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() 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search