telegram-export
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.
What this skill does
# 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.
```bash
pip install telethon
# Optional: for media processing
pip install pillow cryptg # cryptg speeds up encryption 2-3x
```
### Step 3: Basic Client Setup
```python
# 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
```python
# 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
```python
# 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
```python
# 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 expRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.