Telegram Publishing MCP
by mnaza
README.md
# Telegram Publishing MCP
**English** | [Русский](README.ru.md)
A local MCP server for publishing from a **personal Telegram account** over MTProto (Telethon). It lets an AI client explore a network of channels and groups, read context from chosen venues, draft posts, articles, announcements, replies and comments, and then send approved texts. A comment on a channel post goes to the linked discussion group. In groups and comments messages are sent as the user; a post inside a channel appears under the channel's name, per Telegram's rules.
Publishing is limited to venues you pick by hand. The crawler can discover other public channels and groups but never adds them to the publishing allowlist. Neither the server nor the crawler ever joins chats: joining is possible only with `tg-promo allow @chat --join` in a terminal, at most 5 times per 24 hours. The server sends no private messages and does no mass mailing. External classified-ad sites are out of scope; they would need separate integrations and access rights.
## Installation
Requires Python 3.11+. Create an application at [my.telegram.org](https://my.telegram.org) → **API development tools** to get your own `api_id` and `api_hash`.
```bash
cd telegram-promo-mcp
python3 -m venv .venv
.venv/bin/pip install -e .
export TG_API_ID="123456"
export TG_API_HASH="your_api_hash"
.venv/bin/tg-promo login --phone "+15550000000"
```
The first login asks for the Telegram code and, if enabled, the cloud password **in the terminal**. Never give these to the AI client. The session and database live in `~/.local/share/tg-promo-mcp/` by default; override with `TG_STATE_DIR`. Treat that directory like your account password and keep it out of Git. Use the same environment variables for the login command and the MCP server.
## Choosing venues
```bash
.venv/bin/tg-promo dialogs --limit 50
.venv/bin/tg-promo allow @my_product_channel
.venv/bin/tg-promo allow -1001234567890
.venv/bin/tg-promo targets
.venv/bin/tg-promo remove -1001234567890
```
`allow` takes a username or an ID from `dialogs`; private chats with users are rejected. Only add channels and groups where you are allowed to post ads or product news. Removing a venue immediately blocks even previously approved drafts.
To join a public chat and allow it in one step, run in a terminal:
```bash
.venv/bin/tg-promo allow @some_chat --join
```
Only public `@username`s or `t.me` links are accepted. The command shows the title, type and member count and asks you to type `JOIN <id>`, where `<id>` is the chat ID. At most 5 joins per 24 hours. If you are already a member, nothing is joined and the chat is just added to the list. Joining other people's chats to advertise is a common cause of account restrictions; do it only where the rules allow ads.
## Connecting an MCP client
Use **absolute** paths and real values in your client's configuration:
```json
{
"mcpServers": {
"telegram-publishing": {
"command": "/absolute/path/telegram-promo-mcp/.venv/bin/tg-promo-server",
"env": {
"TG_API_ID": "123456",
"TG_API_HASH": "your_api_hash",
"TG_STATE_DIR": "/absolute/path/to/private/tg-promo-state"
}
}
}
}
```
The server uses stdio; the code-based login happens only through `tg-promo login`, before the client starts. If your client can't conveniently pass secrets in `env`, start it from a terminal with the variables exported.
## Workflow
1. Ask the AI client to call `list_targets`, optionally `recent_messages`, then `prepare_publication`. For example: "Draft a short launch announcement for @my_product_channel". For a comment, use `kind="comment"` and the channel post ID in `reference_message_id`; for a reply in a group, use `kind="reply"` and the ID of the message or of a forum topic's starting message.
To find discussions of a subject in an allowed chat, use `search_messages(target, query, limit, offset_id, since_days)`: a keyword search across all forum topics, read-only, without authors; page further with `offset_id = next_offset_id`. `recent_messages` also takes `offset_id` to page backwards.
2. In a terminal run `.venv/bin/tg-promo show ID`, then `.venv/bin/tg-promo approve ID`. The command shows the full text and asks you to type `APPROVE ID`.
3. Ask the AI client to call `publish_next_part` with the same ID. Each call sends exactly **one** message. For a long article repeat it until the status is `sent`; track progress with `view_draft`.
`post` and `announcement` send one message of up to 4000 UTF-16 units. `article` is split at paragraphs into at most eight messages. HTML and Markdown are not interpreted; put links in as plain text. Images, file uploads and external ad boards are not supported yet.
Calling `prepare_publication` again with the same text, venue and parameters returns the existing draft. If that text was already published to that venue within the last 7 days, the server refuses: this guards against repeated mailings.
> **Important.** Approval only protects against MCP tools: none of them can approve. If the AI client has shell access (for example, a coding agent), it could run `tg-promo approve` itself and type the confirmation. Connect this server to a client without terminal access, or forbid it from running `tg-promo`.
## Crawling channels and chats
Call `start_crawl` over MCP with seed public `@username`s or `t.me` links:
```json
{"seeds":["@my_product_channel"],"max_depth":2,"max_nodes":30,"recent_limit":5,"include_recommendations":true}
```
You can pass `"seeds":[],"include_joined":true` to seed from the channels and groups in your dialogs (up to 100, but no more than `max_nodes`). For a specific private group you are already in, give its negative ID from `tg-promo dialogs`. Private chats with users and private invite links are never crawled.
`crawl_next(crawl_id)` checks **one** venue per call. Repeat until `state="done"`; on `state="wait"` wait the given `retry_after_seconds`. `stop_crawl` stops a crawl. `list_crawls` and `crawl_report(crawl_id, query="word")` show results; page through edges of a large graph with `edge_offset` and `edge_limit`.
The crawler extracts public links from the description and from at most the ten latest messages of a venue, finds the linked discussion group and up to five [Telegram-recommended channels](https://core.telegram.org/api/recommend) per checked channel. It stores the title, username, a short description and the link to its source; it does not store full message texts or member lists. Calls are bounded: depth 0–3, 1–100 venues, and a pause between checks. Discovery grants no permission to publish: add the venue with `tg-promo allow` and approve each draft separately.
### Finding chats by topic
With `topic` set, the crawler doesn't just collect links; it looks for chats where the topic is being discussed right now. `start_crawl` parameters:
- `topic` — the topic, 1–500 characters;
- `keywords` — up to 10 keywords (case-insensitive). The crawler adds seeds from them in two ways: it searches public chats by name, and it searches messages in your own chats, including private groups you belong to. Message samples from those chats are then shown to the AI for rating;
- `min_score` — rating threshold 0–10 (default 6): chats rated at or above it are explored further;
- `sample_size` — how many recent messages to show in a sample, 1–30 (default 15).
In topic mode `include_recommendations` defaults to off (on without a topic).
```json
{"seeds":["@my_product_channel"],"topic":"self-publishing apps on Google Play","keywords":["google play","app publishing"],"min_score":6,"sample_size":15}
```
The loop:
1. `crawl_next(crawl_id, batch=3)` checks 1 to 5 venues per call and returns an anonymised sample of recent messages for each (`sample`, up to 200 characters per message; messages without text are marked `[media]`).
2. For **each** returned chat, call `rate_chat(crawl_id, locator, score, reason)`: `score` is an integer 0–10 (how much the topic is discussed in the chat now, not just how related it is), `reason` is at most 300 characters. While chats remain unrated, `crawl_next` may return `state="needs_rating"`: `locators` lists the chats still to rate, and `retry_after_seconds` says when the oldest unrated check expires. A rating not given within 15 minutes is reset and the chat is checked again.
3. Repeat until `state` is `done`. Short Telegram waits (up to 30 seconds, at most 60 seconds per call) are handled inside the call; longer ones come back as `state="wait"` with `retry_after_seconds`.
4. Show the result: `crawl_report(crawl_id, min_score=6)`.
A ready-made prompt:
> Find chats where people discuss <topic>: start_crawl with topic and keywords, then crawl_next and rate_chat for every chat without stopping until done, and finally show crawl_report with min_score=6.
Message texts are not stored: a sample exists only in the tool response. Mentions that turn out to be people's accounts are removed from the results and don't count toward `max_nodes`. The crawler still never joins chats.
To avoid confirming every call, allow the crawl tools in your MCP client's permission settings: `start_crawl`, `crawl_next`, `rate_chat`, `crawl_report`, `list_crawls` and `stop_crawl`. They never post or join chats. Do not auto-allow the publishing tools (`prepare_publication`, `publish_next_part`): they must require confirmation.
### Send limits and reconciliation
Sends to one venue are at least 30 seconds apart, with a cap of 12 messages per venue and 60 in total over the last 24 hours. Telegram may impose its own limits or forbid posting. On a network error the result is marked `uncertain` so an already delivered text is not sent twice. Check the chat and run one of:
```bash
.venv/bin/tg-promo reconcile ID --sent-message-id 12345
.venv/bin/tg-promo reconcile ID --not-sent
```
The first marks the found message as published; the second allows a retry once you've confirmed the message isn't there.
## Testing
```bash
.venv/bin/python -m unittest discover -s tests -v
```
The tests use a fake Telegram and publish nothing online. Real use requires your account login, chosen venues and their rules. Mind the [Telegram API terms](https://core.telegram.org/api/terms) and the [spam warning](https://core.telegram.org/api/obtaining_api_id).
## License
[MIT](LICENSE)
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues