tg-hub
Based on: jackwener/tg-cli (Apache-2.0)
This skill simplifies the original repository as follows:
- Removed the
click / rich / python-dotenv / pyyaml dependencies
- Kept only
telethon as a third-party dependency
- Removed the CLI layer and encapsulated all functionality as a synchronous Python API
- Changed the default session/db path to
/var/minis/workspace/tg-hub/
- Changed configuration to read environment variables directly, with no
.env file required
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 the local SQLite database, with no network access, and respond in milliseconds
- Write operations (sync/refresh): connect to Telegram to fetch new messages and write them 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 (environment variables / default paths)
├── db.py # SQLite message storage
├── exceptions.py # Structured exceptions
└── client.py # TGClient core class (all APIs)
First-Time Login (Must Be Done in Terminal)
tg-hub uses the MTProto protocol (not the Bot API), so you need to log in with your Telegram account.
Recommendation: Use your own TG_API_ID / TG_API_HASH whenever possible.
I have synced the upstream tg-cli anti-risk-control implementation: it uses a Telegram Desktop 5.x fingerprint and prints a warning if you continue using the default api_id=2040. The public app ID is only a fallback. Using your own credentials is still recommended for long-term use.
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 your phone number when prompted (in +86XXXXXXXXXX format)
6. Enter the verification code received in the Telegram app
7. After login succeeds, the session is saved automatically and future logins are not required
If you do not have your own credentials for now, you can log in with the built-in public credentials first. If you encounter login or fetch errors, switch to your own APP ID first.
Open Terminal to log in
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()
# View the current account
me = client.whoami()
print(me["name"], me["phone"])
# List all conversations (fetched from TG in real time)
chats = client.list_chats()
for c in chats[:10]:
print(f" [{c['type']}] {c['name']} Unread: {c['unread']}")
# Incrementally sync a single group
n = client.sync("Group name or username", limit=1000)
print(f"Added {n} messages")
# Quickly refresh all groups (up to 500 new messages per group)
# Slight throttling is enabled by default; you can also limit this round to only the first 30 chats
result = client.refresh(delay=1.0, max_chats=30)
for name, count in result.items():
if count > 0:
print(f" {name}: +{count}")
# Search by keyword
msgs = client.search("Python", hours=48)
for m in msgs:
print(f"[{m['chat_name']}] {m['sender_name']}: {m['content'][:80]}")
# Multi-keyword filtering (OR logic)
msgs = client.filter("hiring,remote,part-time", hours=24)
# Today's messages
msgs = client.today()
# Messages from the last 12 hours
msgs = client.recent(hours=12, limit=200)
# Speaker rankings
top = client.top_senders(hours=24)
for t in top[:5]:
print(f" {t['sender_name']}: {t['msg_count']} messages")
# Timeline statistics
tl = client.timeline(granularity="hour", hours=48)
# Local database statistics
stats = client.stats()
print(f"{stats['total']} local messages across {len(stats['chats'])} groups")
API Quick Reference
Authentication
| Method |
Description |
login() |
Interactive login (first time, requires terminal) |
whoami() |
Get current account information |
Sync (Online)
| Method |
Description |
list_chats(chat_type=None) |
List all conversations (real time) |
sync(chat, limit=5000) |
Sync a single group to local SQLite |
sync_all(limit_per_chat=5000, delay=1.0, max_chats=None) |
Sync all groups (with throttling/count limit) |
refresh(limit_per_chat=500, delay=1.0, max_chats=None) |
Quick incremental refresh (recommended for daily use) |
Query (Local, Offline)
| Method |
Description |
search(keyword, *, chat, sender, hours, regex, limit) |
Keyword/regex search |
filter(keywords, *, chat, hours) |
Multi-keyword OR filtering |
today(chat=None) |
Today's messages |
recent(hours=24, *, chat, sender, limit) |
Messages from the last N hours |
top_senders(chat, hours, limit) |
Speaker rankings |
timeline(chat, hours, granularity) |
Timeline statistics |
stats() |
Database statistics |
local_chats() |
List of locally synced groups |
delete_chat(chat) |
Delete local messages for a group |
Environment Variables
| Variable |
Default Value |
Description |
TG_API_ID |
2040 (fallback only) |
Recommended: replace with your own API ID |
TG_API_HASH |
Built in (fallback only) |
Recommended: replace with your own API Hash |
TG_SESSION_NAME |
tg_hub |
Session filename |
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 whenever possible: Go to
https://my.telegram.org, create an application, and then set TG_API_ID / TG_API_HASH.
- Control sync frequency: Avoid repeatedly running
refresh() at high frequency.
- Use
delay and max_chats: For daily incremental refreshes, we recommend limiting the number of chats synced per round and keeping an interval between chats.
- Do not be too aggressive with the first full sync: tg-hub automatically applies a lower fetch limit for the first sync of each chat.
- Prefer read operations: Local queries such as search and statistics do not use the network, so they are much lower risk than frequent syncs.
Notes
- The first login must be completed in an interactive terminal (a verification code is required).
- Using your own
TG_API_ID / TG_API_HASH is strongly recommended to avoid risk-control issues caused by abuse of the public APP ID.
- tg-hub is aligned with the upstream tg-cli Telegram Desktop 5.x client fingerprint and retains environment variable overrides to reduce the risk of abnormal fingerprints.
- If you are still using the default
api_id=2040, a warning is printed during connection to remind you to switch to your own TG_API_ID / TG_API_HASH.
- The session file is stored at
/var/minis/workspace/tg-hub/tg_hub.session. Keep it safe.
- The first run of
sync_all may take a long time, depending on the number of groups and the amount of historical messages.
- We recommend using
refresh() for daily incremental updates and sync(chat, limit=10000) for the initial full sync.
- Telegram applies rate limits to API requests. During large syncs, Telethon automatically handles flood waits.
1---2name: tg-hub3description: A skill for reading and writing Telegram data with Python and UV. It depends only on Telethon and uses a local-first architecture: messages are synced to SQLite and then queried offline. On first use, you must log in from the terminal with a phone number verification code. After that, the session is persisted and you do not need to log in again. Supports syncing group and channel messages locally, keyword search, multi-keyword filtering, today's messages, recent messages, speaker rankings, timeline statistics, and more. This skill must be triggered whenever the user mentions "Telegram", "TG", "Telegram", "tg-hub", "sync Telegram messages", "search TG groups", "Telegram keywords", "get TG messages", or any scenario that requires programmatically reading or writing Telegram data.4---56# tg-hub78> **Based on**: [jackwener/tg-cli](https://github.com/jackwener/tg-cli) (Apache-2.0)9>10> This skill simplifies the original repository as follows:11> - Removed the `click` / `rich` / `python-dotenv` / `pyyaml` dependencies12> - Kept only `telethon` as a third-party dependency13> - Removed the CLI layer and encapsulated all functionality as a synchronous Python API14> - Changed the default session/db path to `/var/minis/workspace/tg-hub/`15> - Changed configuration to read environment variables directly, with no `.env` file required1617---1819## Architecture: Local-First2021```22Telegram MTProto (telethon)23 ↓ sync / refresh (incremental)24Local SQLite ~/.tg-hub/messages.db25 ↓ search / today / recent / filter (offline)26Structured data27```2829- **Read operations** (search/today/recent): query the local SQLite database, with **no network access**, and respond in milliseconds30- **Write operations** (sync/refresh): connect to Telegram to fetch new messages and write them incrementally to SQLite31- Session file: `~/.tg-hub/tg_hub.session`3233---3435## File Structure3637```38/var/minis/skills/tg-hub/39├── SKILL.md40├── pyproject.toml # telethon only41└── scripts/42 ├── __init__.py43 ├── config.py # Configuration (environment variables / default paths)44 ├── db.py # SQLite message storage45 ├── exceptions.py # Structured exceptions46 └── client.py # TGClient core class (all APIs)47```4849---5051## First-Time Login (Must Be Done in Terminal)5253tg-hub uses the **MTProto protocol** (not the Bot API), so you need to log in with your Telegram account.5455> **Recommendation**: Use your own `TG_API_ID` / `TG_API_HASH` whenever possible.56> I have synced the upstream tg-cli anti-risk-control implementation: it uses a Telegram Desktop 5.x fingerprint and prints a warning if you continue using the default `api_id=2040`. The public app ID is only a fallback. Using your own credentials is still recommended for long-term use.5758```591. Open Terminal602. (Recommended) Set your own TG_API_ID / TG_API_HASH first613. cd /var/minis/skills/tg-hub624. uv run python -c "63 import sys; sys.path.insert(0,'.')64 from scripts.client import TGClient65 me = TGClient().login()66 print('Login successful:', me)67 "685. Enter your phone number when prompted (in +86XXXXXXXXXX format)696. Enter the verification code received in the Telegram app707. After login succeeds, the session is saved automatically and future logins are not required71```7273> If you do not have your own credentials for now, you can log in with the built-in public credentials first. If you encounter login or fetch errors, switch to your own APP ID first.7475[Open Terminal to log in](minis://open_terminal?init_command=cd%20%2Fvar%2Fminis%2Fskills%2Ftg-hub%20%26%26%20uv%20run%20python%20-c%20%22import%20sys%3B%20sys.path.insert(0%2C'.')%3B%20from%20scripts.client%20import%20TGClient%3B%20TGClient().login()%22)7677---7879## Quick Start8081### Environment Setup8283```bash84cd /var/minis/skills/tg-hub85uv sync86```8788### Python Usage8990```python91import sys92sys.path.insert(0, "/var/minis/skills/tg-hub")93from scripts.client import TGClient9495client = TGClient()9697# View the current account98me = client.whoami()99print(me["name"], me["phone"])100101# List all conversations (fetched from TG in real time)102chats = client.list_chats()103for c in chats[:10]:104 print(f" [{c['type']}] {c['name']} Unread: {c['unread']}")105106# Incrementally sync a single group107n = client.sync("Group name or username", limit=1000)108print(f"Added {n} messages")109110# Quickly refresh all groups (up to 500 new messages per group)111# Slight throttling is enabled by default; you can also limit this round to only the first 30 chats112result = client.refresh(delay=1.0, max_chats=30)113for name, count in result.items():114 if count > 0:115 print(f" {name}: +{count}")116117# Search by keyword118msgs = client.search("Python", hours=48)119for m in msgs:120 print(f"[{m['chat_name']}] {m['sender_name']}: {m['content'][:80]}")121122# Multi-keyword filtering (OR logic)123msgs = client.filter("hiring,remote,part-time", hours=24)124125# Today's messages126msgs = client.today()127128# Messages from the last 12 hours129msgs = client.recent(hours=12, limit=200)130131# Speaker rankings132top = client.top_senders(hours=24)133for t in top[:5]:134 print(f" {t['sender_name']}: {t['msg_count']} messages")135136# Timeline statistics137tl = client.timeline(granularity="hour", hours=48)138139# Local database statistics140stats = client.stats()141print(f"{stats['total']} local messages across {len(stats['chats'])} groups")142```143144---145146## API Quick Reference147148### Authentication149150| Method | Description |151|------|------|152| `login()` | Interactive login (first time, requires terminal) |153| `whoami()` | Get current account information |154155### Sync (Online)156157| Method | Description |158|------|------|159| `list_chats(chat_type=None)` | List all conversations (real time) |160| `sync(chat, limit=5000)` | Sync a single group to local SQLite |161| `sync_all(limit_per_chat=5000, delay=1.0, max_chats=None)` | Sync all groups (with throttling/count limit) |162| `refresh(limit_per_chat=500, delay=1.0, max_chats=None)` | Quick incremental refresh (recommended for daily use) |163164### Query (Local, Offline)165166| Method | Description |167|------|------|168| `search(keyword, *, chat, sender, hours, regex, limit)` | Keyword/regex search |169| `filter(keywords, *, chat, hours)` | Multi-keyword OR filtering |170| `today(chat=None)` | Today's messages |171| `recent(hours=24, *, chat, sender, limit)` | Messages from the last N hours |172| `top_senders(chat, hours, limit)` | Speaker rankings |173| `timeline(chat, hours, granularity)` | Timeline statistics |174| `stats()` | Database statistics |175| `local_chats()` | List of locally synced groups |176| `delete_chat(chat)` | Delete local messages for a group |177178---179180## Environment Variables181182| Variable | Default Value | Description |183|------|--------|------|184| `TG_API_ID` | `2040` (fallback only) | **Recommended: replace with your own** API ID |185| `TG_API_HASH` | Built in (fallback only) | **Recommended: replace with your own** API Hash |186| `TG_SESSION_NAME` | `tg_hub` | Session filename |187| `TG_DATA_DIR` | `~/.tg-hub` | Data directory |188| `TG_DB_PATH` | `{TG_DATA_DIR}/messages.db` | SQLite path |189| `TG_DEVICE_MODEL` | `Desktop` | Telethon client device model |190| `TG_SYSTEM_VERSION` | `macOS 15.3` | Telethon client system version |191| `TG_APP_VERSION` | `5.12.1` | Telethon client version |192| `TG_LANG_CODE` | `en` | Client language code |193| `TG_SYSTEM_LANG_CODE` | `en-US` | System language code |194195---196197## Account Security Recommendations1981991. **Use your own API credentials whenever possible**: Go to `https://my.telegram.org`, create an application, and then set `TG_API_ID` / `TG_API_HASH`.2002. **Control sync frequency**: Avoid repeatedly running `refresh()` at high frequency.2013. **Use `delay` and `max_chats`**: For daily incremental refreshes, we recommend limiting the number of chats synced per round and keeping an interval between chats.2024. **Do not be too aggressive with the first full sync**: tg-hub automatically applies a lower fetch limit for the first sync of each chat.2035. **Prefer read operations**: Local queries such as search and statistics do not use the network, so they are much lower risk than frequent syncs.204205---206207## Notes208209- The first login must be completed in an interactive terminal (a verification code is required).210- **Using your own `TG_API_ID` / `TG_API_HASH` is strongly recommended** to avoid risk-control issues caused by abuse of the public APP ID.211- tg-hub is aligned with the upstream tg-cli Telegram Desktop 5.x client fingerprint and retains environment variable overrides to reduce the risk of abnormal fingerprints.212- If you are still using the default `api_id=2040`, a warning is printed during connection to remind you to switch to your own `TG_API_ID` / `TG_API_HASH`.213- The session file is stored at `/var/minis/workspace/tg-hub/tg_hub.session`. Keep it safe.214- The first run of `sync_all` may take a long time, depending on the number of groups and the amount of historical messages.215- We recommend using `refresh()` for daily incremental updates and `sync(chat, limit=10000)` for the initial full sync.216- Telegram applies rate limits to API requests. During large syncs, Telethon automatically handles flood waits.