Skip to main content
Glama
telegram-mcp

telegram-mcp

by Spleps
README.md
# telegram-mcp

A small, self-hosted [MCP](https://modelcontextprotocol.io) server that gives Claude (or any MCP client) access to Telegram in two safe modes:

| Mode | What it does | Tools |
|---|---|---|
| **Personal bot** | Exchange files and notes with your own bot. The bot talks **only to its owner**; messages from anyone else are ignored. | `bot_inbox`, `bot_download`, `bot_send_message`, `bot_send_file` |
| **Your account** | Read and search your chats via [Telethon](https://github.com/LonamiWebs/Telethon). Reading does not mark messages as read. Sending works **only** to chats you list in `config.json` → `"send_allowed_chats": [chat_id, ...]`, the chat must be given by exact id or @username, and every send is logged to `sent.jsonl`. There are no edit / delete tools. | `tg_list_chats`, `tg_read`, `tg_search`, `tg_download`, `tg_send_message`, `tg_send_files` |

Both modes are optional: configure one or both.

## Use cases

- Forward photos of a lab manual to the bot → *"take the photos from the bot and write the report"*.
- *"What was posted in my study group chat this week?"*
- *"Send the finished report to my Telegram."*

## Install

Requires Python 3.10+.

```bash
git clone https://github.com/Spleps/telegram-mcp.git
cd telegram-mcp
pip install -r requirements.txt
```

## Configure

```bash
python setup.py
```

1. **Bot**: create one with [@BotFather](https://t.me/BotFather) (`/newbot`), paste the token, then send `/start` to your bot. That chat becomes the only owner.
2. **Account**: get `api_id` / `api_hash` at [my.telegram.org](https://my.telegram.org) → *API development tools*. Log in by scanning a QR code (Telegram → Settings → Devices → Link Desktop Device). If you use a cloud password (2FA), a small dialog asks for it.

Secrets are stored next to the script in `config.json` and `account.session`. On Windows the setup restricts both files to the current user. They are listed in `.gitignore`: **never share them**. The session file gives full access to your account.

## Register in Claude Code

```bash
claude mcp add --scope user telegram -- python /path/to/telegram-mcp/server.py
```

Start a new Claude session and the `bot_*` / `tg_*` tools appear. Downloaded files go to `~/Downloads/Telegram MCP`.

## Revoke access

- Account: Telegram → Settings → Devices → terminate the session.
- Bot: `/revoke` in @BotFather, then run `setup.py` again.

## Bot commands

While the MCP server is running (i.e. a Claude session is open), the bot long-polls in the background and answers instantly:

- `/help`: what the bot can do
- `/status`: how many messages are waiting for Claude

When no session is open, messages are not lost: Telegram keeps undelivered updates for 24 hours and the bot picks them up on the next start.

## Run 24/7 on a server

To keep the bot answering when no Claude session is open, run the poller as a service and let MCP sessions only read the inbox:

1. Poller (bot only, no MCP): `python server.py --poll`. It exits on a fatal error, so run it under a supervisor. Example systemd unit:

   ```ini
   [Unit]
   Description=Telegram personal bot poller
   Wants=network-online.target
   After=network-online.target

   [Service]
   User=youruser
   WorkingDirectory=/home/youruser/telegram-mcp
   ExecStart=/home/youruser/telegram-mcp/.venv/bin/python server.py --poll
   Restart=always
   RestartSec=10

   [Install]
   WantedBy=multi-user.target
   ```

2. MCP sessions: set `TG_MCP_EXTERNAL_POLLER=1` so they never call `getUpdates` themselves (two pollers fight with HTTP 409):

   ```bash
   claude mcp add-json --scope user telegram '{"type":"stdio","command":"/home/youruser/telegram-mcp/.venv/bin/python","args":["/home/youruser/telegram-mcp/server.py"],"env":{"TG_MCP_EXTERNAL_POLLER":"1"}}'
   ```

3. From another computer, run the same server over SSH (key login), so there is still only one copy of the secrets:

   ```bash
   claude mcp add --scope user telegram -- ssh -o BatchMode=yes youruser@server 'TG_MCP_EXTERNAL_POLLER=1 /home/youruser/telegram-mcp/.venv/bin/python /home/youruser/telegram-mcp/server.py'
   ```

   Downloaded files then land on the server (`~/Downloads/Telegram MCP`).

Only one process may use the account session at a time: Telegram can revoke a session used from two connections at once. `server.py` takes a lock on `account.lock`, and a second process gets a clear error instead.

## How updates are handled

Every incoming message goes through a middleware chain in `server.py`:

```
owner_only -> commands -> store_in_inbox
```

- `owner_only`: access control. Messages from anyone except `owner_chat_id` stop here (commands get "Это приватный бот.").
- `commands`: answers `/help`, `/start`, `/status`.
- `store_in_inbox`: saves everything else for `bot_inbox`.

Add your own middleware as `def mw(ctx, nxt)` and put it into `MIDDLEWARES`.

## Tests

Offline tests (no network, no real config) cover the middleware chain, access control,
commands, `pull_updates` with a fake Telegram API, and the file helpers:

```
python -m unittest discover -s tests -v
```

They also run on GitHub Actions on every push.

## Notes

- Bot API limits: download ≤ 20 MB, upload ≤ 50 MB.
- Setup prompts are in Russian.

## License

MIT

## Optional private-chat auto-replies

`auto_reply.py` uses a separate Telethon session and replies only to explicitly
allowlisted private users. Bots, groups, channels and the owner are ignored.
The Copilot CLI generates text without shell, file or MCP tools; replies include
an automated-reply prefix and are rate-limited. An empty allowlist replies to nobody.

Add an `auto_reply` object to your local, ignored `config.json`:

```json
{
  "auto_reply": {
    "enabled": true,
    "chats": [],
    "owner_name": "Account owner",
    "cooldown_seconds": 20,
    "max_per_hour": 30
  }
}
```

Set `chats` to the user IDs you explicitly want to receive replies.
Install Copilot CLI, log in, then create the separate Telegram session:

```sh
.venv/bin/python auto_reply.py --login
.venv/bin/python auto_reply.py
```

For systemd, `telegram-auto-reply@.service` is a template for installations at
`/home/<user>/Projects/telegram-mcp`. Install it under `/etc/systemd/system/`
and select the service instance `telegram-auto-reply@<user>.service`. Adapt the
paths if your account has another home directory. Configs, sessions and reply
logs stay local and must never be committed.