On this page
- Polling or webhook: which should you choose?
- How do you create the bot and protect its token?
- How do you install the libraries?
- What does a polling bot look like with python-telegram-bot?
- What does the same bot look like in aiogram?
- How do you run the bot with systemd?
- How do you switch to a webhook behind Nginx?
- How do you maintain and debug the bot?
- Questions
Polling or webhook: which should you choose?
Start with long polling unless you have a reason not to. In polling mode the bot repeatedly asks the Bot API for new updates over an outgoing HTTPS connection, so it needs no domain, no certificate and no open port. A webhook reverses the direction: Telegram sends each update as an HTTPS POST to a public URL. That saves the idle requests and delivers updates a little faster, and it fits naturally when the bot already lives inside a web app, but it needs a domain, a valid certificate and a reverse proxy. Both modes give the same features. A bot can use only one at a time: while a webhook is set, polling calls fail.
How do you create the bot and protect its token?
Open a chat with @BotFather in Telegram, send /newbot, choose a display name and a username ending in bot, and copy the token it returns. Store it in a root owned env file readable by the bot group:
sudo useradd --system --create-home --home-dir /opt/tgbot --shell /usr/sbin/nologin tgbot
sudo install -m 640 -o root -g tgbot /dev/null /etc/tgbot.env
sudo nano /etc/tgbot.envTELEGRAM_TOKEN=123456789:replace-with-your-token
TG_WEBHOOK_SECRET=long-random-letters-and-digitsThe second value is only used in webhook mode. If the token leaks, send /revoke to BotFather to issue a new one. Reading values from the environment is explained in the environment variables guide.
How do you install the libraries?
Pick one framework. python-telegram-bot is mature with extensive docs; aiogram is fully asynchronous with a router and middleware design. Both need a recent Python 3, which the Python and pip guide helps with.
# Ubuntu and Debian
sudo apt update
sudo apt install -y python3-venv
# Rocky Linux 9 and AlmaLinux 9
sudo dnf install -y python3.12
sudo -u tgbot python3 -m venv /opt/tgbot/.venv # Rocky and Alma: python3.12
sudo -u tgbot /opt/tgbot/.venv/bin/pip install --upgrade pip
# option A: python-telegram-bot (add the webhooks extra for webhook mode)
sudo -u tgbot /opt/tgbot/.venv/bin/pip install "python-telegram-bot[webhooks]"
# option B: aiogram
sudo -u tgbot /opt/tgbot/.venv/bin/pip install aiogram
sudo -u tgbot /opt/tgbot/.venv/bin/pip list | grep -Ei "telegram|aiogram"What does a polling bot look like with python-telegram-bot?
This script answers /start and echoes text messages. Save it as /opt/tgbot/bot.py owned by tgbot.
import logging
import os
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
logging.basicConfig(level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hi, the bot is online.")
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(update.message.text)
def main():
app = Application.builder().token(os.environ["TELEGRAM_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
app.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main()Quieting the httpx logger stops every poll request from filling the journal, which also keeps the token out of the logs.
What does the same bot look like in aiogram?
aiogram 3 uses a dispatcher with decorated handlers and an asyncio entry point.
import asyncio
import logging
import os
from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import Message
dp = Dispatcher()
@dp.message(CommandStart())
async def start(message: Message):
await message.answer("Hi, the bot is online.")
@dp.message(F.text)
async def echo(message: Message):
await message.answer(message.text)
async def main():
bot = Bot(os.environ["TELEGRAM_TOKEN"])
await dp.start_polling(bot)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
asyncio.run(main())The systemd unit in the next section works unchanged for either script.
How do you run the bot with systemd?
Create /etc/systemd/system/tgbot.service so the bot starts at boot and comes back after a crash.
[Unit]
Description=Telegram bot
After=network-online.target
Wants=network-online.target
[Service]
User=tgbot
Group=tgbot
WorkingDirectory=/opt/tgbot
EnvironmentFile=/etc/tgbot.env
ExecStart=/opt/tgbot/.venv/bin/python bot.py
Restart=always
RestartSec=5
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/opt/tgbot
[Install]
WantedBy=multi-user.targetsudo systemctl daemon-reload
sudo systemctl enable --now tgbot
journalctl -u tgbot -fSend /start to your bot in Telegram; the reply proves the whole path works. Run only one copy: a second polling process makes the API answer with a Conflict error.
How do you switch to a webhook behind Nginx?
Let the bot listen on localhost and have Nginx pass the public HTTPS path to it. With python-telegram-bot, replace run_polling with:
app.run_webhook(
listen="127.0.0.1",
port=8081,
url_path="tg",
secret_token=os.environ["TG_WEBHOOK_SECRET"],
webhook_url="https://bot.example.net/tg",
allowed_updates=Update.ALL_TYPES,
)The library registers the webhook with Telegram at start and rejects requests that lack the matching X-Telegram-Bot-Api-Secret-Token header. aiogram offers the same through SimpleRequestHandler on an aiohttp app. Then add the proxy:
server {
listen 80;
listen [::]:80;
server_name bot.example.net;
location /tg {
proxy_pass http://127.0.0.1:8081;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location / {
return 404;
}
}sudo nginx -t && sudo systemctl reload nginx
sudo setsebool -P httpd_can_network_connect 1 # Rocky and Alma only
sudo certbot --nginx -d bot.example.net --redirect
sudo systemctl restart tgbot
curl -s "https://api.telegram.org/bot<token>/getWebhookInfo"Telegram accepts webhooks only on ports 443, 80, 88 and 8443 with a valid certificate; Nginx on 443 covers that. In getWebhookInfo look for your URL and an empty last_error_message. Open 80 and 443 with sudo ufw allow 80/tcp and sudo ufw allow 443/tcp, or the http and https services in firewalld. In polling mode no inbound rule is needed at all.
How do you maintain and debug the bot?
- Bot silent after switching back to polling: remove the webhook first with
deleteWebhook, or let the library do it (run_pollingdoes by default). - Unauthorized: the token was revoked or mistyped in
/etc/tgbot.env. - Webhook shows SSL errors: the certificate does not match the hostname; rerun Certbot.
- Webhook returns 403: the secret token in the env file and in Telegram differ; restart the bot so it registers again.
- Updates from groups missing: privacy mode is on; disable it with
/setprivacyin BotFather if the bot must read all messages.
Update with pip install -U inside the venv and sudo systemctl restart tgbot, after reading the library changelog. Trading and alert bots often run here next to their exchange logic; the trading bots page shows suitable setups.
Plans that fit this guide
Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.
| Plan | Fits because | Size | Monthly | Order from |
|---|---|---|---|---|
| A1-1 | one polling bot | 1 vCPU, 1 GB RAM, 25 GB NVMe | $3.60/mo | $43.20 for 12 months |
| A1-2 | webhook bot with Nginx and a database | 1 vCPU, 2 GB RAM, 50 GB NVMe | $7.20/mo | $43.20 for 6 months |
| A2-4 | several bots or heavy scheduled jobs | 2 vCPU, 4 GB RAM, 100 GB NVMe | $14.40/mo | $43.20 for 3 months |
Questions about Host a Python Telegram bot
Does a polling bot need any open ports?
No. All traffic is outgoing HTTPS to the Bot API, so the firewall can stay closed except for SSH.
Can one server host more than one bot?
Yes. Give each its own token, user, venv and unit file. For webhooks, use a different path or subdomain per bot behind the same Nginx.
python-telegram-bot or aiogram?
Both are actively developed and support the current Bot API. Choose by style: python-telegram-bot has a large tutorial base, aiogram suits developers who like routers and middleware.
How do I store user data?
SQLite through aiosqlite works for small bots. python-telegram-bot also offers PicklePersistence; for larger bots run PostgreSQL or Redis on the same server.
Can the bot send messages on a schedule?
Yes. python-telegram-bot has a JobQueue (install the job-queue extra), and aiogram pairs well with APScheduler. For heavy background work, use Celery.
More in Python
- Install Python 3, pip and venv
- Run legacy Python 2 code
- Manage Python projects with Poetry
- Miniconda and Anaconda on a server
- Deploy Flask with Gunicorn and Nginx
- Deploy FastAPI with Uvicorn workers
- Deploy Django with Gunicorn and Nginx
- Background tasks with Celery and Redis
- Host a Python Discord bot
- Containerise a Python web app
- JupyterLab on a server