Overview

A Telegram bot is an account controlled over a plain HTTPS API: you call https://api.telegram.org/bot<TOKEN>/METHOD and receive updates either by polling or by a webhook. No SDK is required; every example here works with curl.

Setup

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

# 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 URLNoYes, HTTPS, ports 443, 80, 88 or 8443
Good forLocal dev, scripts, laptopsServers, serverless, production
GotchaOnly one poller per botPolling stops working while a webhook is set

Long Polling

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

# 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.

# 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:

{"method": "sendMessage", "chat_id": 123456789, "text": "Replied in the response"}

Local Webhook Testing

# 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

# Formatting: parse_mode=HTML is the least painful
curl -s "$API/sendMessage" -d chat_id="$TG_CHAT" -d parse_mode=HTML \
  --data-urlencode text='<b>Deploy</b> done: <a href="https://example.com/build/42">build 42</a> <code>main</code>'

# 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_modeBoldCodeMust escape
HTML<b>x</b><code>x</code><, >, &
MarkdownV2*x*`x`_ * [ ] ( ) ~ > # + - = | { } . ! with \
(none)nonenonenothing
import re
def md2(s): return re.sub(r'([_*\[\]()~`>#+\-=|{}.!\\])', r'\\\1', s)    # MarkdownV2 escape for plain text parts

Keyboards & Callbacks

# 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:

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.

# 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

# 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"}]}'
# 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

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

LimitValue
Message text4096 characters (after entity parsing)
Same chatabout 1 message per second (bursts end in 429)
Same group20 messages per minute
Broadcastabout 30 messages per second; paid broadcasts raise it
Upload by the bot50 MB per file
Download with getFile20 MB per file
callback_data1-64 bytes
Undelivered updates kept24 hours

On HTTP 429 the response has parameters.retry_after (seconds): sleep that long and retry.

Troubleshooting

SymptomCauseFix
401 UnauthorizedWrong or revoked tokenCopy it again, or /revoke in BotFather
404 Not Found on every methodMalformed token or URL (missing bot prefix, stray spaces)URL is /bot<TOKEN>/METHOD, token as BotFather gave it
403 bot was blocked by the userUser blocked the botStop sending to that chat
400 chat not foundUser never pressed Start, or wrong idHave them start the bot; recheck the id
400 can't parse entitiesUnescaped characters in Markdown or HTMLEscape, or send without parse_mode
409 Conflict: terminated by other getUpdatesTwo pollers, or a webhook is setOne poller only; deleteWebhook before polling
getUpdates returns nothingA webhook is registeredgetWebhookInfo, then deleteWebhook
Webhook never firesNot HTTPS, bad port, bad certificateCheck last_error_message in getWebhookInfo
Buttons show a spinneranswerCallbackQuery not calledCall it on every callback
Group messages ignoredPrivacy mode/setprivacy > Disable, then re-add the bot
429 Too Many RequestsOver the rate limitHonour retry_after, queue sends
Token leakedCommitted or pasted in chat/revoke immediately, then update every deployment

Quick Reference

ItemValue
Base URLhttps://api.telegram.org/bot<TOKEN>/METHOD
Fileshttps://api.telegram.org/file/bot<TOKEN>/<file_path> (path from getFile)
MethodsgetMe, sendMessage, sendPhoto, sendDocument, editMessageText, deleteMessage, answerCallbackQuery, setMyCommands
UpdatesgetUpdates (poll) or setWebhook (push), never both
Webhook authheader X-Telegram-Bot-Api-Secret-Token equals your secret_token
Webhook ports443, 80, 88, 8443
Reply from webhookJSON body with "method": "sendMessage", ...
New token/revoke in @BotFather

See Also