telegram-export

导出并下载 Telegram 聊天记录、媒体文件和频道内容,适用于导出聊天历史、从频道或群组批量下载媒体、归档对话、备份消息、提取图片或视频、迁移数据等。涵盖使用 Telegram Desktop 导出、基于 Telethon 的脚本以及 TDLib 方法。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "telegram-export":https://skillpi.com/zh/skills/deepskill-52e830bc7a506b7e5481e1dddd2f3bef07f69553c62ccef8ec0155d4a4111503。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

导出并下载 Telegram 聊天记录、媒体文件和频道内容,适用于导出聊天历史、从频道或群组批量下载媒体、归档对话、备份消息、提取图片或视频、迁移数据等。涵盖使用 Telegram Desktop 导出、基于 Telethon 的脚本以及 TDLib 方法。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

软件、账号及付费要求
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: telegram-export
description: >-
  Export and download 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 or videos from Telegram, bulk download from Telegram channels,
  scrape Telegram content, or migrate Telegram data. Covers Telegram Desktop
  export, Telethon-based scripting, and TDLib approaches.
license: Apache-2.0
compatibility: 'Python 3.8+ with Telethon, or Telegram Desktop (Linux, macOS, Windows)'
metadata:
  author: terminal-skills
  version: 1.0.0
  category: content
  tags:
    - telegram
    - export
    - download
    - chat
    - media
    - archive
    - backup

telegram-export

Overview

Export messages, media, and data from Telegram chats, groups, and channels. This skill covers three approaches: Telegram Desktop's built-in export (GUI, good for personal use), Telethon (Python library for programmatic access), and channel scraping for public content. 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/auth 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).

These credentials are free, permanent, and tied to your Telegram account.

Step 2: Install Telethon

Telethon is the most popular Python library for Telegram's MTProto API.

pip install telethon

# Optional: for media processing
pip install pillow cryptg    # cryptg speeds up encryption 2-3x

Step 3: Basic Client Setup

# telegram_client.py — Telethon client initialization and authentication
from telethon import TelegramClient
import asyncio

api_id = 12345678           # your api_id from my.telegram.org
api_hash = "your_api_hash"  # your api_hash

async def main():
    # Session file stores auth — you only log in once
    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()     # prompts for phone + code on first run

    me = await client.get_me()
    print(f"Logged in as {me.first_name} (ID: {me.id})")

    await client.disconnect()

asyncio.run(main())

On first run, Telethon prompts for your phone number and the verification code Telegram sends you. After that, the session file (my_session.session) stores the auth token — no re-login needed.

Step 4: Export Chat Messages

# export_messages.py — Export all messages from a chat to JSON
from telethon import TelegramClient
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument
import asyncio
import json
from datetime import datetime

api_id = 12345678
api_hash = "your_api_hash"

async def export_chat(chat_name, output_file="messages.json"):
    """
    Export all messages from a chat/group/channel to JSON.

    Args:
        chat_name: Username, invite link, or chat title to export
        output_file: Path for the JSON output file
    """
    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()

    entity = await client.get_entity(chat_name)
    messages = []

    async for msg in client.iter_messages(entity, limit=None):
        message_data = {
            "id": msg.id,
            "date": msg.date.isoformat(),
            "sender_id": msg.sender_id,
            "text": msg.text or "",
            "reply_to": msg.reply_to_msg_id if msg.reply_to else None,
            "forwards": msg.forwards,
            "views": msg.views,
        }

        # Classify media type
        if msg.media:
            if isinstance(msg.media, MessageMediaPhoto):
                message_data["media_type"] = "photo"
            elif isinstance(msg.media, MessageMediaDocument):
                mime = msg.media.document.mime_type
                if mime.startswith("video"):
                    message_data["media_type"] = "video"
                elif mime.startswith("audio"):
                    message_data["media_type"] = "audio"
                else:
                    message_data["media_type"] = "document"
                message_data["mime_type"] = mime

        messages.append(message_data)

    # Chronological order (oldest first)
    messages.reverse()

    with open(output_file, "w", encoding="utf-8") as f:
        json.dump(messages, f, ensure_ascii=False, indent=2)

    print(f"Exported {len(messages)} messages to {output_file}")
    await client.disconnect()

asyncio.run(export_chat("@channel_username"))

Step 5: Download Media from Chats and Channels

# download_media.py — Download all media (photos, videos, documents) from a chat
from telethon import TelegramClient
from telethon.tl.types import MessageMediaPhoto, MessageMediaDocument
import asyncio
import os

api_id = 12345678
api_hash = "your_api_hash"

async def download_media(chat_name, output_dir="./media", media_types=None):
    """
    Download media files from a Telegram chat, group, or channel.

    Args:
        chat_name: Username (@channel), invite link, or chat title
        output_dir: Directory to save downloaded files
        media_types: List of types to download: 'photo', 'video', 'audio', 'document'
                     None means download everything
    """
    if media_types is None:
        media_types = ["photo", "video", "audio", "document"]

    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()

    entity = await client.get_entity(chat_name)
    os.makedirs(output_dir, exist_ok=True)

    count = 0
    async for msg in client.iter_messages(entity, limit=None):
        if not msg.media:
            continue

        # Determine media type
        if isinstance(msg.media, MessageMediaPhoto) and "photo" in media_types:
            path = await msg.download_media(file=output_dir)
            count += 1
        elif isinstance(msg.media, MessageMediaDocument):
            mime = msg.media.document.mime_type
            if mime.startswith("video") and "video" in media_types:
                path = await msg.download_media(file=output_dir)
                count += 1
            elif mime.startswith("audio") and "audio" in media_types:
                path = await msg.download_media(file=output_dir)
                count += 1
            elif "document" in media_types:
                path = await msg.download_media(file=output_dir)
                count += 1

        if count % 50 == 0 and count > 0:
            print(f"Downloaded {count} files...")

    print(f"Done! Downloaded {count} files to {output_dir}")
    await client.disconnect()

# Download only photos and videos from a channel
asyncio.run(download_media("@channel_name", media_types=["photo", "video"]))

Step 6: Download with Date Filtering and Progress

# download_filtered.py — Download media with date range and progress tracking
from telethon import TelegramClient
import asyncio
from datetime import datetime, timezone

api_id = 12345678
api_hash = "your_api_hash"

async def download_date_range(chat_name, start_date, end_date, output_dir="./media"):
    """
    Download media from a specific date range.

    Args:
        chat_name: Chat/channel to download from
        start_date: Start of range (datetime)
        end_date: End of range (datetime)
        output_dir: Output directory
    """
    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()

    entity = await client.get_entity(chat_name)
    count = 0

    # offset_date is the upper bound — Telegram returns messages BEFORE this date
    async for msg in client.iter_messages(entity, offset_date=end_date, limit=None):
        if msg.date < start_date:
            break    # past our range, stop

        if msg.media:
            await msg.download_media(file=output_dir)
            count += 1
            print(f"[{count}] {msg.date.strftime('%Y-%m-%d %H:%M')} — downloaded")

    print(f"Downloaded {count} files from {start_date.date()} to {end_date.date()}")
    await client.disconnect()

# Download January 2025 media
asyncio.run(download_date_range(
    "@channel_name",
    start_date=datetime(2025, 1, 1, tzinfo=timezone.utc),
    end_date=datetime(2025, 2, 1, tzinfo=timezone.utc),
))

Step 7: Telegram Desktop Export (No Code)

Telegram Desktop has a built-in export feature — no API credentials or code needed.

  1. Open Telegram Desktop.
  2. Go to Settings → Advanced → Export Telegram data.
  3. Select what to export: messages, photos, videos, voice messages, stickers, etc.
  4. Choose format: HTML (human-readable) or JSON (machine-readable).
  5. Set file size limit and date range if needed.
  6. Click "Export" and wait.

The export creates a folder with result.json (or HTML files) and a files/ directory containing all media. This is the simplest approach for personal chat backups, but it cannot be automated or run headlessly.

Step 8: List Available Chats and Channels

# list_chats.py — List all chats, groups, and channels you're a member of
from telethon import TelegramClient
import asyncio

api_id = 12345678
api_hash = "your_api_hash"

async def list_dialogs():
    """List all conversations with message counts and types."""
    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()

    async for dialog in client.iter_dialogs():
        chat_type = "Channel" if dialog.is_channel else "Group" if dialog.is_group else "User"
        print(f"[{chat_type}] {dialog.name} | ID: {dialog.entity.id} | Messages: {dialog.message.id}")

    await client.disconnect()

asyncio.run(list_dialogs())

Step 9: Export Specific Message Types

# export_links.py — Extract all URLs shared in a chat
from telethon import TelegramClient
import asyncio
import re

api_id = 12345678
api_hash = "your_api_hash"

URL_PATTERN = re.compile(r'https?://[^\s<>"{}|\\^`\[\]]+')

async def extract_links(chat_name, output_file="links.txt"):
    """
    Extract all URLs from messages in a chat.

    Args:
        chat_name: Chat to scan for links
        output_file: File to save extracted URLs
    """
    client = TelegramClient("my_session", api_id, api_hash)
    await client.start()

    entity = await client.get_entity(chat_name)
    links = set()

    async for msg in client.iter_messages(entity, limit=None):
        if msg.text:
            found = URL_PATTERN.findall(msg.text)
            links.update(found)

    with open(output_file, "w") as f:
        for link in sorted(links):
            f.write(link + "\n")

    print(f"Extracted {len(links)} unique URLs to {output_file}")
    await client.disconnect()

asyncio.run(extract_links("@channel_name"))

Examples

Example 1: Archive an entire Telegram channel with all media

User prompt: "I want to download everything from a Telegram channel — all messages, photos, and videos. The channel has about 5,000 posts."

The agent will:

  1. Set up Telethon client with the user's API credentials.
  2. Run the media download script with limit=None to get all posts.
  3. Export messages to JSON in parallel for the text archive.
  4. Organize downloads by date: {channel_name}/{year}-{month}/ structure.
  5. The archive handles Telegram's rate limits automatically — Telethon manages flood waits internally.
  6. Report total files downloaded, disk usage, and message count.

Example 2: Extract all shared links from a group chat for research

User prompt: "My team shares a lot of articles in our Telegram group. Extract all URLs that have been shared in the last 6 months so I can build a reading list."

The agent will:

  1. Connect to the group using Telethon.
  2. Filter messages by date (last 6 months) and extract URLs using regex.
  3. Deduplicate URLs and optionally categorize by domain.
  4. Save the result as a clean text file with one URL per line.
  5. Report how many unique URLs were found across how many messages.

Guidelines

  • Always use Telethon over direct HTTP scraping — it uses Telegram's official MTProto protocol, respects rate limits automatically, and handles encryption properly.
  • Store API credentials in environment variables or a config file, never hardcode them in scripts that might be shared or committed.
  • Use iter_messages(limit=None) for full exports — Telethon handles pagination and rate limiting automatically. For very large channels (100K+ messages), add progress tracking.
  • Enable cryptg (pip install cryptg) for 2-3x faster encryption performance during large downloads.
  • Telegram Desktop export is the simplest option for one-time personal backups — no code, no API setup. Use Telethon when you need automation, filtering, or integration with other tools.
  • Respect rate limits — Telethon handles FloodWaitError automatically by sleeping, but downloading thousands of large files will take time. Plan for hours on large channels.

当前收录版本

1.0.0

核对来源版本 ↗

安全与评测信息

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供 Telegram 聊天记录、媒体、频道内容的多方式导出方案,满足个人备份、数据分析、内容归档等高频需求
  • 覆盖 GUI(Telegram Desktop)与代码(Telethon)两种路径,适配不同用户技术背景
触发精准95/100

亮点

  • 触发场景描述全面,涵盖导出、下载、归档、备份、提取、批量操作等核心用例
  • 明确区分不同技术方案(Desktop/Telethon/TDLib)的适用边界
结构规范95/100

待提升项

  • 缺少独立 When to Use 章节 原报告严重程度:轻微

    文档未设置显式的 When to Use 章节,尽管 frontmatter 和 overview 已包含触发说明

    改进建议:建议在 Overview 后增加独立 When to Use 章节以提升可读性

  • 未显式定义出口条件 原报告严重程度:轻微

    各脚本未明确说明成功/失败的标准输出或退出码

    改进建议:建议在关键脚本末尾添加明确的完成状态提示和错误码说明

亮点

  • 步骤划分清晰(Step 1-9),每步有具体目标和可执行代码
  • 提供完整端到端示例,帮助用户理解实际应用场景
执行可靠90/100

亮点

  • 工具来源明确(Telethon 官方库),参数说明完整
  • 自动处理 Telegram 速率限制(FloodWaitError),保障长时间任务稳定性
  • 建议将 API 凭据存储于环境变量,提升安全性
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

文档引用的域名或地址

这些地址可能用于文档链接或示例,不是已批准的联网清单。使用前核对实际目的地及发送的数据。

  • my.telegram.org

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

翻译待完成,请参阅来源文档。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。