Productivity

Telegram bot webhook setup: complete guide for developers

Learn telegram bot webhook setup step by step. Configure setWebhook, verify with getWebhookInfo, handle HTTPS, and troubleshoot common errors.

TeleClaw

TeleClaw Team

June 17, 2026

Telegram bot webhook setup: complete guide for developers

Telegram bot webhook setup connects your server to Telegram’s update stream so messages arrive in real time instead of on a polling loop. If you are building a custom bot with the Bot API, webhooks are the standard production path: Telegram POSTs each update to your HTTPS endpoint, and your code responds.

This guide walks through prerequisites, registration, a working handler example, verification, troubleshooting, and when a managed platform like TeleClaw makes more sense than self-hosting.

Key takeaways

  • Webhooks and long polling are mutually exclusive. Setting a webhook disables getUpdates until you remove it.
  • HTTPS is mandatory. Your endpoint needs TLS 1.2+, a matching certificate, and port 443, 80, 88, or 8443.
  • Register with setWebhook, verify with getWebhookInfo. Check last_error_message when updates stop flowing.
  • Use secret_token to confirm requests come from Telegram, not random scanners hitting your URL.
  • No-code alternative: TeleClaw handles hosting and delivery so you skip the server layer entirely.

Webhooks vs long polling: which to choose

Telegram offers two ways to receive updates. According to the Bots FAQ, you pick one method per bot. You cannot run both at the same time.

FactorWebhookLong polling (getUpdates)
Connection directionTelegram pushes to your serverYour server pulls from Telegram
Public HTTPS URLRequiredNot required
SSL certificateRequiredNot required
LatencyLower (instant push)Depends on poll interval
Best forProduction, high trafficLocal dev, prototypes
FirewallMust accept inbound POST from TelegramOutbound HTTPS only

Long polling is the fastest way to prototype. Your bot calls getUpdates in a loop, processes each batch, and advances the offset. No domain, no certificate, no open port.

Webhooks flip the model. Telegram sends an HTTPS POST to your URL whenever someone messages the bot. That removes idle polling requests and cuts reaction time, which matters for support bots, payment flows, and group moderation at scale.

If you are still registering the bot itself, start with our guide to creating a Telegram bot to get a token from BotFather before continuing here.

Prerequisites for telegram bot webhook setup

Before you call setWebhook, confirm your infrastructure meets Telegram’s requirements from the official webhook guide:

  • Bot token from @BotFather (see the create-bot guide linked above).
  • Public domain with a valid TLS certificate. Self-signed certs work only if you upload the public key via the certificate parameter.
  • Supported port on your server: 443 (default), 80, 88, or 8443. Other ports are rejected.
  • Certificate CN or SAN must match the domain in your webhook URL. Wildcard certs may not work. Redirects are not supported.
  • Inbound POST access from Telegram subnets 149.154.160.0/20 and 91.108.4.0/22.

For local development, expose localhost through a tunnel (ngrok, Cloudflare Tunnel, or similar) that gives you a public HTTPS URL. Test that the tunnel returns HTTP 200 for POST requests before registering the webhook.

Step 1: Build your webhook endpoint

Your server needs a route that accepts POST requests, parses the JSON Update object, and returns HTTP 200 quickly. Slow handlers cause Telegram to retry and eventually report errors in getWebhookInfo.

Minimal Node.js example with Express:

import express from 'express';

const app = express();
app.use(express.json());

const SECRET = process.env. WEBHOOK_SECRET;

app.post('/webhook', (req, res) => {
 if (SECRET && req.get('X-Telegram-Bot-Api-Secret-Token')!== SECRET) {
 return res.sendStatus(403);
 }

 const update = req.body;
 // Process update.message, update.callback_query, etc.
 console.log('Update ID:', update.update_id);

 res.sendStatus(200);
});

app.listen(443);

Python with Flask follows the same pattern: read JSON from request, validate the secret header if configured, process the update, return 200.

Respond fast. Heavy work (database writes, AI API calls) should go to a background queue. Telegram expects a quick acknowledgment. You can also reply inline by returning a JSON body with a method field instead of making a separate API call, as described in the Bot API webhook notes.

Step 2: Telegram bot configure webhook with setWebhook

Once your endpoint is live, register it with the Bot API. Replace <TOKEN> and the URL with your values.

Using curl:

curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
 -H "Content-Type: application/json" \
 -d '{
 "url": "https://yourdomain.com/webhook",
 "secret_token": "my_random_secret_abc123",
 "max_connections": 40,
 "allowed_updates": ["message", "callback_query", "chat_join_request"],
 "drop_pending_updates": false
 }'

Parameter reference:

  • url (required): Your HTTPS endpoint. Use an empty string to remove the webhook.
  • secret_token (optional): 1-256 characters (A-Z, a-z, 0-9, _, -). Telegram sends it in the X-Telegram-Bot-Api-Secret-Token header.
  • max_connections (optional): 1-100 simultaneous connections. Default is 40.
  • allowed_updates (optional): Limit which update types you receive. Reduces payload size if you only handle messages.
  • drop_pending_updates (optional): Set true to discard queued updates when switching webhooks.
  • certificate (optional): Upload your public key file for self-signed certificates.

A successful response looks like {"ok":true,"result":true,"description":"Webhook was set"}.

Step 3: Verify with getWebhookInfo

Always confirm registration immediately. This is your first troubleshooting tool when updates stop arriving.

curl "https://api.telegram.org/bot<TOKEN>/getWebhookInfo"

Example response:

{
 "ok": true,
 "result": {
 "url": "https://yourdomain.com/webhook",
 "has_custom_certificate": false,
 "pending_update_count": 0,
 "max_connections": 40,
 "allowed_updates": ["message", "callback_query", "chat_join_request"]
 }
}

Watch these fields:

  • url: Empty means no webhook is active (bot is on long polling).
  • pending_update_count: Queued updates waiting for delivery. A rising number signals delivery failures.
  • last_error_date and last_error_message: The most recent failure reason. Fix the root cause, then Telegram retries automatically.
  • ip_address: Which Telegram IP is currently hitting your endpoint.

Send a test message to your bot from a real Telegram account. If pending_update_count stays at zero and your server logs show the POST, the telegram bot webhook setup is working.

Telegram bot webhook example: join request handler

Join-request bots (Guardian-style admission flows) need the chat_join_request update type. Our Guardian bot guide covers the product side. Here is the webhook wiring.

Register with join requests enabled:

curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" \
 -d "url=https://yourdomain.com/webhook" \
 -d "allowed_updates=[\"chat_join_request\",\"message\"]"

Handler logic (pseudocode):

if (update.chat_join_request) {
 const { chat, from, invite_link } = update.chat_join_request;
 // Run screening logic, then approve or decline via Bot API
 await approveChatJoinRequest(chat.id, from.id);
}

Telegram delivers join requests as push updates, so webhooks are a natural fit for admission bots that must respond before the request expires.

Telegram bot remove webhook and switch back to polling

Need to debug locally with getUpdates? Remove the webhook first.

Option A with deleteWebhook:

curl -X POST "https://api.telegram.org/bot<TOKEN>/deleteWebhook" \
 -d "drop_pending_updates=true"

Option B with setWebhook and empty URL:

curl "https://api.telegram.org/bot<TOKEN>/setWebhook?url="

Both methods re-enable long polling. If you skip this step, getUpdates returns nothing because the webhook is still registered to your production URL.

Troubleshooting common webhook errors

When getWebhookInfo shows errors, match the message to a fix:

Error symptomLikely causeFix
SSL error / certificate verify failedIncomplete cert chain or expired certInstall full chain (Let’s Encrypt certbot handles this). Test with an SSL checker.
Wrong response from webhook: 500Server crash on POSTFix handler bugs. Return 200 even if processing fails internally.
Wrong response: 404URL path mismatchEnsure the registered URL matches your route exactly.
Connection timed outFirewall or wrong portOpen 443 to Telegram subnets. Confirm the process listens on a supported port.
Too many redirectsHTTP to HTTPS redirect loopPoint webhook URL directly to the final HTTPS endpoint.
pending_update_count climbingEndpoint was down during trafficFix endpoint, then optionally call setWebhook with drop_pending_updates=true.

Run getWebhookInfo on a schedule in production. Catching last_error_message early prevents hours of silent message loss.

Skip the server: managed bots with TeleClaw

Not every bot needs custom webhook infrastructure. If your goal is an AI assistant for a group or business channel, hosting and update delivery are solved problems.

TeleClaw connects your BotFather token to a managed runtime powered by OpenClaw. You configure personality, knowledge base, and moderation rules in the dashboard. The platform handles HTTPS endpoints, scaling, and AI model routing. Add @claw as a group admin and go live without writing a webhook handler.

Explore what a managed bot can do on the TeleClaw features page. For a full no-code walkthrough, see our Telegram chatbot without code guide.

Custom webhooks still make sense when you need full control: proprietary backends, regulated data residency, or non-standard update processing. For everything else, the operational cost of cert management, monitoring, and retry handling adds up fast.

Conclusion

Telegram bot webhook setup comes down to four steps: deploy an HTTPS endpoint, call setWebhook, verify with getWebhookInfo, and monitor for errors. Use secret_token for request validation, limit allowed_updates to what you process, and keep handlers fast.

Developers who want production push delivery without running servers can use TeleClaw instead. Paste your token, configure AI behavior, and focus on what the bot says rather than how updates arrive.

Ready to launch an AI bot without managing webhooks? Add @claw to your Telegram group →

FAQ

Frequently Asked Questions

How to set up telegram bot webhook?
Deploy an HTTPS endpoint that accepts POST requests and returns HTTP 200. Call setWebhook with your URL and bot token: https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://yourdomain.com/webhook. Confirm with getWebhookInfo. Your server must use TLS 1.2+, a valid certificate, and one of the supported ports (443, 80, 88, or 8443).
What is the difference between webhook and long polling?
Long polling means your bot repeatedly calls getUpdates to fetch new messages. Webhooks mean Telegram pushes each update to your HTTPS URL as it arrives. You can only use one method at a time. Polling is easier for local development. Webhooks deliver lower latency and scale better for production bots with steady traffic.
How do I remove a telegram bot webhook?
Call deleteWebhook on the Bot API, or call setWebhook with an empty url parameter. Both switch the bot back to getUpdates long polling. Add drop_pending_updates=true if you want to discard queued updates instead of receiving them after the switch.
Why is my telegram bot webhook not receiving updates?
Run getWebhookInfo and check last_error_message. Common causes include an invalid SSL certificate, wrong port, redirects on your URL, a server that returns non-200 responses, or a firewall blocking Telegram IP ranges. Fix the endpoint first, then re-register the webhook.
Do I need a webhook to run an AI Telegram bot?
Only if you self-host custom bot code. Platforms like TeleClaw handle hosting, HTTPS, and update delivery for you. Add @claw to your group, paste your BotFather token in the dashboard, and the platform manages the webhook layer while you configure AI behavior.

More Reading

Keep Reading

All articles