Telethon - How to get list of all channels a number is member of?

Viewed 2219

In my python project, using the telethon library, I need a list of the channels (it can include other types of chats, but I only need the channels) that my phone is a member of, regardless of if my number is an admin or not.

All the information I require is the ID and the title of the channels, is there a way to accomplish this? In the documentation I found the method GetChannelsRequest, but I have failed to instantiate it. I have tried this, but it is wrong, since I need a different data type, but I don't know how to work with this.

async def get_all_channels():
    try:
        me = await client.get_input_entity(await client.get_me())
        channels = await client(GetChannelsRequest(  # Expected type 'List[Union[InputChannelEmpty, InputChannel, InputChannelFromMessage]]'
            [await client.get_entity('me')]  # got 'Union[User, Chat, Channel]' instead
            # [await client.get_input_entity('me')]  # got 'Union[InputPeerEmpty, InputPeerSelf, InputPeerChat, InputPeerUser, InputPeerChannel, InputPeerUserFromMessage, InputPeerChannelFromMessage]' instead
        ))
    except:
        return traceback.format_exc()

I'm just starting to learn the library. Are the groups I'm a part of, if they're private, a problem to achieve this?

2 Answers

Loop over your chats with iter_dialogs() and check if the dialog is a channel with dialog.is_channel.

async for dialog in client.iter_dialogs():
    if dialog.is_channel:
        print(f'{dialog.id}:{dialog.title}')

I resolved list all channel and groups on this way:

async def main():
    client = TelegramClient(username, api_id, api_hash)
    await client.connect()
    print("---------Channels---------------")
    async for dialog in client.iter_dialogs():
        if dialog.is_channel:
            print(f'{dialog.id}:{dialog.title}')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
Related