OffshoreVps
Tutorials8 out. 20265 min readBy the OffshoreVps team

How to Host a Telegram Bot on a VPS

Get a bot token, write a Python bot, store the token safely and keep it running 24/7 with a systemd service.

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.

Terminal window on a VPS showing the commands used for hosting a Telegram bot, starting with “sudo apt update && sudo apt install -y python3 p”
The kind of commands you will run on your server in this guide.

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.

The steps of this guide in order: 1. What size VPS?; 2. get a bot token; 3. write a small bot; 4. store the token safely; 5. Updating and watching it; 6. Polling or webhook?
The steps in this guide, in order.

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.