Run multiple telethon clients

I'm trying to listen to multiple telethon clients. But when I run the application, I dont't get errors, but I also don't recieve any updates, if I run without asyncio just receiver.run_until_disconnected() everything works fine, but only one client works.

I do it such a way, entry point:

application = App(MAIN_SETTINGS_PATH)


if __name__ == '__main__':
    asyncio.run(application.start())

application:

class App:

    def __init__(self, settings_path: str):
        self.common_settings = Settings.load(settings_path)

        self.workers = [
            Receiver(ReceiverSettings(self.common_settings)),
        ]

    async def start(self):
        await asyncio.gather(
             *[worker.client.run_until_disconnected() for worker in self.workers]
        )

Worker:

class Receiver(BaseClient):
    EVENTS = {
        'test2': events.NewMessage()
    }

    def __init__(self, receiver_settings: ReceiverSettings):
        self._settings = receiver_settings

        super().__init__(
            TelegramClient(
                self._settings.session_name,
                self._settings.api_id,
                self._settings.api_hash
            )
        )

    @staticmethod
    async def test2(event: events.NewMessage.Event) -> None:
        print(event)

class BaseClient:
    EVENTS: Mapping[str, EventBuilder] = {}

    def __init__(self, client: TelegramClient):
        self.client = client
        self.client.start()

        self._register_events()

    def _register_events(self) -> None:
        for function_name, event in self.EVENTS.items():
            self.client.add_event_handler(getattr(self, function_name), event)

I tried to run clients without any class wrappers, but it also doesn't work:

receiver = TelegramClient('receiver', api_id, api_hash)
sender = TelegramClient('sender', api_id, api_hash)

@receiver.on(events.NewMessage())
async def test2(event):
     await event.reply('test2!')

@sender.on(events.NewMessage())
async def test2(event):
    await event.reply('test2!')

receiver.start()
sender.start(bot_token=bot_token)

async def main():
    return await asyncio.gather(
        receiver._run_until_disconnected(),
        sender._run_until_disconnected()
    )

asyncio.run(main())

Upvotes: 1

Views: 1121

Answers (1)

I found a solution. The problem was that tg connection and application starting occured in another event loop. This changes helped me:

if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    application = App(MAIN_SETTINGS_PATH)

    loop.run_until_complete(application.start())

 async def start(self):
        await asyncio.gather(
             *[worker.client.disconnected for worker in self.workers]
        )

Upvotes: 1

Related Questions