How to Export Telegram Groups and Channels via Telethon

Preface

A group friend said that after creating a new Telegram account, they didn't know how to add back the groups from their old account.

https://t.me/duangvpsfs/3769416

Approach

First, I asked GPT whether this was even possible.
Can a Telegram bot or Telethon query the groups and channels that a Telegram account has joined?
The conclusion is that Telethon can do it, and it provided some code.
GPT reply that telethon can query it, with sample code
from telethon import TelegramClient

client = TelegramClient('session_name', api_id, api_hash)

async def get_my_dialogs():
    await client.start()
    
    # 获取所有对话(包括群组、频道、私聊)
    async for dialog in client.iter_dialogs():
        if dialog.is_group:
            print(f"群组: {dialog.name}")
        elif dialog.is_channel:
            print(f"频道: {dialog.name}")

with client:
    client.loop.run_until_complete(get_my_dialogs())
GPT reply screenshot: this feature only allows querying your own account
I do have some programming ability, and of course I could tell that this code only outputs the names of groups and channels. More precisely, it should also output the usernames of groups and channels.
But, assuming I was just a non-programmer newbie, I would first try running this code to see what happens.

Debugging

I found a VPS (you can use your own computer too, as long as you have Python installed and have the GFW issue sorted out).
Save the code as a .py file and upload it. For example, the file name is tg-get-group-channel.py.
Then run it on the VPS, and there are some errors.
Running tg-get-group-channel.py in the terminal raises ModuleNotFoundError, telethon is missing
I copied and pasted the error to GPT, and the reply was:
Install the telethon module
Apply for an API
Modify the code
GPT reply: install telethon module, apply for API, modify code
from telethon import TelegramClient

# 填入你从 my.telegram.org 获取的信息
api_id = 12345  # 你的 api_id
api_hash = 'your_api_hash_here'  # 你的 api_hash

client = TelegramClient('session_name', api_id, api_hash)

async def get_my_dialogs():
    await client.start()
    
    async for dialog in client.iter_dialogs():
        if dialog.is_group:
            print(f"群组: {dialog.name}")
        elif dialog.is_channel:
            print(f"频道: {dialog.name}")

with client:
    client.loop.run_until_complete(get_my_dialogs())
An error occurred when installing telethon.
pip install telethon fails with pip command not found, prompting to install python3-pip
Thanks to myself for having pre-installed command-not-found.
I followed the prompt and first installed python3-pip, and then I was able to install telethon.
There was a new error.
pip install telethon fails with externally-managed-environment error
Since we're just running this experimentally, just install it directly with the --break-system-packages parameter.
pip install telethon --break-system-packages
Next, go apply for an API.
* Applying for an API has certain requirements for the access IP. You may succeed or fail. We'll skip the details here.
my.telegram.org App configuration page with red box around api_id and api_hash

Put the api_id and api_hash into the code and run it again.
It worked.
You need to enter the phone number, enter the Telegram verification code, and enter the password (if you set one).
The result looks like this.
Terminal running the script, which lists group and channel names after a successful login

This only gives the names of groups and channels, not the usernames.
So I made a request to GPT.
The output looks like this:
群组: test公开群
频道: 翻墙新手求助现场
群组: Joey Huang Blog
群组: ja-netfilter
群组: 折腾啥
群组: Trojan-Go使用与反馈

I need to add output of the usernames of the groups and channels.
The resulting updated code:
from telethon import TelegramClient

api_id = 12345
api_hash = 'your_api_hash_here'

client = TelegramClient('session_name', api_id, api_hash)

async def get_my_dialogs():
    await client.start()
    
    async for dialog in client.iter_dialogs():
        entity = dialog.entity
        username = f"@{entity.username}" if getattr(entity, 'username', None) else "私有"
        
        type_name = "群组" if dialog.is_group else "频道" if dialog.is_channel else "其他"
        
        if dialog.is_group or dialog.is_channel:
            print(f"{type_name}: {dialog.name} | {username}")

with client:
    client.loop.run_until_complete(get_my_dialogs())
Running result:
Group and channel list obtained after adding the output feature, including Nodeloc Monitor and others

Done.

It's already in a usable state.
If you find it troublesome to copy the text from the terminal interface, just ask GPT to add a feature to output to a file.

========

Github


========

Postscript

The GPT I used this time (2026-1-24) is

Claude has a feature to share the entire conversation.
https://claude.ai/share/5ab8d166-974f-44bc-af97-3d21be266fc8


Comments