Running the bot in the background¶
To have a Python (or any other) bot run continuously, automatically restart on failures, and start after server reboot, simply running python main.py is not enough. You need a full‑fledged background service.
Below are three proven methods: from the simple screen to the industrial‑grade systemd. Choose based on your requirements.
Preparing the environment¶
-
Place the bot code, e.g., in
/home/user/bot: -
Create and activate a virtual environment to isolate dependencies:
-
Install dependencies:
-
Test manual launch:
Note
Do not run the bot as root unless necessary. It's better to create a dedicated user:
Method 1. screen — quick launch (for testing and development)¶
Pros: easiest to get started.
Cons: does not restart after a crash or reboot — not suitable for production.
Installation:
Launch:
Management:
| Action | Command |
|---|---|
| Detach from session (leave in background) | Ctrl + A, then D |
| View list of sessions | screen -ls |
| Return to session | screen -r bot |
| Terminate session from inside | Ctrl + A, then K → Y |
Information
Upon server reboot or script crash, the bot will remain stopped. Use only for temporary tasks.
Method 2. systemd — Linux standard for services (recommended)¶
Pros: autostart, restart on errors, logging, system integration.
Cons: requires writing a config.
-
Create a unit file:
-
Paste the config (adapt paths and user!):
[Unit] Description=Telegram Bot Service After=network.target StartLimitIntervalSec=30 StartLimitBurst=5 [Service] Type=simple User=botuser # ← recommended not root! Group=botuser WorkingDirectory=/home/user/bot ExecStart=/home/user/bot/venv/bin/python /home/user/bot/main.py Restart=always RestartSec=10 Environment="PYTHONUNBUFFERED=1" # so logs aren't buffered # Security (optional, but recommended) NoNewPrivileges=true PrivateTmp=true ProtectSystem=strict ProtectHome=true ReadWritePaths=/home/user/bot/data/ # if the bot needs data access [Install] WantedBy=multi-user.target -
Enable the service:
-
Check status and logs:
Security tips
Restrict the service from accessing unnecessary parts of the system (via ProtectSystem, ReadOnlyPaths); If the bot only needs internet — add RestrictNetwork=true and configure IPAddressAllow=...; Use RuntimeDirectory= for temporary files.
Method 3. PM2 — process manager (for Node.js, but supports Python)¶
Pros: simplicity, built‑in logs, monitoring, web interface.
Cons: requires Node.js, overkill for simple Python bots.
Installation:
# Install Node.js and npm (if not already installed)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs
# Install PM2 globally
sudo npm install -g pm2
Start the Python bot:
Useful commands:
| Command | Purpose |
|---|---|
pm2 list | List of processes |
pm2 logs my-bot | View logs |
pm2 monit | Real‑time monitoring |
pm2 startup | Configure autostart after reboot |
pm2 save | Save current processes |
Information
After pm2 startup, follow the terminal instructions — PM2 will generate a systemd unit for autostart.
Method Comparison¶
| Criterion | screen | systemd | PM2 |
|---|---|---|---|
| Autostart after reboot | No | Yes | Yes (requires pm2 startup) |
| Restart on crash | No | Yes | Yes |
| Logging | Only in session | journalctl | Built‑in logs |
| Security | Low | High (isolation settings) | Medium |
| Configuration complexity | Low | Medium | Low (but requires Node.js) |
| Suitable for production | No | Recommended | Yes (if already using Node.js) |
Additional
Set up alerting when the bot stops (e.g., via systemd + healthchecks.io);
Regularly update dependencies pip list --outdated;
Use .env files and python-dotenv to store tokens (and exclude them from Git!).