Polling or webhook¶
A Telegram bot receives updates (messages, button presses) in one of two ways. Use one, not both: Telegram refuses long polling while a webhook is set.
Use a webhook on BotBarn. Long polling works too, as the alternative.
| Webhook (recommended) | Long polling | |
|---|---|---|
| How | Telegram sends each update to the bot over HTTPS. | The bot keeps asking Telegram for new updates. |
| Speed | Updates arrive at once. | Updates arrive when the current request returns. |
| Traffic | Only when there is an update. | A request open to Telegram all the time. |
| Setup on BotBarn | None: BotBarn registers the webhook for you. | None. |
Why webhooks: many bots share BotBarn's servers and their internet address. Webhooks keep the traffic from that address to Telegram low, so no bot is slowed down by limits Telegram applies to the shared address.
Update mode¶
Every bot has an update mode, shown and changed on the Telegram updates card of the bot's
Overview (an AI assistant changes it with set_update_mode):
| Mode | What BotBarn does | What your code does |
|---|---|---|
| Webhook (default for bots your AI assistant creates) | Calls setWebhook each time the bot starts, deleteWebhook when it stops. |
Serves HTTP on PORT. No setWebhook, no getUpdates. |
| Polling (default for bots created in the web app) | Calls deleteWebhook once, when you switch to polling. Nothing else. |
Gets updates itself: long polling, or its own setWebhook. |
Bots created before webhook mode existed are in Polling mode, so code that calls setWebhook
itself keeps working unchanged.
Polling code in webhook mode
A bot in webhook mode whose code polls logs Conflict: can't use getUpdates method while webhook is active. Serve the webhook as below, or switch the bot to Polling.
Webhook¶
BotBarn gives your bot these variables:
| Variable | Value |
|---|---|
PORT |
8080: listen on 0.0.0.0:$PORT. |
BOTBARN_WEBHOOK_URL |
Your bot's public HTTPS URL, for example https://app.botbarn.dev/bots/<node>/<bot id>/. <node> names the machine that runs the bot and can change when the bot moves: read the URL from the variable, do not build it. |
BOTBARN_WEBHOOK_SECRET |
A random secret. Telegram sends it back in every request. |
BOTBARN_WEBHOOK_MANAGED |
1 in webhook mode (BotBarn registers the webhook), 0 in polling mode. |
The Telegram updates card shows the URL. Without PORT and the URL, webhooks are disabled on the
platform: use long polling.
In webhook mode BotBarn registers the webhook (setWebhook with the URL and the secret, pending
updates kept) as soon as the bot reports running after a deploy or a start, and removes it
(deleteWebhook) when you stop the bot, change its Telegram token or delete it. The card shows when
the webhook was set, or Telegram's last error. If Telegram cannot be reached BotBarn retries, first
after a few seconds, then every few minutes up to once an hour while the bot runs. A token Telegram
rejects is not retried: fix the token and deploy again.
Your code does three things:
- Listen for HTTP
POSTrequests on0.0.0.0:$PORT, path/: BotBarn forwardsBOTBARN_WEBHOOK_URL+<path>to/<path>in your container. - Refuse (
403) any request whoseX-Telegram-Bot-Api-Secret-Tokenheader is not the secret. - Hand the update to your library and answer
200.
Check BOTBARN_WEBHOOK_MANAGED at startup so the same code works in both modes:
import asyncio
import hmac
import os
from aiohttp import web # aiohttp==3.12.15 in requirements.txt
from telegram import Update
async def serve_webhook(app):
secret = os.environ["BOTBARN_WEBHOOK_SECRET"]
async def handle(request):
header = request.headers.get("X-Telegram-Bot-Api-Secret-Token", "")
if not hmac.compare_digest(header, secret):
return web.Response(status=403)
await app.update_queue.put(Update.de_json(await request.json(), app.bot))
return web.Response()
server = web.Application()
server.router.add_post("/", handle)
runner = web.AppRunner(server)
async with app:
await app.start()
await runner.setup()
await web.TCPSite(runner, "0.0.0.0", int(os.environ["PORT"])).start()
await asyncio.Event().wait()
if os.environ.get("BOTBARN_WEBHOOK_MANAGED") == "1":
asyncio.run(serve_webhook(app))
else:
app.run_polling(timeout=30, drop_pending_updates=True)
Do not use run_webhook in webhook mode: it calls setWebhook again on its own, which BotBarn
has already done.
import http from 'node:http'
import { webhookCallback } from 'grammy'
if (process.env.BOTBARN_WEBHOOK_MANAGED === '1') {
http
.createServer(webhookCallback(bot, 'http', { secretToken: process.env.BOTBARN_WEBHOOK_SECRET }))
.listen(Number(process.env.PORT), '0.0.0.0')
} else {
await bot.start({ timeout: 30, drop_pending_updates: true })
}
webhookCallback with secretToken refuses requests without the right secret.
The python-webhook example does all of this, and falls back to polling in polling mode.
Managing the webhook yourself¶
In Polling mode your code may still use the webhook variables and call setWebhook with
url = BOTBARN_WEBHOOK_URL and secret_token = BOTBARN_WEBHOOK_SECRET at startup, as bots did before
webhook mode existed. BotBarn routes the requests the same way; it just does not call Telegram.
Rules of the webhook route¶
- Only
POSTrequests reach your bot. - Requests without the right secret are refused by BotBarn before they reach the bot.
- Requests are limited to 1 MB. Your bot must answer within 10 seconds; answer quickly and do long work after answering.
- BotBarn routes requests only while the bot is running.
Rotating the secret¶
Rotate secret on the Telegram updates card creates a new secret. The bot receives it on the next
deploy, or after a stop and start (a restart keeps the old one). In webhook mode BotBarn registers the
new secret with Telegram at that start; in polling mode your code must call setWebhook again with
it. Until then Telegram may be refused.
Changing the Telegram token¶
In webhook mode, saving a new token removes the webhook of the old one at once. The running bot keeps the old token until you deploy again (or stop and start); BotBarn then registers the webhook with the new token.
Long polling¶
If you use polling, use long polling and handle errors politely:
- Long timeout. Each
getUpdatesrequest waits up to 30 to 50 seconds for updates. Never poll in a tight loop with a short or zero timeout. - Back off on errors. After a network error or a
5xxanswer, wait before retrying, and wait longer each time. - Respect
429 Too Many Requests. Wait theretry_afterseconds Telegram sends before the next request. This applies to sending messages too. - One poller per token. Stop any copy running on your computer: Telegram answers Conflict: terminated by other getUpdates request.
The libraries below back off on errors. Set the timeout as shown:
The default timeout is 10 seconds: set it to 30. Retries after errors wait longer each time, and
a RetryAfter error waits the time Telegram asks for.
The default polling_timeout is 10 seconds: set it to 30. backoff_config controls the wait
after errors.
The default timeout is already 30 seconds. On 429 grammY waits retry_after before polling
again.
Polling fails while a webhook is set. Keep the bot in Polling mode: BotBarn then never sets one.
python-telegram-bot, grammY and Telegraf also delete a leftover webhook when they start polling; with
aiogram call delete_webhook first, as above.
Sending many messages¶
Telegram limits how fast a bot sends messages: about one message per second in a chat, 20 per minute
in a group, and 30 per second overall. Use your library's rate limiter (python-telegram-bot
AIORateLimiter, the grammY auto-retry plugin) instead of sending in a tight loop.