| name | tg-hub |
| description | Read and write Telegram data using Python + UV, depends only on telethon, local-first architecture (messages synced to SQLite for offline queries). First use requires phone verification in terminal, then session persists without login. Supports syncing group/channel messages locally, keyword search, multi-keyword filter, today messages, recent messages, top senders, timeline stats, etc. Triggers when user mentions "Telegram", "TG", "tg-hub", "sync Telegram messages", "search TG group", "Telegram keyword", "get TG messages", or any scenario requiring programmatic read/write of Telegram data.
|
tg-hub
Forked from: jackwener/tg-cli (Apache-2.0)
This skill simplifies the original repo as follows:
- Removed
click / rich / python-dotenv / pyyaml dependencies
- Kept
telethon as the only third-party dependency
- Removed CLI layer, all functions wrapped as synchronous Python API
- Default session/db path changed to
/var/minis/workspace/tg-hub/
- Configuration reads environment variables directly, no
.env file needed
Architecture: Local-First
Telegram MTProto (telethon)
↓ sync / refresh (incremental)
Local SQLite ~/.tg-hub/messages.db
↓ search / today / recent / filter (offline)
Structured data
- Read operations (search/today/recent): query local SQLite, offline, millisecond response
- Write operations (sync/refresh): connect to Telegram, fetch new messages, write incrementally to SQLite
- Session file:
~/.tg-hub/tg_hub.session
File Structure
/var/minis/skills/tg-hub/
├── SKILL.md
├── pyproject.toml # telethon only
└── scripts/
├── __init__.py
├── config.py # configuration (env vars / default paths)
├── db.py # SQLite message store
├── exceptions.py # structured exceptions
└── client.py # TGClient core class (all APIs)
First Login (Must use Terminal)
tg-hub uses MTProto protocol (not Bot API), requiring login with your Telegram account.
Recommendation: Use your own TG_API_ID / TG_API_HASH.
This skill follows upstream tg-cli's anti-restriction implementation: uses Telegram Desktop 5.x fingerprint, and warns when using default api_id=2040. Public APP ID is fallback only; long-term use of your own credentials is recommended.
1. Open Terminal
2. (Recommended) Set your own TG_API_ID / TG_API_HASH first
3. cd /var/minis/skills/tg-hub
4. uv run python -c "
import sys; sys.path.insert(0,'.')
from scripts.client import TGClient
me = TGClient().login()
print('Login successful:', me)
"
5. Enter phone number as prompted (+86XXXXXXXXXX format)
6. Enter verification code received in Telegram App
7. Session auto-saved after login, subsequent use skips login
If you don't have your own credentials yet, use the built-in public credentials to login; if login/fetch errors occur, switch to your own APP ID first.
Open Terminal Login
Quick Start
Environment Setup
cd /var/minis/skills/tg-hub
uv sync
Python Usage
import sys
sys.path.insert(0, "/var/minis/skills/tg-hub")
from scripts.client import TGClient
client = TGClient()
me = client.whoami()
print(me["name"], me["phone"])
chats = client.list_chats()
for c in chats[:10]:
print(f" [{c['type']}] {c['name']} unread: {c['unread']}")
n = client.sync("group_name_or_username", limit=1000)
print(f"Added {n} new messages")
result = client.refresh(delay=1.0, max_chats=30)
for name, count in result.items():
if count > 0:
print(f" {name}: +{count}")
msgs = client.search("Python", hours=48)
for m in msgs:
print(f"[{m['chat_name']}] {m['sender_name']}: {m['content'][:80]}")
msgs = client.filter("hiring,remote,freelance", hours=24)
msgs = client.today()
msgs = client.recent(hours=12, limit=200)
top = client.top_senders(hours=24)
for t in top[:5]:
print(f" {t['sender_name']}: {t['msg_count']} messages")
tl = client.timeline(granularity="hour", hours=48)
stats = client.stats()
print(f"Local: {stats['total']} messages, {len(stats['chats'])} groups")
API Reference
Auth
| Method | Description |
|---|
login() | Interactive login (first time, needs terminal) |
whoami() | Get current account info |
Sync (online)
| Method | Description |
|---|
list_chats(chat_type=None) | List all chats (live) |
sync(chat, limit=5000) | Sync single group to local SQLite |
sync_all(limit_per_chat=5000, delay=1.0, max_chats=None) | Sync all groups (with throttling/limit) |
refresh(limit_per_chat=500, delay=1.0, max_chats=None) | Quick incremental refresh (recommended daily) |
Query (local, offline)
| Method | Description |
|---|
search(keyword, *, chat, sender, hours, regex, limit) | Keyword/regex search |
filter(keywords, *, chat, hours) | Multi-keyword OR filter |
today(chat=None) | Today's messages |
recent(hours=24, *, chat, sender, limit) | Last N hours messages |
top_senders(chat, hours, limit) | Top senders ranking |
timeline(chat, hours, granularity) | Timeline stats |
stats() | Database statistics |
local_chats() | Locally synced chat list |
delete_chat(chat) | Delete local messages for a chat |
Environment Variables
| Variable | Default | Description |
|---|
TG_API_ID | 2040 (fallback) | Recommended to use your own API ID |
TG_API_HASH | built-in (fallback) | Recommended to use your own API Hash |
TG_SESSION_NAME | tg_hub | Session file name |
TG_DATA_DIR | ~/.tg-hub | Data directory |
TG_DB_PATH | {TG_DATA_DIR}/messages.db | SQLite path |
TG_DEVICE_MODEL | Desktop | Telethon client device model |
TG_SYSTEM_VERSION | macOS 15.3 | Telethon client system version |
TG_APP_VERSION | 5.12.1 | Telethon client version |
TG_LANG_CODE | en | Client language code |
TG_SYSTEM_LANG_CODE | en-US | System language code |
Account Security Recommendations
- Use your own API credentials: Visit
https://my.telegram.org to create an app, then set TG_API_ID / TG_API_HASH.
- Control sync frequency: Avoid high-frequency repeated calls to
refresh().
- Use
delay and max_chats: Limit per-round sync count and keep intervals between chats for daily incremental refresh.
- Don't be too aggressive on first full sync: tg-hub auto-limits fetch amount for first-time sync.
- Prefer read operations: Local queries (search/stats) are offline, much lower risk than frequent syncs.
Notes
- First login must be done in interactive terminal (verification code required)
- Strongly recommend using your own
TG_API_ID / TG_API_HASH to avoid risk control issues from public APP ID abuse
- tg-hub aligns with upstream tg-cli's Telegram Desktop 5.x client fingerprint, retains env var override capability to reduce abnormal fingerprint risk
- If still using default
api_id=2040, a warning is printed on connect, reminding you to set your own TG_API_ID / TG_API_HASH
- Session file stored at
/var/minis/workspace/tg-hub/tg_hub.session, keep it safe
sync_all first run takes longer (depends on number of groups and history message volume)
- Use
refresh() for daily incremental updates, sync(chat, limit=10000) for first full sync
- Telegram has API rate limits; telethon handles flood wait automatically during large syncs