Most Telegram bot tutorials stop at run_polling() on a laptop. That works until you close the laptop. This guide takes a Python bot to a VPS and runs it the way production bots usually run: webhooks behind Nginx with HTTPS, started and restarted by systemd, with a secret token so only Telegram can call it.
You need:
- A Linux VPS (the commands use Ubuntu 24.04)
- A domain or subdomain pointing at the server (an
Arecord such asbot.example.com) - A bot token from @BotFather
Polling or webhook?
| Polling | Webhook | |
|---|---|---|
| How it works | Your bot keeps asking Telegram for updates | Telegram sends each update to your HTTPS URL |
| Needs a public HTTPS endpoint | No | Yes |
| Idle cost | Constant requests | None until a message arrives |
| Good for | Development, small bots | Production, many users |
Telegram only delivers webhooks to ports 443, 80, 88 or 8443, and only over HTTPS. Nginx on 443 in front of the bot takes care of both.
Hosting from Iran? Telegram is filtered in Iran, so a bot on an Iranian server has no direct route to
api.telegram.org. Most bots for Iranian users run on a server abroad (Germany is a common choice) and serve the same users without problems.
Step 1: A user and a virtual environment for the bot
sudo apt update && sudo apt install -y python3-venv nginx
sudo adduser --system --group --home /opt/mybot mybot
sudo -u mybot python3 -m venv /opt/mybot/venv
sudo -u mybot /opt/mybot/venv/bin/pip install "python-telegram-bot[webhooks]>=21,<22"
The [webhooks] extra installs the small web server that python-telegram-bot uses to receive updates. The bot runs as its own system user, so a bug in the bot cannot touch the rest of the server.
Step 2: The bot
/opt/mybot/bot.py:
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
logging.basicConfig(level=logging.INFO)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Hi! I'm running on a webhook.")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text(update.message.text)
def main() -> None:
app = Application.builder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_webhook(
listen="127.0.0.1", # only Nginx can reach it
port=8000,
url_path="telegram",
webhook_url=f"https://{os.environ['BOT_DOMAIN']}/telegram",
secret_token=os.environ["WEBHOOK_SECRET"],
drop_pending_updates=True,
)
if __name__ == "__main__":
main()
run_webhook registers the webhook with Telegram on start-up (setWebhook) and serves it. With secret_token set, Telegram sends the value in the X-Telegram-Bot-Api-Secret-Token header, and the library rejects any request where it is missing or wrong.
Step 3: Keep the secrets out of the code
sudo tee /etc/mybot.env > /dev/null <<'EOF'
BOT_TOKEN=123456:ABC-your-token
BOT_DOMAIN=bot.example.com
WEBHOOK_SECRET=change-me-to-a-long-random-string
EOF
sudo chown root:mybot /etc/mybot.env
sudo chmod 640 /etc/mybot.env
Generate the secret with openssl rand -hex 32. Telegram allows only the characters A-Z, a-z, 0-9, _ and -, up to 256 of them, and hex output fits.
Step 4: A systemd service
/etc/systemd/system/mybot.service:
[Unit]
Description=Telegram bot (webhook)
After=network-online.target
Wants=network-online.target
[Service]
User=mybot
Group=mybot
WorkingDirectory=/opt/mybot
EnvironmentFile=/etc/mybot.env
ExecStart=/opt/mybot/venv/bin/python /opt/mybot/bot.py
Restart=always
RestartSec=5
# basic sandboxing
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Don't start it yet. Telegram will refuse the webhook until HTTPS works.
Step 5: Nginx and a free certificate
/etc/nginx/sites-available/mybot:
server {
listen 80;
server_name bot.example.com;
location /telegram {
proxy_pass http://127.0.0.1:8000/telegram;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
return 404;
}
}
sudo ln -s /etc/nginx/sites-available/mybot /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d bot.example.com
Certbot adds the listen 443 ssl block, an HTTP-to-HTTPS redirect, and a timer that renews the certificate automatically.
Step 6: Start it and check what Telegram sees
sudo systemctl daemon-reload
sudo systemctl enable --now mybot
sudo journalctl -u mybot -f
Then ask Telegram what it thinks of your webhook:
curl -s "https://api.telegram.org/bot<YOUR_TOKEN>/getWebhookInfo"
A healthy result shows your URL, "pending_update_count": 0, and no last_error_message. Send /start to the bot and you should get a reply within a second.
When it doesn't work
| What you see | Likely cause | Fix |
|---|---|---|
last_error_message: "Wrong response from the webhook: 502 Bad Gateway" |
Bot not running, or a different port |
systemctl status mybot, check port= matches proxy_pass
|
| "Wrong response from the webhook: 404 Not Found" | Path mismatch |
url_path, webhook_url and the Nginx location must all say /telegram
|
| "Wrong response from the webhook: 403 Forbidden" | Secret token mismatch | Restart the bot so it registers the webhook again with the current secret |
| "SSL error" or certificate errors | No valid certificate for the domain | Re-run certbot --nginx -d ..., check DNS points to this server |
pending_update_count keeps growing |
Telegram can't reach you at all | Firewall: sudo ufw allow 'Nginx Full'
|
| Bot works, then stops after a reboot | Service not enabled | systemctl enable mybot |
Before you call it production
-
Logs:
journalctl -u mybotalready keeps them. AddSystemMaxUse=injournald.confif the bot is chatty. - State: anything you keep in Python variables is gone on restart. Use SQLite or Redis for user data.
-
Updates: pin the major version (
>=21,<22) and read the changelog before you move to the next one. -
Several bots on one server: give each one its own user, port,
url_pathand service file. One Nginx server block can route several paths.
If you'd rather not run the VPS yourself, managed Telegram bot hosting and Python hosting take care of the server side, and a VPS in Germany is a good fit when your users are in Iran (pages are in Persian).
References: python-telegram-bot: Webhooks, Telegram Bot API: setWebhook
Parsa Shahmohammadi works on Pikohost, a hosting provider for Persian-speaking developers and businesses.
Top comments (0)