
# Deploy a Telegram bot in Python to a VPS and run it 24/7

**To deploy a Telegram bot in Python, copy your code to an Ubuntu 24.04 VPS, install dependencies in a virtualenv, keep the token in a `.env` file and run the bot as a systemd service.** systemd keeps the bot online 24/7, restarts it after a crash and starts it again after a reboot. This guide uses aiogram 3.33 and Python 3.12, which ships with Ubuntu 24.04. The same steps work for python-telegram-bot: only the bot code changes.


Let an AI agent do the whole thing:


```text
Create an s1-1 server with Ubuntu 24.04 and hourly billing on 0x.cloud. Show me the dry_run price first and wait for my confirmation. Then deploy my aiogram Telegram bot from <repository URL>: create a virtualenv, install requirements.txt, put BOT_TOKEN in a .env file with 600 permissions, create a systemd service with Restart=always and show me how to read the logs.
```


## Requirements and plan

- **Server:** a simple bot runs on s1-1 (1 vCPU, 1 GB RAM, 15 GB NVMe) at $4.49/mo. A bot with an AI model, a database or image processing fits s1-2 (2 GB RAM) at $7.99/mo. See [Telegram bot hosting](https://0x.cloud/telegram-bot-hosting) for details.
- **OS:** Ubuntu 24.04 LTS. Python 3.12 is preinstalled, and aiogram 3 supports Python 3.11 through 3.15.
- **A bot token** from @BotFather.
- **Shortcut:** 0x.cloud has a bots image with Python, Telegram and Discord libraries, and a service that keeps your bot running. The steps below start from plain Ubuntu 24.04 and work with any provider.

Why s1-1 is enough for a simple bot: a polling bot is one Python process that spends most of its time waiting on Telegram. It needs tens of MB of RAM and almost no CPU; the rest of the 1 GB covers the OS and spikes. Once the bot runs a local model, processes images or keeps a database, move to s1-2 so 2 GB of RAM keeps it from being killed when memory runs out.

Trying it is cheap: s1-1 on hourly billing is $0.030750 an hour ($4.49 / 730 × 5), and setup is $0. Delete it and the remainder returns to your balance.


[Deploy to 0x.cloud](https://0x.cloud/cabinet/create?plan=s1-1&app=bots)


## Prepare the server

Open the web console of the server in your cabinet (an agent runs the same commands with `run_command`) and install the basics:

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

`python3-venv` lets you create virtual environments and `git` pulls your code.

Turn on the firewall. A polling bot needs no inbound ports, only SSH:

```bash
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status
```

The output should include `OpenSSH ALLOW Anywhere`. More rules are in the UFW firewall guide. Work as a regular sudo user, not root. The examples use a user called `deploy` (create it with `sudo adduser deploy`).

## Deploy the Telegram bot in Python: code and virtualenv

```bash
git clone https://github.com/you/tgbot.git ~/tgbot   # or: mkdir ~/tgbot
cd ~/tgbot
python3 -m venv .venv
.venv/bin/pip install -U pip aiogram
.venv/bin/python -c "import aiogram; print(aiogram.__version__)"
```

`python3 -m venv .venv` creates an isolated environment. Ubuntu 24.04 blocks `pip install` into the system Python (`externally-managed-environment`), so a venv is required. The last command should print a version such as `3.33.0`. If you have a `requirements.txt`, run `.venv/bin/pip install -r requirements.txt`.

A minimal aiogram 3 bot, `bot.py`:

```python
import asyncio
import logging
import os

from aiogram import Bot, Dispatcher
from aiogram.filters import CommandStart
from aiogram.types import Message

dp = Dispatcher()


@dp.message(CommandStart())
async def start(message: Message) -> None:
    await message.answer("Running on a server 24/7")


@dp.message()
async def echo(message: Message) -> None:
    await message.send_copy(chat_id=message.chat.id)


async def main() -> None:
    logging.basicConfig(level=logging.INFO)
    bot = Bot(token=os.environ["BOT_TOKEN"])
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())
```

Keep the token out of the code:

```bash
echo 'BOT_TOKEN=123456:ABC...' > .env
chmod 600 .env
```

Test it in the foreground:

```bash
set -a; . ./.env; set +a
.venv/bin/python bot.py
```

`set -a` exports every variable from `.env`. Send `/start` to the bot, confirm it replies, then press Ctrl+C.

## Run the bot 24/7 with systemd

```bash
sudo nano /etc/systemd/system/tgbot.service
```

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

[Service]
User=deploy
WorkingDirectory=/home/deploy/tgbot
EnvironmentFile=/home/deploy/tgbot/.env
ExecStart=/home/deploy/tgbot/.venv/bin/python bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
```

- `After=network-online.target` waits for the network before starting;
- `EnvironmentFile` passes the token from `.env`;
- `Restart=always` with `RestartSec=5` restarts the bot five seconds after any exit.

Enable and start it:

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now tgbot
systemctl status tgbot
journalctl -u tgbot -f
```

`systemctl status` should show `Active: active (running)`, and the log should show `Start polling` and `Run polling for bot @your_bot`. `daemon-reload` reads the new unit, `enable --now` turns on autostart and starts the bot, and `journalctl -f` streams the logs. Every unit option is explained in [how to create a systemd service](https://0x.cloud/kb/servers/systemd-service).

## Webhook instead of polling

Polling suits most bots. With a webhook, Telegram pushes updates to your URL, which saves resources at high volume. You need a domain, an HTTPS certificate and port 443, 80, 88 or 8443. Incoming connections from the internet don't reach 0x.cloud servers, so use polling there. The aiogram + aiohttp pattern (imports and `dp` as in `bot.py`):

```python
from aiohttp import web
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application

BASE_URL = "https://bot.example.com"
SECRET = os.environ["WEBHOOK_SECRET"]


async def on_startup(bot: Bot) -> None:
    await bot.set_webhook(f"{BASE_URL}/webhook", secret_token=SECRET)


def main() -> None:
    bot = Bot(token=os.environ["BOT_TOKEN"])
    dp.startup.register(on_startup)
    app = web.Application()
    SimpleRequestHandler(dispatcher=dp, bot=bot, secret_token=SECRET).register(app, path="/webhook")
    setup_application(app, dp, bot=bot)
    web.run_app(app, host="127.0.0.1", port=8080)
```

The bot listens on `127.0.0.1:8080` only, and Nginx with a Let's Encrypt certificate proxies public HTTPS traffic to it. `secret_token` rejects requests that don't come from Telegram. Full details are in the [aiogram webhook docs](https://docs.aiogram.dev/en/latest/dispatcher/webhook.html).

## Update the bot

```bash
cd ~/tgbot
git pull
.venv/bin/pip install -r requirements.txt
sudo systemctl restart tgbot
```

This pulls new code, updates dependencies and restarts the service, so the bot is offline only for the few seconds the service takes to restart.

## Back up the bot

Your code lives in Git. What stays only on the server is `.env` and data such as a SQLite file:

```bash
tar czf ~/tgbot-backup-$(date +%F).tar.gz -C ~ tgbot/.env tgbot/bot.db
```

Copy the archive off the server, for example with `scp` to another machine of yours. On 0x.cloud you can also enable automatic server backups (7 daily copies, +20% of the plan price) or take a $0.99/mo snapshot before a big change.

## Troubleshooting

| Error | Fix |
|---|---|
| `TelegramConflictError: terminated by other getUpdates request` | The bot runs twice (maybe on your laptop too). Keep one copy |
| `TelegramUnauthorizedError` | Wrong token in `.env`. Check it with @BotFather |
| `KeyError: 'BOT_TOKEN'` | The service can't read `.env`. Check the `EnvironmentFile` path |
| `error: externally-managed-environment` | You're installing into system Python. Use `.venv/bin/pip` |
| `start request repeated too quickly` | The bot crashes on start. Read `journalctl -u tgbot -n 50` |
| Webhook updates never arrive | Wrong port or certificate. Check `getWebhookInfo` in the Bot API |

Running a scraper or worker rather than a bot? Follow [how to run a Python script 24/7](https://0x.cloud/deploy/python-script-24-7). Prefer JavaScript? See the [Node.js Telegram bot guide (grammY)](https://0x.cloud/deploy/telegram-bot-nodejs).

Servers are in Warsaw, and support answers in about 30 minutes on average during business hours (06:00–20:00 UTC). If you break the system, reinstalling the OS costs $0.

## FAQ

**Why does my bot stop when I close the terminal?**
A process started in an SSH session gets a hangup signal when you disconnect. Run the bot as a systemd service instead: it's independent of your session and restarts after crashes and reboots.

**Polling or webhook: which should I use?**
Polling is simpler: no domain or certificate, the bot asks Telegram for updates. Webhooks are more efficient at high volume but need an HTTPS URL on port 443, 80, 88 or 8443.

**How much does a server for a Telegram bot cost?**
A simple bot fits on s1-1 (1 vCPU, 1 GB RAM) at $4.49/mo. A bot that calls an AI model and keeps a database is happier on s1-2 with 2 GB RAM at $7.99/mo.

**Can I host a Telegram bot for free?**
Yes, on your own computer, but the bot goes offline when the computer does. Free tiers of cloud platforms usually put apps to sleep or cap their running hours. An s1-1 server costs $0.030750 an hour, runs the bot 24/7, and if you delete it the unused balance stays on your account.

**Can one server run several bots?**
Yes. Give each bot its own folder, its own virtualenv and its own systemd service with a unique name.


[Deploy to 0x.cloud](https://0x.cloud/cabinet/create?plan=s1-1&app=bots)



[Create server: s1-1, $4.49/mo](https://0x.cloud/cabinet/create?plan=s1-1)
