docker-telethon-plus
Provides tools for interacting with Telegram as the authenticated user, including reading and sending messages, downloading media, resolving entities, listing dialogs, and managing chats via MTProto.
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@docker-telethon-plusSend a Telegram message to Alice saying 'See you tomorrow'."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
docker-telethon-plus
Your Telegram account, but it takes HTTP requests. Wraps Telethon — the real MTProto userbot client, not that neutered Bot API garbage — behind a JSON HTTP API and a Model Context Protocol endpoint.
Same tools, two doors. POST some JSON, or point your AI agent at /mcp and let it go nuts. Either way it's talking to Telegram as you, with full account access.
One login. One session string. Never type a code again.
Table of Contents
Related MCP server: telegram-mcp
How it works
+-------------------+ +-----------------------+
| Any HTTP client | -----> | REST /api/... | --+
+-------------------+ +-----------------------+ |
| +-----------+ Telegram
+-------------------+ +-----------------------+ +-> | Telethon | <----> Servers
| MCP-aware agent | -----> | /mcp (Streamable | --+ +-----------+ (MTProto)
| (Claude, etc.) | | HTTP transport) |
+-------------------+ +-----------------------+One Telethon client. One async lock. Both surfaces share the same tool registry — no duplication, no weird state, no bullshit.
Quick start
services:
telethon-plus:
image: psyb0t/telethon-plus
ports:
- "8080:8080"
environment:
TELETHON_API_ID: "123456"
TELETHON_API_HASH: "your-api-hash"
TELETHON_SESSION: "1Aa...long-string-from-login-helper..."
restart: unless-stoppedGet API_ID / API_HASH from https://my.telegram.org/apps. Get the session string from the login helper below.
First-time login
Telegram makes you prove you're a human once — phone number, SMS code, optionally 2FA. Do it once, never again.
cp .env.example .env
$EDITOR .env # put in TELETHON_API_ID and TELETHON_API_HASH
make loginmake login builds the image, runs the interactive flow, and shoves TELETHON_SESSION straight into your .env. That's it. Run make run and you're live.
No repo? No problem:
docker run --rm -it \
-e TELETHON_API_ID=123456 \
-e TELETHON_API_HASH=your-api-hash \
psyb0t/telethon-plus loginCopy the session string it spits out, set it as TELETHON_SESSION, done.
The session string is full account access. Whoever has it is you. Don't commit it, don't paste it in Slack, don't tattoo it anywhere.
Configuration
All config via environment variables. Copy .env.example to get the full list with comments.
Variable | Required | Default | Description |
| yes | — | API ID from my.telegram.org |
| yes | — | API hash from my.telegram.org |
| yes | — | StringSession from the login helper |
| no |
|
|
| no |
|
|
| no |
| Per-request timeout in seconds |
| no |
| Auto-sleep through |
| no |
| What Telegram thinks your device is |
| no |
| Ditto for OS |
| no |
| Ditto for app |
| no |
| Scratch space for |
| no |
| When set, all endpoints require |
Throttling & cache (anti-flood)
Telegram bans accounts that hammer it. Defaults here are conservative — meant to keep you under the server-side limits without you having to think about it. Tune only if you know what you're doing.
Variable | Default | What it does |
|
| Master switch for all rate-limiting below |
|
| Min gap between any two outgoing requests |
|
| Random ±jitter added on top (kills metronome traffic patterns) |
|
| Min gap between sends to the same chat (Telegram's "1/sec/chat" ceiling, with margin) |
|
| Min gap between reads from the same chat. Stops single-channel scraping from monopolizing the read bucket. |
|
| On each |
|
| Cap on |
|
| Cap on |
|
| Cap on channel/group joins |
|
| Cap on channel/group creation |
|
| Cap on sends across all chats |
|
| Cap on read ops. Counted per server-side API call, not per tool call: |
|
| Persist resolved entities to disk |
|
| Mount |
|
| 7 days. Set |
|
| Telethon's reactive auto-sleep: if a |
How the layers stack:
Entity cache short-circuits resolveUsername — first lookup of
@somechannelcalls Telegram; every subsequent lookup is free. Survives container restarts via the/cachevolume.Per-method token buckets cap the dangerous methods. If you try to resolve 6 new usernames in one minute, the 6th sleeps until the oldest expires.
Per-chat send interval throttles sends to each chat to ≤1/sec (with margin).
Global gap + jitter humanizes the overall traffic shape.
Adaptive backoff: a single FLOOD_WAIT halves your effective rate for an hour. Three in a row → ÷8. Auto-recovers after an idle hour.
For bulk scraping work (the scenario that caused 22-hour bans before): the cache + bucket_resolve_per_min=5 combination is what saves you. Resolving 200 new channels takes ~40 minutes instead of getting you banned in 5.
Tools
JSON in, JSON out. All inputs are pydantic-validated — send garbage, get a 400 back with exactly what's wrong.
Chat references (chat, from_chat, to_chat) accept whatever Telethon accepts:
Format | Example |
Username |
|
Phone number |
|
t.me link |
|
Numeric ID |
|
Supergroup/channel ID |
|
Your own Saved Messages |
|
Numeric IDs only resolve for entities Telethon has already seen — i.e. cached in your session via a prior
@username/t.melookup, dialog list, or incoming message. MTProto needs anaccess_hash, not just an ID, and bare numbers don't carry one. Especially relevant for bots: pass@botusernamefirst (or callGET /api/dialogs/GET /api/entities?chat=@botonce) before referring to it by numeric ID. If you only have the bot's token and no username, hit Telegram's Bot APIgetMeto fetch the username, then use that.
Response shape
Every 2xx returns the resource directly. No {"result": ...} wrapper, no envelope. Lists are JSON arrays, singles are JSON objects.
Errors return {"detail": "..."} (FastAPI standard). Telegram RPC errors arrive as 502 with detail = {"telegram_error": "...", "message": "..."}.
Quick reference
Endpoint | Required params | What it does |
| — | Account profile. |
|
| Resolve a username/ID/link to a profile. |
|
| Bulk resolve, honoring the resolve-username bucket. |
| — | List dialogs. Optional: |
|
| Read recent messages. Optional: |
|
| Fetch a single message. |
|
| Download attachment as raw bytes (binary stream). Returns |
|
| Send a message. If |
|
| Forward messages. |
|
| Mark as read. Optional |
|
| Edit. |
|
| Bulk delete (body has the list). |
|
| Pin. Optional |
|
| Unpin. |
|
| React. Optional |
|
| Remove your reaction. |
|
| List members. Optional: |
|
| Create supergroup or channel. |
|
| Delete supergroup/channel you own (body). |
|
| Join public channel/group. |
|
| Join via private |
|
| Leave. |
| — | Resolve a channel's linked discussion group. |
|
| Ban a user. Optional |
|
| Lift a ban. |
|
| Kick (ban + immediate unban). |
|
| Grant admin rights + optional |
|
| Strip admin rights. |
|
| Create a poll. Optional |
|
| Vote (0-based indices). |
|
| Current vote counts. |
| — | Live rate-limit + cache state. |
| — | Flood-risk tier. |
| — | Prometheus exposition (no auth). |
|
| Stream incoming Telegram events. |
{chat} in path accepts the same formats as elsewhere: @username, numeric ID, me. Phone (+...) and t.me/... links need URL-encoding (%2B etc.) — usernames and IDs work inline.
HTTP API
Standard REST API. JSON in, JSON out. 2xx returns the resource directly; errors return {"detail": ...}.
If TELETHON_AUTH_KEY is set, every request (except /healthz) needs:
Authorization: Bearer your-secret-keyGET /api/me
Who am I right now.
GET /api/me{
"id": 123456789,
"type": "User",
"username": "psyb0t",
"first_name": "Ciprian",
"phone": "+40..."
}GET /api/entities
Resolve any chat reference to a full profile.
GET /api/entities?chat=@telegram{
"id": 1234567,
"type": "Channel",
"username": "telegram",
"title": "Telegram"
}GET /api/dialogs
GET /api/dialogs?limit=10&archived=falseParam | Type | Default | Description |
| int | 20 | How many dialogs (1–200) |
| bool | false | Include archived chats |
[
{
"id": 123456789,
"type": "User",
"username": "someone",
"first_name": "Some",
"last_name": "One",
"unread_count": 3,
"pinned": true,
"last_message": {
"id": 999,
"date": "2026-04-29T11:00:00+00:00",
"chat_id": 123456789,
"sender_id": 123456789,
"text": "hey",
"out": false,
"reply_to_msg_id": null,
"media": false,
"media_type": null
}
}
]GET /api/messages
GET /api/messages?chat=me&limit=5&search=helloParam | Type | Default | Description |
| string | required | Chat to read from |
| int | 20 | How many messages (1–200) |
| int | 0 | Start from this message ID (pagination) |
| string | — | Full-text search filter |
[
{
"id": 4242,
"date": "2026-04-29T12:00:00+00:00",
"chat_id": 12345,
"sender_id": 67890,
"text": "hello",
"out": false,
"reply_to_msg_id": null,
"media": false,
"media_type": null
}
]Newest first. Returns [] if nothing matches.
POST /api/messages
Send a message. The same endpoint handles text and files — if the body contains file_url, the URL is fetched and sent as media (with text becoming the caption); otherwise text is sent as a plain message.
POST /api/messages
Content-Type: application/json
{
"chat": "@psyb0t",
"text": "**hello** from a container",
"parse_mode": "md",
"silent": true,
"reply_to": 4241
}POST /api/messages
Content-Type: application/json
{
"chat": "@psyb0t",
"file_url": "https://example.com/photo.jpg",
"text": "look at this shit",
"silent": true
}Field | Type | Default | Description |
| string | required | Target chat |
| string | required if no | Message text or caption (1–4096 chars) |
| string | null | HTTPS URL to fetch and send as media. Telegram auto-picks media type from extension/MIME; override with |
| string | null |
|
| int | null | Message ID to reply to |
| bool | false | Send without notification |
| bool | true | Show link previews (text only) |
| string | null | ISO datetime in the future to schedule the send |
| bool | false | When sending a file: send as generic doc instead of letting Telegram pick |
| int | 52428800 | When sending a file: reject larger than this (max 2 GB) |
{
"id": 4242,
"date": "2026-04-29T12:00:00+00:00",
"chat_id": 12345,
"sender_id": 67890,
"text": "hello from a container",
"out": true,
"reply_to_msg_id": 4241,
"media": false,
"media_type": null
}PATCH /api/messages/{id}
Edit a message. Message ID goes in the URL, everything else in the body.
PATCH /api/messages/4242
Content-Type: application/json
{
"chat": "me",
"text": "fixed version",
"parse_mode": "md"
}Field | Type | Default | Description |
| string | required | Chat containing the message |
| string | required | New text (1–4096 chars) |
| string | null |
|
| bool | true | Show link previews |
{
"id": 4242,
"date": "2026-04-29T12:00:00+00:00",
"chat_id": 99999,
"sender_id": 123456789,
"text": "fixed version",
"out": true,
"reply_to_msg_id": null,
"media": false,
"media_type": null
}DELETE /api/messages
Delete messages by ID.
DELETE /api/messages
Content-Type: application/json
{
"chat": "@psyb0t",
"message_ids": [4242, 4243],
"revoke": true
}Field | Type | Default | Description |
| string | required | Chat containing the messages |
| list[int] | required | IDs to delete (max 100) |
| bool | true | Delete for everyone, not just yourself |
{ "deleted": 2, "requested": 2 }POST /api/messages/forward
POST /api/messages/forward
Content-Type: application/json
{
"from_chat": "@sourcechannel",
"to_chat": "me",
"message_ids": [101, 102, 103],
"silent": true
}Field | Type | Default | Description |
| string | required | Source chat |
| string | required | Destination chat |
| list[int] | required | IDs to forward (max 100) |
| bool | false | Forward without notification |
[
{
"id": 5001,
"date": "2026-04-29T12:01:00+00:00",
"chat_id": 99999,
"sender_id": 123456789,
"text": "forwarded content here",
"out": true,
"reply_to_msg_id": null,
"media": false,
"media_type": null
}
]POST /api/messages/read
Mark messages as read.
POST /api/messages/read
Content-Type: application/json
{ "chat": "@psyb0t", "max_id": 0 }Field | Type | Default | Description |
| string | required | Chat to mark as read |
| int | 0 | Mark up to this message ID. |
{ "ok": true }GET /api/participants
List members of a group or channel.
GET /api/participants?chat=-1001234567890&limit=50&search=johnParam | Type | Default | Description |
| string | required | Group or channel |
| int | 100 | Max members to return (1–1000) |
| string | — | Filter by name |
[
{ "id": 123456789, "type": "User", "username": "johndoe", "first_name": "John" }
]Large public channels may return a limited set or require admin rights.
POST /api/chats
Create a supergroup or broadcast channel.
POST /api/chats
Content-Type: application/json
{ "title": "my-group", "megagroup": true }Field | Type | Default | Description |
| string | required | Group name (1–255 chars) |
| bool | true |
|
{ "id": 1234567890, "type": "Channel", "title": "my-group" }DELETE /api/chats
Delete a supergroup or channel you own. Irreversible.
DELETE /api/chats
Content-Type: application/json
{ "chat": "-1001234567890" }{ "ok": true }POST /api/chats/join
Join a public channel or supergroup.
POST /api/chats/join
Content-Type: application/json
{ "chat": "@somegroup" }{ "ok": true }POST /api/chats/leave
Leave a channel or supergroup.
POST /api/chats/leave
Content-Type: application/json
{ "chat": "@somegroup" }{ "ok": true }Errors
Status | When |
| Bad JSON, validation failure, or Telethon said the input is nonsense. Body has details. |
| Missing or wrong Bearer token (only when |
| Unknown endpoint. |
| Telegram threw an RPC error ( |
Health
GET /healthz{ "status": "ok", "authorized": true }authorized: false means the container started but the session is fucked — bad string, revoked, or Telegram unreachable. Always public, no auth required.
Observability
GET /metrics
Prometheus exposition. Scrape it. No auth (publicly readable inside your cluster — if you need it locked down, put it behind your usual scrape-network policy).
Series exported:
telethon_plus_tool_calls_total{tool=...}telethon_plus_tool_errors_total{tool=...}telethon_plus_flood_events_total{bucket=...}telethon_plus_cache_hits_total/_misses_total/_entriestelethon_plus_throttle_multipliertelethon_plus_bucket_used{bucket=...}/_bucket_limit{bucket=...}telethon_plus_uptime_seconds
GET /api/throttle/status
Live state of every bucket, multiplier, recent flood events, cache stats:
{
"throttle": {
"enabled": true,
"adaptive": true,
"multiplier": 1.0,
"flood_events_1h": 0,
"buckets": {
"resolve_username": {"used": 0, "limit": 5, "window_seconds": 60},
"send": {"used": 0, "limit": 20, "window_seconds": 60}
},
"tracked_chats_send": 12,
"tracked_chats_read": 30,
"global_interval_ms": 50,
"per_chat_interval_ms": 1100,
"per_chat_read_interval_ms": 250,
"jitter_ms": 200
},
"cache": {"entries": 247},
"read_only": false,
"dry_run": false
}GET /api/account/health
{
"authorized": true,
"risk": "ok",
"multiplier": 1.0,
"flood_events_1h": 0,
"read_only": false,
"dry_run": false
}risk is ok (multiplier 1×), warning (≥2×), or high (≥8×).
Throttle response headers
Every /api/... response carries:
X-Throttle-MultiplierX-Throttle-Flood-Events-1hX-RateLimit-Remaining-<bucket>for each bucket
Lets clients self-throttle without polling /api/throttle/status.
Updates / webhooks
Two ways to receive incoming Telegram events (new messages, edits, deletes, chat actions):
WebSocket — /ws/updates
const ws = new WebSocket('ws://your-host:8080/ws/updates?token=YOUR_AUTH_KEY');
ws.onmessage = (e) => console.log(JSON.parse(e.data));If TELETHON_AUTH_KEY is set, pass it as ?token=. Browser WS clients can't set Authorization headers, hence query-string.
Multiple subscribers are supported — each gets its own queue. Slow consumers drop events at TELETHON_UPDATES_BUFFER_SIZE.
Outbound webhook — TELETHON_POST_TO_URL
Set the env var to your endpoint and every event gets POSTed there as JSON. Fire-and-forget — a slow or failing webhook never blocks Telethon's loop. Use for distributed workers, separate processes, anything that can't hold a WS open.
Event payload shape
{
"type": "NewMessage",
"message": {
"id": 4242,
"date": "2026-04-29T12:00:00+00:00",
"text": "hi",
"out": false,
"sender_id": 12345,
"chat_id": -1001234567890,
"reply_to_msg_id": null,
"media": false,
"media_type": null
},
"chat_id": -1001234567890
}For MessageEdited, MessageDeleted, ChatAction — same shape, fewer fields.
Safety switches
TELETHON_READ_ONLY=true
Every write endpoint returns 403. Reads, status, metrics still work. Killswitch for panic mode or for keeping a test deployment harmless.
TELETHON_DRY_RUN=true
Write endpoints accept the request, validate it, don't call Telegram, return {"dry_run": true, "would_...": {...}}. Useful for verifying scripts before pointing them at production.
MCP
Mounted at /mcp/ using the streamable HTTP transport. Every tool from the table above shows up automatically as an MCP tool with the same name and schema.
Point your agent at:
http://your-host:8080/mcp/Stateless — every request is independent, no session juggling. Drop it into Claude Desktop, a custom agent, anything that speaks MCP over HTTP. Works out of the box.
Agent integrations
The skill works in any agent that reads .agents/skills/, and installs natively in the clients below.
Claude Code
claude plugin marketplace add psyb0t/agents
claude plugin install telethon-plus@psyb0tClaude Code prompts for the telethon-plus server URL and, if auth is enabled, the bearer token — the token is stored in your OS keychain.
Codex
codex plugin marketplace add psyb0t/agents
codex plugin add telethon-plus@psyb0tInstalled via the marketplace, the skill invokes as $telethon-plus:telethon-plus. Codex also picks the skill up automatically with no install in any repo containing .agents/skills/, where it invokes as plain $telethon-plus.
OpenClaw
The skill is published to ClawHub on every release:
openclaw skills install @psyb0t/telethon-plusFor MCP clients that speak local stdio, the @psyb0t/telethon-plus plugin bridges to the service's /mcp/ endpoint:
openclaw plugins install clawhub:@psyb0t/telethon-plusThen set TELETHON_PLUS_URL (and TELETHON_AUTH_KEY if the server requires auth).
Development
make build # build psyb0t/telethon-plus:latest
make build-test # build psyb0t/telethon-plus:latest-test
make run # run locally on :8080 (reads .env)
make login # interactive login — writes TELETHON_SESSION to .env automatically
make lint # flake8 + pyright
make format # isort + black
make test # run integration tests in Docker
make clean # remove built imagesTests
Real tests. Real Telegram. No mocking bullshit.
tests/ spins up the container and hammers both REST and MCP with your actual account. Messages get sent and deleted. If anything breaks, you'll know.
Setup:
cp .env.example .env
$EDITOR .env # needs TELETHON_API_ID, TELETHON_API_HASH, TELETHON_SESSION, TEST_CHAT
make testTEST_CHAT is where test messages land. Use me for Saved Messages — private, yours, no one else sees it. All chat reference formats from the Tools section work here.
make test builds both images and runs pytest inside Docker with the socket mounted. No setup beyond .env. If credentials are missing, the suite skips cleanly.
Test file | What it beats on |
| Container boots, auth succeeds, OpenAPI spec has all the routes. |
| Validation errors, extra fields rejected, send → edit → fetch → delete roundtrip, dialogs, entity resolution, public channel read, group create/delete, participants. |
| MCP streamable HTTP: tool discovery, |
| Auth middleware: 401 on missing/wrong token, 200 on correct token, |
License
WTFPL — do whatever the fuck you want.
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- Alicense-qualityDmaintenanceMCP server that connects AI assistants to your real Telegram account via User API (MTProto). Features default-deny ACL with per-chat permissions, message search, file sending, forwarding, media downloads, and rate limiting.Last updated1MIT
- Alicense-qualityBmaintenanceA Telegram integration for Claude, Cursor, and other MCP-compatible clients, exposing account, chat, message, contact, media, folder, and admin operations through the Model Context Protocol using Telethon.Last updatedApache 2.0
- Alicense-qualityCmaintenanceEnables AI assistants to interact with Telegram accounts, chats, messages, media, and more via MCP, using Telethon.Last updatedApache 2.0
- Alicense-qualityCmaintenanceIntegrates Telegram user account with MCP, exposing operations like reading and sending messages, managing chats, and more via stdio or SSE transport.Last updatedApache 2.0
Related MCP Connectors
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API
MCP server exposing the Backtest360 engine API as tools for AI agents.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/psyb0t/docker-telethon-plus'
If you have feedback or need assistance with the MCP directory API, please join our Discord server