Search code examples
pythonconnectiontelegramtelethon

Cannot send requests while disconnected


I'm trying to connect account to telethon to collect messages from different channels.

If I use

with TelegramClient('name', api_id, api_hash, system_version="4.16.30-vxCUSTOM") as client:
    ...
    @client.on(events.NewMessage(chats=list_channels))  # all channels id
    async def normal_handler(event):
        ...
    client.run_until_disconnected()

then everything works well.But if I create an Account class (i need to connect 2 accounts later), then it raises ConnectionError: Cannot send requests while disconnected on self.client.run_until_disconnected()

my class:

class Account:
    def __init__(self, acc):
        self.client = TelegramClient(acc['name'], acc['api_id'], acc['api_hash'])
        self.client.run_until_disconnected()

    def run(self):
        @self.client.on(events.NewMessage(chats=list_channels))  # all channels id
        async def my_event_handler(event):
            ...

Solution

  • You have to start/connect the client before using run_until_disconnected().

    self.client = TelegramClient(...).start()