Search code examples
pythontelegramtelegram-botpyrogram

How to run multiple clients (my_account, my_bot) at the same time on pyrogram


I'm having trouble with running both 'my_account' and 'my_bot' at the same time. I need to do some tasks with Client('my_account') class and automatic reply to commands with Client('my_bot') class.

I've tried so many ways, but no results. Here is my code.

import asyncio
from pyrogram.handlers.message_handler import MessageHandler

from pyrogram import Client, compose

api_id = 12345678
api_hash = "1234567891a23456b7891234cde5f67f"
bot_token = "1234567891:ABCD1EFG234HI5jKL6MNopqRSt7UVwXyz8A"


async def dummy(client, message):
    await message.reply("heeloo")


async def main():
    apps = [
        Client("my_account", api_id=api_id, api_hash=api_hash),
        Client("my_bot", api_id=api_id, bot_token=bot_token)
    ]
    await compose(apps)

    apps[0].add_handler(MessageHandler(dummy))


if __name__ == "__main__":
    asyncio.run(main())


Solution

  • In your code, you are adding the handler after calling compose, so it’ll never be added since compose blocks. Adding the handlers before the compose call should fix the problem:

    async def main():
        apps = [
            Client("my_account", api_id=api_id, api_hash=api_hash),
            Client("my_bot", api_id=api_id, bot_token=bot_token)
        ]
    
        apps[0].add_handler(MessageHandler(dummy))
    
        await compose(apps)