A Telegram bot has to be running all the time to answer messages. Running it on your laptop means it goes offline whenever you close the lid. A small VPS fixes that for a few dollars a month. This guide runs a Python bot as a systemd service so it starts on boot and restarts after a crash.
What size VPS?
Most bots are light. A plan with 1 to 2 vCPUs and 2 GB of RAM is plenty. See Telegram bot hosting for suggested plans.
Step 1: get a bot token
Talk to @BotFather on Telegram, send /newbot, choose a name and a username ending in bot, and copy the token. Treat it like a password, because anyone with it can control the bot.
Step 2: prepare the server
sudo apt update && sudo apt install -y python3 python3-venv
sudo adduser --disabled-password --gecos "" botuser
sudo -iu botuser
mkdir ~/mybot && cd ~/mybot
python3 -m venv .venv
. .venv/bin/activate
pip install python-telegram-bot
Step 3: write a small bot
# bot.py
import os
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
async def start(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Hello! I am running on a VPS.")
app = ApplicationBuilder().token(os.environ["BOT_TOKEN"]).build()
app.add_handler(CommandHandler("start", start))
app.run_polling()
Polling needs no open ports, so you do not have to set up a domain or a webhook.
Step 4: store the token safely
echo "BOT_TOKEN=123456:ABC..." > ~/mybot/.env
chmod 600 ~/mybot/.env
Step 5: run it as a service
Back as an admin user, create /etc/systemd/system/mybot.service:
[Unit]
Description=Telegram bot
After=network-online.target
[Service]
User=botuser
WorkingDirectory=/home/botuser/mybot
EnvironmentFile=/home/botuser/mybot/.env
ExecStart=/home/botuser/mybot/.venv/bin/python bot.py
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now mybot
sudo journalctl -u mybot -f
Updating and watching it
- Update the code, then
sudo systemctl restart mybot. - Check logs with
journalctl -u mybot -n 100. - Use backups if the bot stores data.
Polling or webhook?
Polling is simplest and fine for most bots. Use a webhook if you need instant delivery at high volume, which needs a domain and HTTPS. See hosting with Nginx and HTTPS.