Looking for developers for a 25-minute call: 500 RUB credit for your time.

Pick a time

Telegram bots: long polling or webhook

What it's for

You have a Telegram bot (aiogram, python-telegram-bot, grammY, Telegraf or any other library) and you want it running around the clock on DADA Cloud. A bot receives messages in one of two ways, and each way is a different kind of app on the platform. This guide helps you pick one, shows what to set up, and shows how to check that Telegram's messages reach the bot.

Pick a mode

Long pollingWebhook
How messages arriveThe bot asks Telegram for new messages (getUpdates)Telegram sends every message to an HTTPS address of your app
App on DADA CloudBackground worker: no HTTP, no public addressRegular app with a public HTTPS address
Port and domainNoneThe app listens on 0.0.0.0 and the port from the PORT variable. An address on dada-tuda.ru is issued automatically and shown in the console
What you setBOT_TOKENBOT_TOKEN, then WEBHOOK_URL with your app's address
FitsA start, small and medium load, nothing to maintain around the botHigher load, several replicas, a bot that shares a web server with other routes

Start with long polling. It needs no domain and the bot is one file. Move to a webhook when load or the architecture calls for it.

In the console the mode is chosen when you create the app: Create app, Telegram bot, then Long polling or Webhook. An uploaded archive depends on it: a polling bot is filed as a background worker with no port, a webhook bot is filed as a regular app and gets a port and an address (if the archive does not say which port it listens on, the console asks). With GitHub the platform decides from the code.

Use one mode at a time. While a webhook is set, Telegram answers getUpdates with a 409 Conflict error and a polling bot receives nothing. DADA Cloud never calls setWebhook or deleteWebhook for you: the webhook is yours.

Long polling

  1. Create the bot with @BotFather and copy its token.
  2. Python: upload the project as a zip or connect a GitHub repository. It needs a requirements.txt and the file that starts the bot (bot.py, main.py and the like). The platform recognizes a Python bot without a web framework, builds it without a Dockerfile and runs it as a background worker. Node.js: a package.json project is a web app by default. Turn on the background worker mode when you create the app, or add a Dockerfile that has no EXPOSE line.
  3. Set BOT_TOKEN in the app's environment variables.
  4. Make sure no webhook is set on the bot. python-telegram-bot and grammY delete it when polling starts, aiogram does not, so call delete_webhook yourself.
# aiogram 3
async def main() -> None:
    bot = Bot(token=os.environ["BOT_TOKEN"])
    await bot.delete_webhook()
    await dp.start_polling(bot)
# python-telegram-bot 22
Application.builder().token(os.environ["BOT_TOKEN"]).build().run_polling()
// grammY
const bot = new Bot(process.env.BOT_TOKEN);
await bot.start();

Webhook

  1. Create the bot and copy its token, as above.
  2. The app has to be a regular app with a port. A Python project without a web framework is detected as a worker, so add a Dockerfile that declares the port. The platform reads it from EXPOSE. A Node.js project is a regular app by default, so keep the background worker mode off:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8080
CMD ["python", "bot.py"]
  1. Set BOT_TOKEN and deploy. The bot has to listen on 0.0.0.0 and the port from the PORT variable (8080 by default).
  2. Open the app's page and copy its address, for example https://my-bot-ab12cd.dada-tuda.ru. The address has a random part, so it is only known after the app exists. Set the WEBHOOK_URL variable to it, without a trailing slash. The app restarts and registers the webhook at start.
  3. Check the result, see below.

The part of the code that matters:

# aiogram 3 (aiohttp)
async def on_startup(bot: Bot) -> None:
    await bot.set_webhook(f"{WEBHOOK_URL}/webhook", secret_token=SECRET)

dp.startup.register(on_startup)
app = web.Application()
SimpleRequestHandler(dispatcher=dp, bot=bot, secret_token=SECRET).register(app, path="/webhook")
setup_application(app, dp, bot=bot)
web.run_app(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8080")))
# python-telegram-bot 22 (install python-telegram-bot[webhooks])
application.run_webhook(
    listen="0.0.0.0", port=int(os.environ.get("PORT", "8080")),
    url_path="webhook", webhook_url=f"{WEBHOOK_URL}/webhook", secret_token=SECRET,
)
// grammY (node:http)
const handleUpdate = webhookCallback(bot, "http", { secretToken: SECRET });
createServer((req, res) => {
  if (req.method === "POST" && req.url === "/webhook") return handleUpdate(req, res);
  res.writeHead(200).end("ok");
}).listen(Number(process.env.PORT ?? 8080), "0.0.0.0", () =>
  bot.api.setWebhook(`${WEBHOOK_URL}/webhook`, { secret_token: SECRET }),
);

SECRET is the secret token Telegram sends in the X-Telegram-Bot-Api-Secret-Token header of every request. The bot refuses requests without it, so nobody else can feed it fake updates. It may be 1 to 256 characters: Latin letters, digits, _ and -.

Check that it works

Write the bot /start. If it answers, you are done.

On the app's page, the Your Telegram bot card shows what the platform learned by asking Telegram about the bot's token:

  • whether Telegram accepts the token, and the bot's name;
  • how the bot receives messages: long polling, or a webhook and the host it points to;
  • the number of messages waiting for delivery, and the last delivery error Telegram reported;
  • findings, with what to do about each.

The token is read on the server and is never shown. The webhook's host is shown, its path is not. The check only reads: it does not change the webhook.

The app's logs, further down the same page, show what the bot itself prints.

Typical problems

What you seeWhyWhat to do
409 Conflict in the logs of a polling botA webhook is set, or another process polls with the same token (an old copy of the bot, a run on a laptop)Delete the webhook (deleteWebhook) and stop the other process. The card names the webhook case. If the process exits on the 409 (grammY and Telegraf do), the app page names the reason itself, another instance or a webhook. aiogram and python-telegram-bot log the 409 and keep retrying, so the bot stays running and the 409 shows only in its logs
Unauthorized, InvalidToken, Token is invalidThe token was revoked or has a typoIssue a new one with /token in @BotFather and save it in BOT_TOKEN again
The card says the value has whitespace at its edgesThe token was pasted with a trailing space or line break. The check trims it, the app receives it as is, and aiogram rejects itSave the token again without the extra characters
The webhook bot is silent, the card says the webhook points to another hostWEBHOOK_URL is old, mistyped, or the address of another appFix WEBHOOK_URL. If the app has a domain of its own and the webhook uses it, this is fine
The webhook bot is silent, the card shows delivery errorsThe app does not answer Telegram: it does not listen on PORT or crashes on the requestRead the error in the card and the app's logs. 502 or connection refused usually means the port
The card says the bot has a webhook but the app is a workerThe webhook was left from an earlier setupCall deleteWebhook, or run the bot as a regular app
The app does not start and asks for WEBHOOK_URLThe address was not known yetSet it as in step 4 of the webhook section
The card says Telegram could not be reachedA network problem during the check. It does not mean the token is wrongCheck again in a moment

Keep the token safe

Set the token only in the environment variables, never in the repository. A variable whose name contains TOKEN, SECRET, PASSWORD, API_KEY, PRIVATE_KEY, API_HASH or SESSION_STRING is always stored as a secret: the variable list in the console and the API does not return its value. Only people who can edit the app can reveal it on request. Bot tokens that a library prints into its own logs are masked in the logs the console shows, in the app's alert emails and for the AI agent.