Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

telegram-export

БесплатноБез исполняемых скриптовНе проверен

Exports and downloads Telegram chats, media, and channel content. Use when a user asks to export Telegram chat history, download media from Telegram channels…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

telegram-export

Overview

Export messages, media, and data from Telegram chats, groups, and channels. This skill covers two approaches: Telegram Desktop's built-in export (GUI, good for personal use) and Telethon (Python library for programmatic access through Telegram's MTProto API, signed in as your own account). Use cases range from personal chat backups to bulk media download from channels to data analysis of group conversations.

Instructions

Step 1: Get Telegram API Credentials

All programmatic approaches require API credentials from Telegram.

  1. Go to https://my.telegram.org and log in with your phone number.
  2. Click "API development tools."
  3. Create a new application — fill in app title and short name (anything works).
  4. Save your api_id (integer) and api_hash (string).

The credentials are free and tied to your Telegram account: one api_id per phone number. The api_hash is a secret that Telegram does not let you revoke, so keep both in environment variables (TELEGRAM_API_ID, TELEGRAM_API_HASH), never in a script.

Step 2: Install Telethon

Telethon is the most popular Python library for Telegram's MTProto API. The 1.x line (1.45.0, September 2026) is in maintenance mode but still follows Telegram's API changes. Its GitHub repository was archived in February 2026; the source now lives on Codeberg.

python3 -m venv .venv && source .venv/bin/activate   # Debian/Ubuntu refuse pip outside a virtual environment
pip install telethon cryptg
python -c "import telethon; print(telethon.__version__)"

cryptg is optional: it does the encryption in C instead of Python, which is what makes large media downloads fast.

Step 3: Basic Client Setup

# tg_login.py — sign in once; later runs reuse archive.session
import asyncio, os
from telethon import TelegramClient

API_ID = int(os.environ["TELEGRAM_API_ID"])
API_HASH = os.environ["TELEGRAM_API_HASH"]

async def main():
    # "archive" is the session name: auth is stored in archive.session
    async with TelegramClient("archive", API_ID, API_HASH) as client:
        me = await client.get_me()
        print(f"Logged in as {me.first_name} (ID: {me.id})")

asyncio.run(main())

On first run, Telethon prompts for your phone number, the verification code Telegram sends you, and the two-step verification password if one is set. After that, archive.session stores the auth key — no re-login needed as long as the script runs from the same directory. Never name a script telethon.py: it shadows the library.

Step 4: List Available Chats and Channels

Public chats can be addressed by username ("@telegram") or t.me link. Private groups have neither: take their ID from this listing and pass it as an integer.

# list_chats.py — every chat, group and channel of the account
import asyncio, os
from telethon import TelegramClient

async def main():
    async with TelegramClient("archive", int(os.environ["TELEGRAM_API_ID"]), os.environ["TELEGRAM_API_HASH"]) as client:
        async for dialog in client.iter_dialogs():
            # supergroups are both is_group and is_channel, so test is_group first
            kind = "Group" if dialog.is_group else "Channel" if dialog.is_channel else "User"
            print(f"[{kind}] {dialog.name} | ID: {dialog.id}")

asyncio.run(main())

Step 5: Export Chat Messages

# export_messages.py — write every message of a chat to JSON Lines, oldest first
# usage: python export_messages.py @telegram telegram_news.jsonl
import asyncio, json, os, sys
from telethon import TelegramClient

def media_kind(msg):
    for kind in ("photo", "video", "voice", "audio", "document"):
        if getattr(msg, kind):
            return kind
    return None

async def export_chat(chat, output_file):
    chat = int(chat) if chat.lstrip("-").isdigit() else chat
    count = 0
    async with TelegramClient("archive", int(os.environ["TELEGRAM_API_ID"]), os.environ["TELEGRAM_API_HASH"]) as client:
        with open(output_file, "w", encoding="utf-8") as f:
            # reverse=True yields oldest first; the default is newest first
            async for msg in client.iter_messages(chat, reverse=True):
                record = {
                    "id": msg.id,
                    "date": msg.date.isoformat(),
                    "sender_id": msg.sender_id,
                    "text": msg.raw_text or "",       # msg.text would add Markdown markup
                    "reply_to": msg.reply_to_msg_id,
                    "views": msg.views,
                    "forwards": msg.forwards,
                    "media": media_kind(msg),
                    "file_name": msg.file.name if msg.file else None,
                }
                f.write(json.dumps(record, ensure_ascii=False) + "\n")
                count += 1
    print(f"Exported {count} messages to {output_file}")

asyncio.run(export_chat(sys.argv[1], sys.argv[2]))

Writing one JSON object per line keeps memory flat on cha

Полный SKILL.md на GitHub

Установить telegram-export в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл telegram-export?

Exports and downloads Telegram chats, media, and channel content. Use when a user asks to export Telegram chat history, download media from Telegram channels or groups, archive Telegram conversations, backup Telegram messages, extract images, videos or links from Telegram, bulk download from Telegram channels, or migrate Telegram data. Covers Telegram Desktop's built-in export and Python scripts built on the Telethon library.

Как установить скилл telegram-export?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл telegram-export запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить telegram-export с