TeleHarvest
# TeleHarvest v2.0 — AI-Agent-Ready Telegram Scraper & Intelligence Suite
[](https://www.python.org/)
[](https://modelcontextprotocol.io/)
[](LICENSE)
**TeleHarvest v2.0** is a complete, security-hardened Telegram scraping, multimodal indexing (OCR + Voice Transcription), hybrid semantic search, channel network discovery, BI analytics, and export suite — built to be effortless for **both non-technical humans (1-Click Launch + Guided Simple/Pro TR/EN Web Dashboard)** and **AI Agents (18-Tool Native MCP Server + `SKILL.md` + `--json` CLI)**.
> Launch in 1 click (`./start.sh` on macOS/Linux, `start.bat` on Windows, or `uv run tgscrape start`) — or connect your AI agent and say: *"Inspect and scrape `@durov`, discover similar channels, and export BI metrics + Gephi graph."*
---
## Accountless vs. MTProto: What Works Without Logging In?
Telegram enforces strict protocol rules on what can be read anonymously:
| Target Type | Accountless (`t.me/s/`) | MTProto Login (`Telethon`) | Account Ban Risk |
|---|:---:|:---:|---|
| **Public Broadcast Channels** (e.g. `@telegram`) | **YES** (instant, no API keys) | **YES** (full history, comments, media) | **NONE** on `t.me/s/` |
| **Public Groups / Supergroups** (e.g. `@some_chat`) | **NO** *(Telegram never exposes group history on `t.me/s/`)* | **YES** (messages, topics, members, live) | **LOW** (safe preset) |
| **Private Channels & Private Groups** (`t.me/+...`) | **NO** | **YES** (any chat you are a member of) | **LOW** (safe preset) |
| **Similar Channels, Stories & Global Search** | **NO** | **YES** | **LOW** |
| **Live Real-Time Tracking (New / Edit / Delete)** | **NO** | **YES** | **LOW** |
Run `uv run tgscrape inspect <link>` anytime (or paste any link in the Web Home Smart Inspector) to check a target **without an account** before scraping!
---
## 1-Click Launch (Humans)
```bash
# macOS / Linux (creates env, checks build, starts server & opens browser)
./start.sh
# Windows
start.bat
# Or via CLI anytime:
uv run tgscrape start
```
The dashboard includes:
- **Simple Mode (6 essential tabs)** by default + **Pro Mode (all 12 tabs)** toggle.
- **Turkish / English (`TR` / `EN`)** live language switcher.
- **Smart Link Inspector Home**: Paste `@durov` or any `t.me/` URL -> auto-detects accountless vs. 60-second QR login flow + 1-click presets (`Last 100`, `Last 500 + Media`).
- **1-Click "Connect AI Agent (MCP)" Modal** right in the sidebar to copy Claude Code / Cursor / Antigravity / `uvx` setup snippets.
---
## Quick Start for AI Agents (Zero Friction)
### Option 1: Built-In MCP Server (`tgscrape mcp` — 18 Tools)
```bash
git clone https://github.com/SmtDcs/telegram-scraper.git telegram-scraper
cd telegram-scraper
uv sync --python 3.12
```
**Claude Code (1 Command):**
```bash
claude mcp add teleharvest -- uv --directory /ABSOLUTE/PATH/TO/telegram-scraper run tgscrape mcp
```
**Cursor / Antigravity / Windsurf / Claude Desktop (`mcp.json`):**
```json
{
"mcpServers": {
"teleharvest": {
"command": "uv",
"args": ["--directory", "/ABSOLUTE/PATH/TO/telegram-scraper", "run", "tgscrape", "mcp"]
}
}
}
```
**Or Zero-Clone via `uvx` (from Git URL or PyPI):**
```json
{
"mcpServers": {
"teleharvest": {
"command": "uvx",
"args": ["--from", "git+https://github.com/SmtDcs/telegram-scraper", "tgscrape", "mcp"]
}
}
}
```
Your AI agent immediately gets **18 native Telegram tools**:
`inspect_telegram_target`, `scrape_public_channel`, `list_accounts`, `list_dialogs`, `list_chats`, `scrape_chat`, `scrape_members`, `search_messages`, `get_message_thread`, `get_analytics`, `export_dataset`, `get_overview_stats`, `discover_similar_channels`, `global_telegram_search`, `scrape_stories`, `list_stories`, `get_channel_bi_metrics`, `semantic_search_messages`.
### Option 2: Agent Skill + `--json` CLI (No MCP Needed)
The repository includes [`AGENTS.md`](AGENTS.md), [`CLAUDE.md`](CLAUDE.md), and a portable Agent Skill at [`.agents/skills/teleharvest/SKILL.md`](.agents/skills/teleharvest/SKILL.md).
---
## What's New in v2.0 & Key Features
- **Zero-Auth Public Channel Scraper (`t.me/s/`):** Instant scraping with `HTTP 429` retry backoff, multi-photo albums, SHA-256 media dedup, and Smart `inspect` target diagnostics.
- **Full MTProto Scraper (`Telethon`) + Safety Shield (`AccountSafetyGuard`):** QR Code (Web UI + terminal ASCII), Phone+OTP+2FA, `StringSession`, SOCKS5/HTTP/MTProxy tester, gap-free incremental sync, `fcntl.flock` session protection, `safe`/`balanced`/`fast` presets, and automatic FloodWait/freeze quarantine.
- **Snowball Channel Discovery & Gephi Graph Mapping:** `GetChannelRecommendationsRequest` + forward network edges (`discover`), plus **`edgelist_csv`** (Gephi) & **`graph_json`** exports.
- **Global Telegram Search:** Search unjoined public channels and messages across Telegram (`global-search`).
- **Ephemeral Stories Archiver:** Archive active 24h stories + media before expiration (`stories` / `/api/chats/{id}/scrape-stories`).
- **Multimodal OCR + Voice Transcription indexed into FTS5:** Gemini Vision OCR (`ocr`) + `gemini-3.5-transcribe` audio/voice/video_note transcription (`transcribe`) automatically searchable via SQLite FTS5.
- **Auto-Translation & Hybrid Semantic Vector Search:** Multi-language batch translation (`translate`) + 768-dim `gemini-embedding-001` vectors (`embed`) fused with FTS5 via Reciprocal Rank Fusion (`semantic-search`).
- **Channel BI Metrics & Native Broadcast Stats:** Automatic **ER %** (engagement / views), **ERR %** (reach / subscribers), posts/day, plus native Telegram `GetBroadcastStatsRequest` inspection (`bi-stats`).
- **11 Export Formats:** `json`, `jsonl`, `csv` (UTF-8 BOM), 4-sheet **Excel (`.xlsx`)**, self-contained **HTML Archive**, **Markdown**, filtered **SQLite (`.db`)**, `members_csv`, `members_json`, **`edgelist_csv` (Gephi)**, and **`graph_json`**.
- **Security Hardening:** Optional Bearer `API_TOKEN`, strict localhost CORS, `X-Content-Type-Options: nosniff` + attachment downgrade on `.html`/`.svg`, SSRF-checked webhooks, `0700`/`0600` data directory permissions.
---
## CLI Reference (`tgscrape`)
```bash
# Inspect any link without an account (channel vs group vs private)
uv run tgscrape inspect https://t.me/tradesberserk_chat --json
# Accountless public broadcast channel scrape
uv run tgscrape public @telegram --limit 200 --media --json
# Authorize an MTProto account (QR code in terminal or Phone+OTP+2FA)
uv run tgscrape auth add
uv run tgscrape auth list
uv run tgscrape auth export-string 1
# Browse joined chats & scrape private channels or public groups
uv run tgscrape dialogs
uv run tgscrape scrape @group_or_channel --limit 500 --comments --media
uv run tgscrape scrape @group_or_channel --incremental
uv run tgscrape scrape @group_or_channel --resume-backfill
uv run tgscrape media-retry --limit 200
# Harvest group members & admins
uv run tgscrape members @group_name --limit 2000
# Live monitor in terminal
uv run tgscrape listen
# Search (SQLite FTS5) & Export (11 formats)
uv run tgscrape search "bitcoin OR ethereum" --json
uv run tgscrape export xlsx --chat-id -100123456789
uv run tgscrape export members_csv --chat-id -100123456789
uv run tgscrape export edgelist_csv # Gephi graph CSV
uv run tgscrape export graph_json # Network nodes+edges JSON
uv run tgscrape export sqlite # secret-free filtered DB
# Discovery, Stories, Global Search & BI Metrics (v2.0)
uv run tgscrape discover @seed_channel --depth 1 --json
uv run tgscrape global-search "bitcoin" --type channels --json
uv run tgscrape stories -100123456789 --json
uv run tgscrape bi-stats --days 30 --json
# AI Digest, Auto-Tagging, OCR, Transcription, Translation & Semantic Search
uv run tgscrape ai digest --limit 150
uv run tgscrape ai classify --limit 50
uv run tgscrape ai ask "What were the main announcements this week?"
uv run tgscrape ai ocr --limit 25
uv run tgscrape ai transcribe --limit 20
uv run tgscrape ai translate --lang Turkish --limit 40
uv run tgscrape ai embed --limit 200
uv run tgscrape ai semantic-search "crypto inflows" --json
# Start MCP Server (for AI agents) or 1-Click Web Dashboard
uv run tgscrape mcp
uv run tgscrape start
uv run tgscrape serve --host 127.0.0.1 --port 8765
```
---
## Environment Variables (`.env.example`)
| Variable | Default | Purpose |
|---|---|---|
| `TG_API_ID` / `TG_API_HASH` | *(optional)* | Default Telegram API credentials from [my.telegram.org/apps](https://my.telegram.org/apps) |
| `HOST` / `PORT` | `127.0.0.1` / `8765` | Web Dashboard bind address |
| `API_TOKEN` | *(empty)* | Enables Bearer auth on `/api/*` & `/ws` (**required** when binding non-localhost / Docker) |
| `CORS_ORIGINS` | localhost ports | Comma-separated allowed browser origins |
| `SAFETY_PRESET` | `safe` | `safe` (`1.5–3.5s`), `balanced` (`0.8–2.0s`), `fast` (`0.4–1.2s`) |
| `FLOOD_WAIT_MAX_SLEEP` | `300` | Above this duration (sec), jobs pause safely instead of waiting |
| `MAX_MEDIA_SIZE_MB` | `50` | Maximum media download size per file |
| `ALLOW_PRIVATE_WEBHOOKS` | `false` | Set `true` only to allow local/private network webhooks (e.g. local n8n) |
| `AI_PROVIDER` | `gemini` | `gemini`, `openai`, or `ollama` |
| `GEMINI_API_KEY` / `GEMINI_MODEL` | `gemini-4-hydrogen` | Google Gemini Interactions API config |
---
## Docker
```bash
# For non-localhost exposure, set API_TOKEN in .env first
docker compose up -d --build
```
## Development & Tests
```bash
# Run full test suite
uv run pytest -v
# Rebuild React + TypeScript + Tailwind frontend into backend/tgscrape/static/
cd frontend && npm install && npm run build
```
## Disclaimer & Safety Notice
Use TeleHarvest responsibly and only on channels, groups, and data you are authorized to access under Telegram's Terms of Service and applicable privacy laws. High-frequency MTProto scraping—especially aggressive member enumeration or bio harvesting on fresh/VoIP accounts or datacenter IPs—can lead to temporary `FloodWait` limits or account freezes. Prefer a dedicated secondary account on a clean IP with the default `safe` preset.
## License
[MIT](LICENSE)
TDQS
Scored across 18 tools
Most tools target clearly different resources or workflows, with especially clear separation between accountless scraping and MTProto scraping. Minor overlap remains between list_chats and list_dialogs, between search_messages and semantic_search_messages, and among analytics/metrics tools, though descriptions generally clarify intent.
The set mostly follows a predictable verb_noun pattern such as list_chats, scrape_chat, search_messages, and get_analytics. A few names break the pattern, notably global_telegram_search and semantic_search_messages, but the overall convention remains readable.
Eighteen tools is slightly above the ideal compact range, but the server covers a broad domain including scraping, search, analytics, export, accounts, stories, and discovery. Each tool appears to earn its place rather than duplicating another operation.
The surface covers the core Telegram harvesting lifecycle well: target inspection, public and MTProto scraping, member/story archiving, search, thread retrieval, analytics, export, and discovery. Minor gaps exist around in-MCP account authorization/removal and data cleanup or alert management, but core workflows are not blocked.