Polling or webhook
A Telegram bot gets its updates (messages, button presses, joins) in one of two ways:
getUpdates: your bot asks Telegram for new updates in a loop (long polling). Simple, works behind any firewall, but needs a process running all the time.setWebhook: Telegram sends each update to your HTTPS URL as it happens. No loop, scales to zero, and fits serverless hosting.
You can't use both: while a webhook is set, getUpdates fails with 409 Conflict. The trade-offs are the same as in webhooks vs. polling.
Set the webhook
Create the bot with @BotFather (/newbot) to get its token, then register your URL:
curl "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
-d "url=https://bot.example.com/telegram" \
-d "secret_token=$(openssl rand -hex 32)" \
-d 'allowed_updates=["message","callback_query"]'Save the secret you generated; you need it to check requests.
| Parameter | What it does |
|---|---|
url | Your HTTPS endpoint. Telegram only connects to ports 443, 80, 88 and 8443. |
secret_token | 1 to 256 characters (A-Z, a-z, 0-9, _, -). Sent back in a header on every request. |
allowed_updates | Only the update types you handle, so you aren't sent the rest. |
max_connections | Parallel connections Telegram may open, 1 to 100 (default 40). |
drop_pending_updates | Discards updates that queued up while the bot was down. |
certificate | Your public certificate, only when you use a self-signed one. |
Verify every request
Your webhook URL is public, so anyone could send it fake updates. With a secret_token set, Telegram adds the header X-Telegram-Bot-Api-Secret-Token to every request. Compare it with your secret in constant time and reject anything else:
import { timingSafeEqual } from "node:crypto";
export async function POST(req) {
const got = Buffer.from(req.headers.get("x-telegram-bot-api-secret-token") ?? "");
const want = Buffer.from(process.env.TELEGRAM_WEBHOOK_SECRET);
if (got.length !== want.length || !timingSafeEqual(got, want)) {
return new Response("forbidden", { status: 403 });
}
const update = await req.json();
// queue the work, then answer quickly
return new Response("ok");
}Never put the bot token itself in the webhook path as the only protection; the token controls the whole bot.
What an update looks like
{
"update_id": 912345678,
"message": {
"message_id": 42,
"from": { "id": 111222333, "first_name": "Ada" },
"chat": { "id": 111222333, "type": "private" },
"date": 1793952000,
"text": "/start"
}
}Every update has an increasing update_id. Use it to skip duplicates: if a delivery times out, Telegram sends the same update again. See idempotency.
Reply to the user
Call the Bot API's sendMessage with the chat.id from the update. For a quick reply you can also answer the webhook request itself with a method in the body:
{ "method": "sendMessage", "chat_id": 111222333, "text": "Welcome!" }That saves a request, but you don't learn whether it worked. For anything slow, answer the webhook with 200 straight away and do the work in the background.
When updates stop arriving
Ask Telegram what it last saw:
curl "https://api.telegram.org/bot<BOT_TOKEN>/getWebhookInfo"Look at pending_update_count (updates waiting for you), last_error_date and last_error_message. The usual causes:
- "Wrong response from the webhook: 500" or a timeout: your handler crashed or was too slow. Telegram keeps retrying, and updates pile up.
- SSL errors: the certificate is self-signed or the chain is incomplete.
- A port other than 443, 80, 88 or 8443.
- A redirect: Telegram doesn't follow it. Register the final URL, with the exact scheme and trailing slash your server expects.
deleteWebhook switches back to getUpdates, which is handy while debugging; add drop_pending_updates=true to clear the queue.
Don't lose updates when your bot is down
Telegram keeps pending updates for 24 hours at most. If your bot is down longer, or you deploy a bug that answers 500 to everything, updates are gone.
With HookStead in front, every update is stored the moment it arrives and delivered to your bot with retries:
- Create a source with the Secret header option, header
X-Telegram-Bot-Api-Secret-Token, and your secret. HookStead rejects requests without it and doesn't forward the header. - Turn on deduplication with the custom JSON path
update_id, so repeats are answered without reaching your bot twice. - Call
setWebhookwith the source's URL, and add your bot as a destination.
HookStead answers Telegram itself, so the "reply in the webhook response" shortcut above doesn't apply; call sendMessage instead. See any provider for the source options.
Frequently asked questions
- How do I set a webhook for a Telegram bot?
- Call https://api.telegram.org/bot<token>/setWebhook with url set to your HTTPS endpoint, and set secret_token so you can verify requests.
- Why does getUpdates return 409 Conflict?
- A webhook is set. Telegram delivers updates either by webhook or by getUpdates, not both. Call deleteWebhook to go back to polling.
- Which ports can a Telegram webhook use?
- Only 443, 80, 88 and 8443, over HTTPS.
- How do I check why my Telegram webhook fails?
- Call getWebhookInfo. last_error_message and pending_update_count show what went wrong and how many updates are waiting.