Telegram Bot API

How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting

· 9 min read

To deploy a Telegram bot, run its code on a machine that is always on and can reach api.telegram.org, then choose how it receives updates: long polling with getUpdates, which works on any server without a domain, or a webhook, which needs a public HTTPS URL. A small VPS with systemd or a Docker container is the usual choice for polling bots; serverless platforms such as Cloudflare Workers fit webhook bots. This guide shows each option with copy-paste configs, plus logging, restarts and a launch checklist.

Polling or webhook on a server

Telegram offers two mutually exclusive ways to get updates, and Telegram keeps undelivered updates for at most 24 hours either way. The choice decides what your Telegram bot hosting needs:

Long polling (getUpdates)Webhook (setWebhook)
NetworkOutgoing HTTPS only; works behind NATPublic HTTPS URL, ports 443, 80, 88 or 8443, IPv4
ProcessLong-running loopHTTP handler; can be serverless
InstancesExactly one per tokenSeveral behind one URL is fine
Good hostsVPS, Docker, home serverVPS with a reverse proxy, Cloudflare Workers, AWS Lambda, Vercel

If polling already works on your machine, keep it: Telegram's own webhook guide says there is nothing wrong with using getUpdates. Move to a webhook when your platform requires it or when you want several instances to share the load.

A deployable polling bot

Production-ready code has three properties: it reads the token from an environment variable, logs to stdout, and survives network errors instead of crashing. This echo bot does all three and calls deleteWebhook at startup, because getUpdates doesn't work while a webhook is set:

import logging
import os
import time

import requests

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("bot")

TOKEN = os.environ["BOT_TOKEN"]  # never hardcode the token
API = f"https://api.telegram.org/bot{TOKEN}"


def call(method, **params):
    data = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if not data["ok"]:
        raise RuntimeError(f"{method}: {data['error_code']} {data['description']}")
    return data["result"]


def main():
    call("deleteWebhook")  # polling and a webhook are mutually exclusive
    log.info("started as @%s", call("getMe")["username"])
    offset = 0
    while True:
        try:
            updates = call("getUpdates", offset=offset, timeout=30)
        except Exception:
            log.exception("getUpdates failed, retrying in 5 s")
            time.sleep(5)
            continue
        for update in updates:
            offset = update["update_id"] + 1
            msg = update.get("message")
            if msg and "text" in msg:
                try:
                    call("sendMessage", chat_id=msg["chat"]["id"], text="Echo: " + msg["text"])
                except Exception:
                    log.exception("update %s failed", update["update_id"])


if __name__ == "__main__":
    main()
const TOKEN = process.env.BOT_TOKEN; // never hardcode the token
if (!TOKEN) throw new Error("BOT_TOKEN is not set");
const API = `https://api.telegram.org/bot${TOKEN}`;
const log = (...args) => console.log(new Date().toISOString(), ...args);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const data = await res.json();
  if (!data.ok) throw new Error(`${method}: ${data.error_code} ${data.description}`);
  return data.result;
}

await call("deleteWebhook"); // polling and a webhook are mutually exclusive
log("started as @" + (await call("getMe")).username);

let offset = 0;
while (true) {
  let updates;
  try {
    updates = await call("getUpdates", { offset, timeout: 30 });
  } catch (err) {
    log("getUpdates failed, retrying in 5 s:", err.message);
    await sleep(5000);
    continue;
  }
  for (const update of updates) {
    offset = update.update_id + 1;
    const msg = update.message;
    if (!msg?.text) continue;
    try {
      await call("sendMessage", { chat_id: msg.chat.id, text: "Echo: " + msg.text });
    } catch (err) {
      log(`update ${update.update_id} failed:`, err.message);
    }
  }
}

Save them as bot.py (with requests in requirements.txt) or bot.mjs (Node.js 18+, no dependencies). Frameworks from the libraries list handle the loop for you, but the deployment steps below stay the same.

Telegram bot on a VPS with systemd

A VPS gives you a normal Linux machine. Let systemd start the bot at boot and restart it when it crashes:

  1. Create a user without login rights and copy the code to /opt/mybot; for Python, create a virtual environment there and install the requirements.
  2. Put the token in /etc/mybot.env as a line BOT_TOKEN=123456789:AAEexampleTokenReplaceWithYours and restrict access with chmod 600.
  3. Create the unit file /etc/systemd/system/mybot.service:
[Unit]
Description=Telegram bot
After=network-online.target
Wants=network-online.target

[Service]
User=mybot
WorkingDirectory=/opt/mybot
EnvironmentFile=/etc/mybot.env
ExecStart=/opt/mybot/.venv/bin/python -u bot.py
# Node.js: ExecStart=/usr/bin/node bot.mjs
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable it and follow the logs:

sudo systemctl daemon-reload
sudo systemctl enable --now mybot
journalctl -u mybot -f        # live logs
sudo systemctl restart mybot  # after updating the code

For a webhook on the same VPS, run the bot as an HTTP server on a local port and put nginx or Caddy in front of it to terminate TLS on port 443; the webhook guide has a handler with the secret token check.

Deploy a Telegram bot with Docker

A container packs the runtime and dependencies, so the bot runs the same on your laptop and on any Docker host. A Dockerfile for the Python bot:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY bot.py .
CMD ["python", "-u", "bot.py"]
# Node.js: FROM node:22-slim, COPY bot.mjs ., CMD ["node", "bot.mjs"]

Build and run it with the token passed at runtime, never baked into the image:

docker build -t mybot .
docker run -d --name mybot --restart unless-stopped --env-file .env mybot
docker logs -f mybot

--restart unless-stopped brings the bot back after crashes and host reboots. Keep .env out of Git and out of the image (add it to .dockerignore). When you redeploy a polling bot, stop the old container before starting the new one: two containers polling with the same token make getUpdates fail with 409 Conflict.

Serverless: Telegram bot on Cloudflare Workers

Serverless platforms run code only when a request arrives, so they need webhook mode. On Cloudflare Workers the default workers.dev address already serves HTTPS on port 443. This Worker checks the secret token header, answers immediately and finishes the work in the background with ctx.waitUntil:

// worker.js: deploy with "npx wrangler deploy"
export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);
    if (request.method !== "POST" || url.pathname !== "/telegram/webhook") {
      return new Response("Not found", { status: 404 });
    }
    const enc = new TextEncoder();
    const received = enc.encode(request.headers.get("X-Telegram-Bot-Api-Secret-Token") ?? "");
    const expected = enc.encode(env.WEBHOOK_SECRET);
    if (received.byteLength !== expected.byteLength ||
        !crypto.subtle.timingSafeEqual(received, expected)) {
      return new Response("Forbidden", { status: 403 });
    }
    const update = await request.json();
    ctx.waitUntil(handleUpdate(update, env)); // reply 200 now, keep working
    return new Response("OK");
  },
};

async function handleUpdate(update, env) {
  const msg = update.message;
  if (!msg?.text) return;
  const res = await fetch(`https://api.telegram.org/bot${env.BOT_TOKEN}/sendMessage`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ chat_id: msg.chat.id, text: "Echo: " + msg.text }),
  });
  if (!res.ok) console.error("sendMessage failed", res.status, await res.text());
}

Store both values as Worker secrets, deploy, then register the Worker URL with the same secret:

npx wrangler secret put BOT_TOKEN
npx wrangler secret put WEBHOOK_SECRET
npx wrangler deploy

curl -X POST "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://mybot.example.workers.dev/telegram/webhook", "secret_token": "replace-with-your-random-secret"}'

Or fill in setWebhook in the Bot API Tester. The same pattern works on AWS Lambda (behind an HTTPS function URL or API gateway) and on Vercel functions: parse the JSON body, verify the header, return 2XX quickly. Platforms limit how long a function and its background work may run, so move slow jobs to a queue. Telegram retries every non-2XX response, so a function that times out or crashes receives the same update again.

Free and low-cost ways to host a Telegram bot

Webhook requirements for any host

After every deploy, open getWebhookInfo in the Bot API Tester: a growing pending_update_count or a fresh last_error_message means Telegram can't deliver updates.

Environment variables, logging and restarts

Deployment checklist

  1. Token comes from an environment variable or secret; getMe succeeds on the server.
  2. Exactly one polling instance per token, or a webhook with secret_token, never both.
  3. The process restarts automatically after crashes and reboots.
  4. Logs are collected and contain no tokens.
  5. Errors in one update are logged, not fatal; webhook handlers return 2XX quickly.
  6. For webhooks, getWebhookInfo shows the right URL and no recent error.
  7. A separate test bot or the Telegram test server is used for experiments, not the production token.

Troubleshooting deployment problems

SymptomCause and fix
409 Conflict: terminated by other getUpdates requestTwo instances poll with one token (old container, your laptop). Stop all but one.
409 Conflict mentioning an active webhookA webhook is still set. Call deleteWebhook before polling.
401 UnauthorizedThe token variable is empty, mistyped or revoked. Check it with getMe.
Works locally, silent on the serverOutgoing HTTPS to api.telegram.org is blocked, or the environment file isn't loaded. Check the logs.
Webhook bot receives nothingSee last_error_message in getWebhookInfo: TLS, wrong port, 403 from a secret mismatch or a crashing handler.

New to bots? Start with how to create a Telegram bot, then come back to deploy it.

Frequently asked questions

Where can I host a Telegram bot?

Anywhere that can make outgoing HTTPS requests: a VPS, a Docker host, a home server or a serverless platform. A bot that uses getUpdates needs no public address; a webhook bot needs a public HTTPS URL on port 443, 80, 88 or 8443.

Should a deployed bot use polling or a webhook?

Both work in production. Long polling with getUpdates is simplest on a VPS or in Docker because no domain or certificate is needed. Webhooks are required on serverless platforms, which only run code when a request arrives.

Why do I get 409 Conflict after deploying my bot?

Either a webhook is still set while the bot polls with getUpdates (call deleteWebhook), or two copies of the bot poll at the same time, for example the old and the new container during a deploy, or your laptop and the server. Run exactly one polling instance per token.

How do I keep a Telegram bot running 24/7?

Run it under a process supervisor that restarts it after crashes and reboots: a systemd service with Restart=always on a VPS, or a Docker container with --restart unless-stopped. Log to stdout and watch the logs with journalctl or docker logs.

Can I run a Telegram bot on Cloudflare Workers?

Yes, in webhook mode. The Worker receives each update as a POST request, checks the X-Telegram-Bot-Api-Secret-Token header and calls the Bot API with fetch. Register its workers.dev HTTPS address with setWebhook. A long polling loop does not fit this model.

Where should I store the bot token on a server?

In an environment variable loaded from a file readable only by the bot user, or in the platform's secret store (for example a Worker secret). Never commit the token to Git or bake it into a Docker image. If it leaks, revoke it in @BotFather.

How to Create a Telegram Bot: Step by Step with BotFather and Python

How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.

Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More

What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.

Telegram Bot API Errors: What Each Error Means and How to Fix It

Telegram Bot API errors explained: 400 chat not found, 403 bot was blocked by the user, 409 Conflict, 429 retry_after. Causes, fixes and handling code.

Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length

Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.

Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links

Set up Telegram bot commands: @BotFather /setcommands, setMyCommands with scopes and languages, /start deep link parameters and /cmd@bot in groups.

Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard

Add Telegram bot buttons: inline keyboard with callback_data, answerCallbackQuery, editing the message after a press, reply keyboard and ForceReply.

n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages

Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.

How to Send a Message with the Telegram Bot API (sendMessage)

Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.

Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe

Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.

How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting

Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.

How to Get a Telegram Chat ID for a User, Group, Channel or Topic

How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.

Telegram Inline Bot: How to Enable Inline Mode and Answer Inline Queries

Build a Telegram inline bot: enable inline mode with @BotFather or setMySettings, handle inline_query updates and reply with answerInlineQuery.

Telegram Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions

Accept Telegram Stars payments in your bot: sendInvoice with XTR, pre_checkout_query, successful_payment, refunds, subscriptions, Python/JS code.

Telegram Test Server: How to Test a Bot in the Telegram Test Environment

Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.

Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button

Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.

TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits

TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.

Telegram Widget Examples: Complete HTML and Python Bot Code

Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.

Telegram Widgets: Interactive HTML Inside Bot Messages

Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.

How to Test a Telegram Mini App: From Browser Mock to Real Telegram

Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.