--- title: "Telegram Bots" date: 2026-12-05T00:00:00Z draft: false description: "Telegram Bot API quick reference: BotFather, polling vs webhooks, sending messages and keyboards, commands, groups and limits, with copy-paste snippets." categories: ["tools"] tags: ["telegram", "bot", "api", "webhook", "automation", "cli"] --- ## Overview A Telegram bot is an account controlled over a plain HTTPS API: you call `https://api.telegram.org/bot/METHOD` and receive updates either by polling or by a webhook. No SDK is required; every example here works with `curl`. ## Setup ```text 1. In Telegram, open @BotFather and send /newbot pick a display name, then a username ending in "bot" 2. BotFather replies with the token 123456:ABC-DEF... (a password: never commit it) 3. Open your bot and press Start (a bot cannot message you first) 4. Optional: /setcommands, /setprivacy, /setjoingroups, /revoke (new token), /mybots ``` **Warning:** the token is a password. Never commit it, paste it into a chat or leave it in shell history; keep it in an environment variable or a `chmod 600` file outside the repo. The snippets below assume `TG_TOKEN`, `TG_CHAT` and `API="https://api.telegram.org/bot$TG_TOKEN"` are set. ## Quick Start ```bash # Check the token curl -s "$API/getMe" # Press Start in the bot, then find your chat id curl -s "$API/getUpdates" | jq '.result[].message.chat | {id, type, username}' # Send a message curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d text="Build finished" ``` Every response is JSON: `{"ok": true, "result": ...}` or `{"ok": false, "error_code": 400, "description": "..."}`. Always check `ok`. ## Receiving Updates Two mutually exclusive ways. Unreceived updates are kept for at most 24 hours. | | Long polling (`getUpdates`) | Webhook (`setWebhook`) | |---|---|---| | Needs a public URL | No | Yes, HTTPS, ports 443, 80, 88 or 8443 | | Good for | Local dev, scripts, laptops | Servers, serverless, production | | Gotcha | Only one poller per bot | Polling stops working while a webhook is set | ### Long Polling ```python import os, time, requests API = f"https://api.telegram.org/bot{os.environ['TG_TOKEN']}" offset = None while True: r = requests.get(f"{API}/getUpdates", params={"timeout": 50, "offset": offset}, timeout=60).json() for u in r.get("result", []): offset = u["update_id"] + 1 # acknowledge by moving the offset msg = u.get("message") if msg and "text" in msg: requests.post(f"{API}/sendMessage", json={"chat_id": msg["chat"]["id"], "text": "You said: " + msg["text"]}) time.sleep(0.2) ``` ### Webhook ```bash # Register (secret_token: 1-256 chars of A-Z a-z 0-9 _ -) curl -s "$API/setWebhook" \ -d url="https://example.com/tg/hook" \ -d secret_token="PASTE_LONG_RANDOM_SECRET" \ -d allowed_updates='["message","callback_query"]' \ -d drop_pending_updates=true curl -s "$API/getWebhookInfo" # pending_update_count, last_error_message, last_error_date curl -s "$API/deleteWebhook" # go back to polling ``` Telegram sends an HTTPS POST with a JSON `Update` and the header `X-Telegram-Bot-Api-Secret-Token`. Answer with a 2xx; otherwise it retries and eventually gives up. ```python # Minimal receiver (FastAPI): check the secret header, then handle the update import os, requests from fastapi import FastAPI, Header, HTTPException, Request app = FastAPI() API = f"https://api.telegram.org/bot{os.environ['TG_TOKEN']}" @app.post("/tg/hook") async def hook(req: Request, x_telegram_bot_api_secret_token: str = Header(None)): if x_telegram_bot_api_secret_token != os.environ["TG_SECRET"]: raise HTTPException(status_code=403) update = await req.json() msg = update.get("message") if msg and msg.get("text") == "/start": requests.post(f"{API}/sendMessage", json={"chat_id": msg["chat"]["id"], "text": "Hello!"}) return {"ok": True} ``` You can also reply inside the webhook response by returning JSON with a `method` field: ```json {"method": "sendMessage", "chat_id": 123456789, "text": "Replied in the response"} ``` ### Local Webhook Testing ```bash # Expose localhost over HTTPS (any tunnel works), then register the https URL it prints cloudflared tunnel --url http://localhost:8000 ngrok http 8000 ``` ## Sending Messages ```bash # Formatting: parse_mode=HTML is the least painful curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d parse_mode=HTML \ --data-urlencode text='Deploy done: build 42 main' # Reply to a message / send into a forum topic curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d text="Re:" -d reply_to_message_id=123 curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d text="In topic" -d message_thread_id=45 # Silent, no link preview curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d text="FYI" -d disable_notification=true \ -d 'link_preview_options={"is_disabled":true}' # Files: path upload, or a file_id / URL curl -s "$API/sendDocument" -F chat_id="$TG_CHAT" -F document=@report.pdf -F caption="Report" curl -s "$API/sendPhoto" -F chat_id="$TG_CHAT" -F photo=@shot.png # Edit and delete curl -s "$API/editMessageText" -d chat_id="$TG_CHAT" -d message_id=123 -d text="Updated" curl -s "$API/deleteMessage" -d chat_id="$TG_CHAT" -d message_id=123 ``` ### Formatting Modes | `parse_mode` | Bold | Code | Must escape | |---|---|---|---| | `HTML` | `x` | `x` | `<`, `>`, `&` | | `MarkdownV2` | `*x*` | `` `x` `` | `_ * [ ] ( ) ~ > # + - = \| { } . !` with `\` | | (none) | none | none | nothing | ```python import re def md2(s): return re.sub(r'([_*\[\]()~`>#+\-=|{}.!\\])', r'\\\1', s) # MarkdownV2 escape for plain text parts ``` ## Keyboards & Callbacks ```bash # Inline buttons under a message curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d text="Deploy to prod?" \ -d 'reply_markup={"inline_keyboard":[[{"text":"Yes","callback_data":"deploy:yes"},{"text":"No","callback_data":"deploy:no"}],[{"text":"Open build","url":"https://example.com/build/42"}]]}' ``` A press arrives as `update.callback_query` (`id`, `data`, `from`, `message`). You must answer it, or the client keeps showing a spinner: ```bash curl -s "$API/answerCallbackQuery" -d callback_query_id="$CQ_ID" -d text="Deploying..." # toast curl -s "$API/editMessageText" -d chat_id="$TG_CHAT" -d message_id=123 -d text="Deploying..." # replace the message ``` `callback_data` is 1-64 bytes: send an id or a short code, not a payload. ```bash # Reply keyboard (replaces the phone keyboard) and removing it -d 'reply_markup={"keyboard":[["Status","Help"]],"resize_keyboard":true}' -d 'reply_markup={"remove_keyboard":true}' ``` ## Commands ```bash # Menu shown when users type "/" curl -s "$API/setMyCommands" -H 'Content-Type: application/json' \ -d '{"commands":[{"command":"start","description":"Start"},{"command":"status","description":"Show status"}]}' ``` ```python # Parse "/status@mybot extra args" in a handler text = msg["text"] if text.startswith("/"): cmd, _, args = text.partition(" ") cmd = cmd.split("@")[0].lstrip("/").lower() # strips the @botname added in groups ``` ## Groups, Channels & Chat IDs ```text Private chat positive id; the user must press Start first Group negative id (-123456789) Supergroup/chan id starts with -100 (-1001234567890) Channel add the bot as admin with "Post messages" to post; chat_id can be @channelusername Find an id send a message in the chat, then getUpdates (webhook off), or forward it to a bot that shows ids Group upgraded a group that becomes a supergroup gets a new id (error mentions migrate_to_chat_id) ``` Privacy mode is on by default: in groups the bot only sees commands, replies to it, mentions and service messages. Turn it off with `/setprivacy` in BotFather (then re-add the bot to the group), or make the bot an admin. ## Limits | Limit | Value | |---|---| | Message text | 4096 characters (after entity parsing) | | Same chat | about 1 message per second (bursts end in 429) | | Same group | 20 messages per minute | | Broadcast | about 30 messages per second; paid broadcasts raise it | | Upload by the bot | 50 MB per file | | Download with `getFile` | 20 MB per file | | `callback_data` | 1-64 bytes | | Undelivered updates kept | 24 hours | On HTTP 429 the response has `parameters.retry_after` (seconds): sleep that long and retry. ## Troubleshooting | Symptom | Cause | Fix | |---|---|---| | `401 Unauthorized` | Wrong or revoked token | Copy it again, or `/revoke` in BotFather | | `404 Not Found` on every method | Malformed token or URL (missing `bot` prefix, stray spaces) | URL is `/bot/METHOD`, token as BotFather gave it | | `403 bot was blocked by the user` | User blocked the bot | Stop sending to that chat | | `400 chat not found` | User never pressed Start, or wrong id | Have them start the bot; recheck the id | | `400 can't parse entities` | Unescaped characters in Markdown or HTML | Escape, or send without `parse_mode` | | `409 Conflict: terminated by other getUpdates` | Two pollers, or a webhook is set | One poller only; `deleteWebhook` before polling | | `getUpdates` returns nothing | A webhook is registered | `getWebhookInfo`, then `deleteWebhook` | | Webhook never fires | Not HTTPS, bad port, bad certificate | Check `last_error_message` in `getWebhookInfo` | | Buttons show a spinner | `answerCallbackQuery` not called | Call it on every callback | | Group messages ignored | Privacy mode | `/setprivacy` > Disable, then re-add the bot | | `429 Too Many Requests` | Over the rate limit | Honour `retry_after`, queue sends | | Token leaked | Committed or pasted in chat | `/revoke` immediately, then update every deployment | ## Quick Reference | Item | Value | |---|---| | Base URL | `https://api.telegram.org/bot/METHOD` | | Files | `https://api.telegram.org/file/bot/` (path from `getFile`) | | Methods | `getMe`, `sendMessage`, `sendPhoto`, `sendDocument`, `editMessageText`, `deleteMessage`, `answerCallbackQuery`, `setMyCommands` | | Updates | `getUpdates` (poll) or `setWebhook` (push), never both | | Webhook auth | header `X-Telegram-Bot-Api-Secret-Token` equals your `secret_token` | | Webhook ports | 443, 80, 88, 8443 | | Reply from webhook | JSON body with `"method": "sendMessage", ...` | | New token | `/revoke` in @BotFather | ## See Also - [Bots: an introduction for developers](https://core.telegram.org/bots) - [Telegram Bot API reference](https://core.telegram.org/bots/api) - [Bot features](https://core.telegram.org/bots/features) (commands, keyboards, privacy mode, BotFather commands) - [Guide to webhooks](https://core.telegram.org/bots/webhooks) - [Bots FAQ](https://core.telegram.org/bots/faq) (limits, broadcasting, files) - [From BotFather to Hello World](https://core.telegram.org/bots/tutorial) - [Inline bots](https://core.telegram.org/bots/inline), [Mini Apps](https://core.telegram.org/bots/webapps), [Payments](https://core.telegram.org/bots/payments) - [curl](/tools/curl/) and [jq](/tools/jq/) for testing the API