Skip to content
TGDirectory
DirectoryCategoriesRankingsBlogAPI
Log inList your channel
TGDirectoryMenu
List Your Channel, Group or Bot/MiniGame

Your channels

  • My Channels

Account

Log InRegister

Discover

  • View all Telegram Channels
  • Categories
  • Best Telegram Channels
  • Crypto Channels 2026
  • Top Rated
  • Recently Added
  • Articles & Guides

Company

  • Contact Us

TGDirectory — find, compare and discover Telegram channels.

  1. Home/
  2. Blog/
  3. Bots & Mini Apps/
  4. How to Set a Webhook for a Telegram Bot (and When to Use Polling)
Bots & Mini Apps

How to Set a Webhook for a Telegram Bot (and When to Use Polling)

How Telegram delivers updates to a bot, how to set, test and secure a webhook step by step, how to fix the usual errors, and when long polling is the better choice.

TGDirectory31 Oct 202619 min read
Bots & Mini AppsHow to Set a Webhook for a Telegram Bot (and When to Use Polling)

To set a webhook, you tell Telegram's Bot API the HTTPS address of your server by calling the setWebhook method with your bot token, and from then on Telegram sends every new update to that address as it happens. Polling is the alternative: your bot repeatedly asks Telegram for new updates with getUpdates. Webhooks suit bots running on a public server; polling suits development, small bots and machines that cannot accept incoming connections.

This guide explains both delivery methods, walks through setting and checking a webhook without assuming a particular programming language, covers security, and then works through each common failure with its own fix. It describes methods and parameters in words rather than code. The authoritative reference is Telegram's Bot API documentation on core.telegram.org, which you should keep open while you work, because parameters are added over time.

How a bot receives updates

Everything that happens to a bot arrives as an update: a new message, a button press, a user joining a group the bot is in, a payment, an inline query. Each update has a numeric update ID that increases over time.

Telegram holds updates for your bot until they are delivered. The Bot API documentation says incoming updates are kept on Telegram's servers until the bot receives them, but not for longer than 24 hours. If your bot is down for longer than that, the oldest updates are gone.

There are two mutually exclusive ways to collect them:

  • Long polling. Your bot calls getUpdates. If updates are waiting, they come back at once. If not, Telegram holds the request open for up to the timeout you set, and answers as soon as something arrives. Your bot then calls again, telling Telegram which update it got up to by passing an offset one higher than the last update ID it processed. That offset is what marks earlier updates as delivered.
  • Webhook. You register a URL. Telegram makes an HTTPS POST request to it for each update, with the update in the request body as JSON. Your server answers, and Telegram moves on.

You cannot use both at once. While a webhook is set, getUpdates returns an error. To go back to polling, you delete the webhook first.

Webhook or polling: how to choose

Neither is "better". They trade different things.

Choose long polling when

  • You are developing on your own computer. It needs no public address, no certificate and no open port.
  • Your bot runs behind a home router, a company firewall or a network you do not control. Polling only makes outgoing connections.
  • You run one small bot process and are happy for it to keep a connection open.
  • You want the simplest thing that works. Most bot libraries can start polling with one setting.

Choose a webhook when

  • The bot runs on a server with a public HTTPS address, or on a serverless platform that only wakes up when a request arrives. Polling cannot work there, because nothing is running to poll.
  • You want to scale out. Several server instances behind a load balancer can share incoming webhook requests; several pollers would compete for the same updates.
  • You want no idle traffic. A webhook does nothing until there is something to deliver.

What does not decide it

Speed is rarely a reason. Well-configured long polling delivers updates almost as soon as they arrive, because the open request is answered the moment an update comes in. Choose on where the bot runs, not on latency.

Before you start

Gather these things before setting a webhook:

  1. A bot token. You get it from @BotFather when you create the bot. Treat it like a password: anyone with it controls your bot. Our guide to creating a bot with BotFather shows where to find it.
  2. A public HTTPS URL on a server you control, which runs your bot's code. HTTP without TLS is not accepted.
  3. A supported port. The Bot API documentation lists ports 443, 80, 88 and 8443. If you use anything other than 443, write the port into the URL.
  4. A valid TLS certificate, either from a recognised certificate authority, or a self-signed certificate that you upload to Telegram when you set the webhook.
  5. A secret token you generate yourself, used to prove that requests really come from Telegram. More on this below.
  6. A decision about which update types you need. Receiving only what you use reduces load.

Step by step: setting a webhook

You call Bot API methods by making HTTPS requests to Telegram's Bot API address, with your token in the path and the method name at the end. Parameters can be passed as query parameters, as a form, or as JSON in the request body. Any HTTP tool works: your bot library, a command-line HTTP client, or an API testing app.

1. Make your endpoint answer

Before telling Telegram about the URL, make sure your server is listening on it and returns a success status (any 2xx response) to a POST request. Test it from outside your network, for example from your phone's mobile data, so you know the outside world can reach it.

2. Generate a secret token

Create a random string of letters, digits, underscores and hyphens. The Bot API documentation allows between 1 and 256 characters. Longer and random is better. Store it in your server's configuration, not in your source code.

3. Call setWebhook

Call the setWebhook method with these parameters:

  • url (required): your HTTPS endpoint. A common pattern is to include something unguessable in the path as well, though the secret token is the proper check.
  • secret_token: the string you generated. Telegram will send it back in a request header on every webhook call, named X-Telegram-Bot-Api-Secret-Token.
  • allowed_updates (optional): a list of the update types you want, such as messages and callback queries. If you leave it out, the previous setting is kept. The documentation notes that some update types, such as chat member updates and message reactions, are not sent unless you ask for them explicitly.
  • max_connections (optional): how many simultaneous HTTPS connections Telegram may open to your server, from 1 to 100, defaulting to 40. Lower it for a small server; raise it if your server handles many updates in parallel.
  • drop_pending_updates (optional): set to true to throw away updates that queued up while the bot had no delivery method. Useful when switching from polling, if you do not want a burst of old messages.
  • certificate (only for self-signed certificates): upload your public certificate file so Telegram can trust it.
  • ip_address (optional): a fixed IP for Telegram to use instead of resolving your domain name through DNS.

Telegram replies with a JSON object. A field named ok set to true means the webhook was accepted. If ok is false, the description field says why, for example a bad URL or an unreachable host.

SponsoredCrypto Trading28K members · TradingOpen in Telegram

4. Check the result with getWebhookInfo

Call getWebhookInfo with no parameters. It returns the current webhook state, including:

  • url: the address set. Empty means no webhook is set and the bot is in polling mode.
  • pending_update_count: how many updates are waiting to be delivered. If this keeps growing, deliveries are failing.
  • last_error_date and last_error_message: when the most recent delivery failed and why, in Telegram's words. This is the single most useful field when debugging.
  • max_connections, ip_address, allowed_updates and has_custom_certificate: confirmation of the settings you sent.

5. Send your bot a message

Open a chat with your bot and send a message. Your server should receive a POST within a moment. Check your server logs, then call getWebhookInfo again and confirm pending_update_count is zero and there is no fresh error.

Handling webhook requests correctly

Setting the webhook is the short part. How your endpoint behaves decides whether the bot is reliable.

Check the secret header first

On every request, compare the X-Telegram-Bot-Api-Secret-Token header with your stored secret. If it is missing or wrong, return an error and stop. Without this check, anyone who discovers your URL can send fake updates that look like real users pressing buttons or sending commands.

Answer quickly

Telegram waits for your response before considering the update delivered. If your bot does slow work, such as calling an AI model, querying a slow database or downloading files, do not make Telegram wait for it. Acknowledge the request with a success status straight away, then do the work in the background and send the result with a separate Bot API call.

If your endpoint is slow or returns an error, Telegram treats the delivery as failed and tries again later. Updates pile up behind it, and users see a bot that seems to lag.

Expect the same update twice

Because failed deliveries are retried, a request that timed out on Telegram's side may already have been processed on yours. Make your handler safe to run twice. The simplest way is to remember recent update IDs and skip any you have already handled. This matters most for actions with side effects, such as sending a payment confirmation or posting to a channel.

Choose your error responses deliberately

Telegram retries any delivery that does not get a success status. That is helpful for temporary problems and harmful for permanent ones. If an update can never be processed, for example because it is a type your bot does not handle or it refers to a chat the bot has left, answering with an error makes Telegram send it again and again until it gives up, wasting work on both sides and cluttering your error logs. For updates you have deliberately decided to ignore, return success and move on. Reserve error responses for real, temporary failures where a retry might work, and for requests that fail the secret check.

Replying inside the webhook response

The Bot API allows a shortcut: instead of an empty success response, your endpoint can answer with a Bot API method call in the response body, as JSON naming the method and its parameters. Telegram executes it. It saves one request per update, but you do not learn whether the call succeeded, so use it only for simple replies where failure does not matter.

Use only the updates you need

Every update type you subscribe to is traffic your server must accept and answer. If your bot only reacts to messages and button presses, set allowed_updates to those. You can change it with another setWebhook call at any time.

Self-signed certificates

If you cannot get a certificate from a recognised authority, for example on an internal test server, you can use a self-signed one:

  1. Create a certificate whose common name matches your server's domain name or IP address exactly.
  2. Configure your web server to use it.
  3. Call setWebhook with the url and upload the public certificate file in the certificate parameter.
  4. Check getWebhookInfo: has_custom_certificate should be true.

Telegram's documentation has a separate page on self-signed certificates. If you can use a free certificate from a recognised authority, do that instead; it removes one moving part.

Switching between webhook and polling

From webhook to polling

  1. Call deleteWebhook. Pass drop_pending_updates set to true if you want to discard updates that are queued.
  2. Confirm with getWebhookInfo that url is empty.
  3. Start your bot in polling mode.

From polling to webhook

  1. Stop the polling process first, so it does not keep calling getUpdates.
  2. Call setWebhook as above. Decide whether to drop pending updates.
  3. Check getWebhookInfo and send a test message.

Running a development bot and a production bot

A bot has one delivery method at a time. If you poll from your laptop while the production server expects a webhook, you will delete the production webhook and break the live bot. Create a separate bot with @BotFather for development, with its own token. It is free and avoids a whole category of accidents.

Long polling done right

If polling is the right choice for your bot, a few details make it as reliable as a webhook.

Use a long timeout, not a fast loop

The getUpdates method takes a timeout parameter in seconds. With a timeout of zero, Telegram answers immediately even when there is nothing new, so a bot calling it in a loop sends a constant stream of pointless requests. With a timeout of a few tens of seconds, the request stays open until an update arrives or the time runs out. That is the "long" in long polling, and it gives near-instant delivery with very little traffic.

Make sure your HTTP client's own timeout is longer than the one you pass to Telegram, or your client will give up before Telegram answers.

Acknowledge with the offset

Each call passes an offset equal to the highest update ID you have processed plus one. That tells Telegram everything before it has been handled and can be forgotten. Two consequences follow:

  • If your bot crashes before advancing the offset, the same updates are returned on the next call. That is good, because nothing is lost, but it means your handler should be safe to repeat, exactly as with webhooks.
  • If you advance the offset before processing, a crash loses those updates. Process first, then advance.

Run one poller per token

Only one getUpdates call can be active for a bot at a time. If two copies of your bot poll with the same token, for example an old process that was never stopped and a new one, Telegram answers one of them with a conflict error saying another getUpdates request terminated it. The two keep knocking each other off, and updates go to whichever happened to be connected. When you see that conflict error, find and stop the second process.

Limit and filter

getUpdates also accepts a limit on how many updates to return per call and an allowed_updates list, which works the same way as for webhooks. Filtering here reduces work for your bot just as it does for a server.

SponsoredPumpFun Trade Tokens27K members · CryptoOpen in Telegram

Monitoring a webhook in production

A webhook fails silently from the user's point of view: the bot just stops answering. A little monitoring catches it before users do.

  1. Check getWebhookInfo on a schedule. Every few minutes, a small job calls it and raises an alert if pending_update_count is above a level you consider normal, or if last_error_date is recent.
  2. Log every request your endpoint receives, with the update ID, the time and your response status, but not the message content. When something goes wrong, those three facts usually explain it.
  3. Set the webhook as part of each deployment, with the same parameters every time. Calling setWebhook with unchanged settings is harmless, and it guarantees that a deployment to a new address updates Telegram too.
  4. Watch your certificate's expiry date. An expired certificate stops all deliveries at once. Automated renewal plus an alert a few weeks before expiry removes this risk.
  5. Test after every infrastructure change. New firewall rules, a new load balancer or a moved domain are the usual times a working webhook stops working. Send the bot a message and check getWebhookInfo afterwards.

Hosting options and what changes

A normal server or virtual machine

You run a web server with a certificate, your bot code behind it, and a firewall that allows incoming HTTPS. This is the classic setup and gives you full control over timeouts and background work.

Serverless functions

Each update starts a function that handles it and stops. Webhooks are the only option here. Watch three things: function time limits (answer fast and hand slow work to a queue), cold starts (the first request after a quiet period is slower), and retries (the same update may arrive twice, so keep your handler safe to repeat).

No-code automation platforms

Many automation tools give you a webhook URL that you can register with setWebhook, so a workflow runs for each message. Our guide on automating Telegram with n8n, Zapier or Make shows that approach, and building a bot without coding covers the wider options.

Testing a webhook on your own computer

Your laptop has no public HTTPS address. Tunnelling tools can give a temporary public URL that forwards to your machine. Set that URL as the webhook of your development bot, never your production one, and remember that the URL usually changes each time the tunnel restarts, so you will need to call setWebhook again.

Troubleshooting: when updates do not arrive

Start every investigation with getWebhookInfo. The last_error_message usually names the cause. Then use the section that matches.

The certificate is not trusted

How to recognise it: the last error mentions SSL, a certificate, verification or a handshake.

  1. Check that the certificate covers the exact domain in your URL.
  2. Make sure your server sends the full certificate chain, including intermediate certificates, not only your own certificate.
  3. If self-signed, re-upload it with setWebhook and confirm the common name matches.
  4. Check that your server supports a modern TLS version.

If it still fails, test the URL with an online TLS checker and fix what it reports.

The connection is refused or times out

How to recognise it: the last error mentions a connection refused, timeout, or host unreachable.

  1. Confirm the port is one of 443, 80, 88 or 8443, and that it is written in the URL if it is not 443.
  2. Check your firewall and hosting provider's security rules allow incoming connections on that port.
  3. Check the server process is running and listening on that port.
  4. If you set ip_address, make sure it is the correct public address.

Telegram's webhook guide lists the network ranges Telegram's servers send from. If your firewall only allows specific sources, take the current ranges from that guide rather than an old blog post.

Your server answers with an error

How to recognise it: the last error includes an HTTP status code, such as a 4xx or 5xx error.

  1. Look at your server logs at the time shown in last_error_date.
  2. A 401 or 403 often means your own secret check is failing, for example because the secret in your configuration differs from the one you sent in setWebhook. Call setWebhook again with the correct value.
  3. A 404 means the path is wrong. Compare the URL in getWebhookInfo with your server's routes.
  4. A 5xx means your code crashed. Fix the error, then watch pending_update_count fall as queued updates are delivered.

Requests redirect

How to recognise it: your server answers with a redirect status, often because it sends HTTP traffic to HTTPS or adds a trailing slash.

Set the webhook to the final address exactly, including the trailing slash if your server expects one, so no redirect is needed.

The response is too slow

How to recognise it: errors mention a timeout, pending updates grow during busy periods, and users see delays.

  1. Acknowledge the request immediately and move heavy work to a background job.
  2. Lower max_connections if your server is overloaded, or raise it if the server has spare capacity and each request is slow.
  3. Check whether a database or external API is the bottleneck.

getUpdates says a webhook is active

How to recognise it: your polling bot reports a conflict error mentioning an active webhook.

Call deleteWebhook, check that getWebhookInfo shows an empty url, and start polling again. If it keeps coming back, another deployment of your bot is setting the webhook on startup. Find and stop it, or give that deployment its own bot token.

Updates arrive, but not the ones you expect

How to recognise it: messages arrive but button presses, member changes or reactions never do.

  1. Check allowed_updates in getWebhookInfo.
  2. Add the missing types with a new setWebhook call. Remember some types are only sent when requested explicitly.
  3. In groups, check the bot's privacy mode. By default a bot in a group only sees commands and messages addressed to it. You change this with @BotFather, or by making the bot an admin. See adding a bot to a channel or group.

Security checklist

  • Keep the token secret. If it leaks, revoke it with @BotFather and set the webhook again with the new token.
  • Always set and check a secret token on the webhook.
  • Do not log full updates forever. They contain users' messages and IDs. Keep logs short-lived and limited.
  • Validate input. Treat every field in an update as untrusted text, including names and captions.
  • Use separate bots for development and production.
  • Restrict what the server can do if it is compromised: give the bot only the database access it needs.

Our guide on whether Telegram bots are safe looks at the same questions from the user's side, which is a useful reminder of what you are protecting.

SponsoredOnly Finance80K members · FinanceOpen in Telegram

Example setups

These are illustrative examples.

A small community bot

A volunteer runs a bot that welcomes new members and answers a handful of commands. It runs on a cheap home computer behind a router. Long polling is the right choice: no certificate, no port forwarding, and the bot only makes outgoing connections.

A shop bot on a serverless platform

A shop bot runs as serverless functions. It sets a webhook with a secret token, subscribes only to messages, callback queries and payment-related updates, and acknowledges each request immediately while a queue handles order processing. It stores processed update IDs for a day to ignore repeats. Our guide to bot payments for developers covers the payment updates it handles.

A team moving from polling to webhooks

A team's polling bot outgrows a single process. They stop the poller, set a webhook pointing at a load balancer with several instances, drop pending updates during a short planned maintenance window, and watch getWebhookInfo for errors for the first hour.

Common mistakes

  • Leaving a development poller running that deletes the production webhook.
  • Skipping the secret token, leaving the endpoint open to fake updates.
  • Doing slow work before answering, which causes timeouts, retries and duplicate actions.
  • Not handling duplicate updates for actions with side effects.
  • Sending an incomplete certificate chain.
  • Using an unsupported port, or forgetting to write a non-standard port into the URL.
  • Expecting reactions or member updates without listing them in allowed_updates.
  • Committing the bot token to a public repository.

FAQ

Is a webhook faster than polling?

Not meaningfully for most bots. Long polling answers as soon as an update arrives. Choose based on where the bot runs and how it scales.

Can I use getUpdates and a webhook at the same time?

No. The two delivery methods are exclusive, so delete the webhook before you start polling.

What happens to updates while my server is down?

Telegram keeps them and keeps retrying, but not for longer than 24 hours according to the Bot API documentation. Check pending_update_count when you come back.

Do I need a domain name, or can I use an IP address?

You need an HTTPS URL that Telegram can reach with a valid certificate. With a self-signed certificate whose common name is your IP address, you can use an IP. A domain with a normal certificate is simpler.

Can one server host webhooks for several bots?

Yes. Give each bot its own path and its own secret token, and route requests by path.

How do I stop my bot receiving anything?

Call deleteWebhook and do not poll. Updates will queue for up to a day and then expire.

Summary

A webhook makes Telegram push each update to your HTTPS endpoint; polling makes your bot ask for them. Use polling for development and for bots that cannot accept incoming connections; use a webhook for public servers and serverless platforms. Set it with setWebhook, including a secret token and only the update types you need, confirm it with getWebhookInfo, answer requests quickly, and make your handler safe to run twice. When something breaks, the last error in getWebhookInfo almost always tells you which of the causes above you are dealing with.

AdHow the 30% discount works
Verified
Verified channels

Ownership confirmed through our claim process — not an endorsement of their content.

  1. Pavel DurovOwner verified
    @durov·News·10M members

    Founder of Telegram.

    ★ 5.0(2179)
  2. Telegram NewsOfficial channel
    @telegram·News·9.1M members

    The official Telegram on Telegram. Much recursion. Very Telegram. Wow.

    ★ 5.0(2879)
  3. Telegram PremiumOfficial channel
    @premium·News·6.3M members

    Telegram Premium – a subscription that unlocks dozens of exclusive features.

    ★ 4.6(1283)
  4. Binance AnnouncementsOfficial channel
    @binance_announcements·Crypto·3.2M members

    Binance Official English Group Binance Official Chinese Group Binance English Announcements Binance Chinese Announcements

    ★ 4.0(450)
Directory
The Crypto Channel Directory
List Your Channel, Group or Bot/MiniGame
  1. Crypto ResearchOfficial channel
    @cryptoresearch·Crypto·53K members

    is a modern crypto news and research platform covering the latest developments across digital assets, markets, regulation, and blockchain technology.

    ★ 4.5(553)
  2. Charts Signals TradingOfficial channel
    @ChartsSignalsTrading·Trading·105K members

    Technical analysis & high-probability trade setups. Price action, market structure, risk control.

    ★ 4.8(1865)
  3. Black Block MarketsOfficial channel
    @BlackBlockMarkets·Crypto·70K members

    BlackBlock Markets exists to observe how capital moves before it becomes obvious.

    ★ 4.4(1369)
  4. Only FinanceOfficial channel
    @OnlyFinance_Pro·Finance·80K members

    This channel focuses exclusively on what shapes global finance. Macroeconomics, markets, liquidity, central banks.

    ★ 4.1(1245)
  5. Bitunix Trading Signals
    @Bitunix_Trades·Trading·67K members

    Clear long & short signals for BTC, ETH & liquid altcoins. AI-backed analysis, real-time execution.

    ★ 4.4(220)
Explore the directory→
More from the blog
Privacy & SafetyHow to Recover Deleted Messages on TelegramPrivacy & SafetyHow to Recover Deleted Messages on TelegramWhat Telegram's delete options actually remove, which copies survive on your other devices, local caches and exports, and what is gone for good.12 Nov 2026Bots & Mini AppsHow to Use Telegram Bots to Send Automatic RepliesBots & Mini AppsHow to Use Telegram Bots to Send Automatic RepliesSet up Telegram automatic replies the right way: built-in Business greeting, away and quick replies, or a custom BotFather bot with menus, keyword answers and handoff.11 Nov 2026Getting StartedHow to Use Telegram Saved Messages as a Personal CloudGetting StartedHow to Use Telegram Saved Messages as a Personal CloudWhere Saved Messages sits on each Telegram app, how to save and organise notes and files there, and what it does not protect.10 Nov 2026Getting StartedHow to Search Messages in a Telegram Chat or ChannelGetting StartedHow to Search Messages in a Telegram Chat or ChannelFind a specific past message, link, photo or file inside a Telegram chat or channel on phone or desktop, using search filters, hashtags and date ranges.9 Nov 2026Getting StartedTelegram Web Preview of Channels ExplainedGetting StartedTelegram Web Preview of Channels ExplainedWhat a t.me/s link is, how to read a public Telegram channel in a browser without joining, and how to embed a single post.8 Nov 2026Getting StartedHow to Transfer Telegram Chats to a New PhoneGetting StartedHow to Transfer Telegram Chats to a New PhoneA step-by-step guide to moving Telegram to a new Android phone or iPhone: what returns from the cloud, what stays behind, and the order of steps before wiping the old device.7 Nov 2026
View all articles→
List Your Channel, Group or Bot/MiniGame

Discover

  • View all Telegram Channels
  • Categories
  • Best Telegram Channels
  • Crypto Channels 2026
  • Top Rated
  • Recently Added
  • Articles & Guides
TGDirectory

The most comprehensive Telegram channel directory. Discover the best channels, groups and bots in one place.

Contact: contact@telegramchannels.io

Explore
DirectoryCategoriesRankingsNew ChannelsInsightsTelegram Trading SignalsFree Crypto Signals Telegram ChannelsBitcoin Telegram ChannelsCrypto Exchange Telegram ChannelsCrypto News Telegram Channels
Company
AboutAdvertiseArticles & GuidesContact UsSubmit a ChannelDevelopers & APIFAQ
Legal
Privacy PolicyTerms of ServiceDisclaimer
© 2026 TGDirectory. All rights reserved.TGDirectory is an independent directory and is not affiliated with or endorsed by Telegram.
Report a problem→