If you want a Telegram bot that answers around the clock, it can't live on your laptop. It needs a server that stays on when you close the lid, and a VPS is the natural fit: your own Linux box, SSH access and full control over the process. In this guide you'll run a Python bot built on aiogram 3 inside a virtual environment, keep the token in a .env file, and let systemd restart the bot when it crashes and bring it back after a reboot. If you haven't logged in to your server yet, start with how to connect to a VPS over SSH.

What you need

  • A VPS running Ubuntu 24.04 or Debian 12 with SSH access.
  • A bot token from @BotFather (send it the /newbot command).
  • Python 3.11 or newer. Ubuntu 24.04 and Debian 12 already ship with it.
  • Basic comfort with the Linux command line.

Step 1. Prepare the server

Update the system and install the packages for Python virtual environments. On Ubuntu and Debian, python3-venv is a separate package, and without it the venv command won't work.

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3 python3-venv python3-pip git

Next, create a dedicated system user with no login shell. Don't run the bot as root: if the token or the process gets compromised, the attacker only gets the bot's permissions, not the whole server.

sudo useradd --system --create-home --home-dir /opt/bot --shell /usr/sbin/nologin bot

Step 2. Write the bot with aiogram 3

Create a virtual environment in /opt/bot and install the libraries. The venv keeps the bot's dependencies separate from the system Python, so an OS upgrade won't break your bot.

sudo python3 -m venv /opt/bot/venv
sudo /opt/bot/venv/bin/pip install --upgrade pip aiogram python-dotenv
sudo chown -R bot:bot /opt/bot

Now create /opt/bot/bot.py. This is a bare-bones bot: it replies to /start and echoes back any text you send. Your own logic goes into the handlers.

import asyncio
import logging
import os

from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import Message
from dotenv import load_dotenv

load_dotenv('/opt/bot/.env')
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')

BOT_TOKEN = os.environ['BOT_TOKEN']

dp = Dispatcher()


@dp.message(CommandStart())
async def cmd_start(message: Message) -> None:
    await message.answer('The bot is running on a VPS. Send me any message.')


@dp.message(F.text)
async def echo(message: Message) -> None:
    await message.answer(message.text)


async def main() -> None:
    bot = Bot(token=BOT_TOKEN)
    await dp.start_polling(bot)


if __name__ == '__main__':
    asyncio.run(main())

This is aiogram 3 syntax: filters go into the dp.message decorator, and the bot object is created with the token at startup. A lot of older tutorials use aiogram 2, where the names are different, so don't copy-paste from those.

As the bot grows, split the handlers into modules. aiogram 3 gives you the Router class for that: each module creates its own router, and the main Dispatcher pulls them in with include_router. The code stays readable, and adding a command doesn't mean editing one giant file.

Step 3. Put the token in .env

Never hardcode the token, and definitely never commit it to Git. Create a .env file and paste in the token you got from @BotFather. The value below is a placeholder.

BOT_TOKEN=000000000:REPLACE_WITH_TOKEN_FROM_BOTFATHER
sudo nano /opt/bot/.env
sudo chown bot:bot /opt/bot/.env
sudo chmod 600 /opt/bot/.env

Mode 600 means only the file owner, the bot user, can read it. If the token ever ends up in a chat, a public repo or a screenshot, open @BotFather, send /revoke, pick the bot and put the new token in .env.

Step 4. Run it as a systemd service

Running python bot.py in an SSH session works for a quick test, but the process dies when you disconnect or the server reboots. systemd fixes both. Create a unit file at /etc/systemd/system/bot.service.

[Unit]
Description=Telegram bot (aiogram)
After=network-online.target
Wants=network-online.target

[Service]
User=bot
Group=bot
WorkingDirectory=/opt/bot
ExecStart=/opt/bot/venv/bin/python /opt/bot/bot.py
Restart=always
RestartSec=5
NoNewPrivileges=true

[Install]
WantedBy=multi-user.target

Restart=always restarts the process no matter how it exits: a crash, an unhandled exception or a signal. RestartSec=5 adds a five-second pause so a broken bot doesn't spin in a tight restart loop. Reload systemd and enable the service.

sudo systemctl daemon-reload
sudo systemctl enable --now bot
sudo systemctl status bot

enable makes the service start on boot, and --now starts it right away. Check that the Active line says active (running).

Logs and troubleshooting

systemd captures the process output in the journal. Everything you log with logging, plus Python tracebacks, lands there automatically, so you don't need separate log files.

journalctl -u bot -f                       # follow logs live
journalctl -u bot --since "1 hour ago"     # last hour
journalctl -u bot -n 100 --no-pager       # last 100 lines
journalctl -u bot -p err                   # errors only

One gotcha: if the service keeps crashing, Restart=always can hide it. The bot looks alive but never replies. Check systemctl status bot and the journal. The usual suspects are a wrong token, a missing library or a bug in your code.

Log through the logging module, and never log the token or users' personal data. Inside handlers, use logging.exception for errors, since it writes the full traceback. Use INFO for normal events and WARNING for unexpected situations the bot managed to handle.

For a quick health check without reading logs, run systemctl is-active bot. It prints active or failed, which makes it easy to wire into a small cron script that pings you when the bot goes down.

Updating the bot

An update is a handful of commands: pull the new code, update dependencies if they changed, restart the service. Generate requirements.txt once with pip freeze so every server runs the same library versions.

sudo /opt/bot/venv/bin/pip freeze > /opt/bot/requirements.txt
sudo -u bot git -C /opt/bot pull
sudo /opt/bot/venv/bin/pip install -r /opt/bot/requirements.txt
sudo systemctl restart bot
journalctl -u bot -n 50 --no-pager

If your code isn't in Git, upload the new bot.py to /opt/bot over SFTP or scp and run the last two commands. For a bot people actually use, back up the current directory before you update.

Webhook vs. polling

A bot can receive updates in two ways. With polling, which is what the example above uses, the bot keeps asking Telegram for new messages. It's the simple option: no domain, no HTTPS certificate, no open inbound ports. For most bots with moderate traffic, polling is plenty.

With a webhook, Telegram pushes updates to your HTTPS endpoint. That's more efficient under heavy traffic, but you need a domain with a valid certificate and one of the ports Telegram supports: 443, 80, 88 or 8443. For the web server and SSL part, see how to host a website on a VPS with Nginx and SSL. For your first bot, stick with polling.

Common mistakes

  • The token is hardcoded or committed to Git. Revoke it with /revoke and issue a new one.
  • The bot runs as root. Use a dedicated bot user, as shown in this guide.
  • The service doesn't come back after a reboot. Run systemctl is-enabled bot to make sure it's enabled.
  • Libraries were installed outside the venv. The service must run /opt/bot/venv/bin/python.

Wrapping up

A bot on a VPS comes down to four pieces: a venv with aiogram 3, a .env file with the token, a systemd unit with Restart=always, and journalctl for debugging. That setup survives crashes and reboots, and an update is just new code plus a restart. You don't need Docker for a single bot, but if you want to package several services together, check out Docker on a VPS. To pick a server size, see the VPS plans.