Skip to content

Running the bot in the background

In this article

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

  1. Place the bot code, e.g., in /home/user/bot:

    mkdir -p /home/user/bot && cd /home/user/bot
    

  2. Create and activate a virtual environment to isolate dependencies:

    python3 -m venv venv
    source venv/bin/activate
    

  3. Install dependencies:

    pip install -r requirements.txt
    # If the file does not exist — install manually, e.g., pip install python-telegram-bot
    

  4. Test manual launch:

    python main.py
    

Note

Do not run the bot as root unless necessary. It's better to create a dedicated user:

# Ubuntu / Debian
sudo adduser --disabled-login botuser
# CentOS / AlmaLinux / Rocky Linux
sudo useradd -m -s /sbin/nologin botuser

sudo chown -R botuser:botuser /home/user/bot

Make sure that botuser has read access to the /home/user directory (otherwise the service will not be able to open /home/user/bot).

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:

# Ubuntu / Debian
sudo apt update && sudo apt install screen -y

# CentOS 7
sudo yum install -y screen

# AlmaLinux / Rocky Linux 9–10 (the package is in EPEL)
sudo dnf install -y epel-release && sudo dnf install -y screen

Note

Instead of screen, you can use tmux — it is available in the standard repositories of all the distributions listed above.

Launch:

screen -S bot  # create a named session
source venv/bin/activate
python main.py

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.

Pros: autostart, restart on errors, logging, system integration.
Cons: requires writing a config.

  1. Create a unit file:

    sudo nano /etc/systemd/system/bot.service
    

  2. Paste the config (adapt paths and user!):

    [Unit]
    Description=Telegram Bot Service
    After=network.target
    StartLimitIntervalSec=30
    StartLimitBurst=5
    
    [Service]
    Type=simple
    # It is recommended not to run as root
    User=botuser
    Group=botuser
    WorkingDirectory=/home/user/bot
    ExecStart=/home/user/bot/venv/bin/python /home/user/bot/main.py
    Restart=always
    RestartSec=10
    # So that logs are not buffered
    Environment="PYTHONUNBUFFERED=1"
    
    # Security (optional, but recommended)
    NoNewPrivileges=true
    PrivateTmp=true
    ProtectSystem=strict
    # The bot code is located in /home, so the directory is mounted read-only
    ProtectHome=read-only
    # Directory the bot is allowed to write to (if needed; "-" means it is not an error if it does not exist)
    ReadWritePaths=-/home/user/bot/data
    
    [Install]
    WantedBy=multi-user.target
    

Attention

In systemd unit files, comments are only allowed on a separate line starting with # or ;. A comment at the end of a line with a parameter becomes part of its value, and the service will fail to start.

  1. Enable the service:

    sudo systemctl daemon-reload
    sudo systemctl enable bot.service   # autostart on boot
    sudo systemctl start bot.service    # start now
    

  2. Check status and logs:

    sudo systemctl status bot.service
    journalctl -u bot.service -f --since "1 hour ago"
    

Security tips

Restrict the service from accessing unnecessary parts of the system (via ProtectSystem, ProtectHome, ReadOnlyPaths);

Limit the network capabilities of the service: RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX allows only IPv4/IPv6 network sockets and local sockets, while IPAddressDeny=/IPAddressAllow= let you define a list of allowed addresses;

You can additionally use ProtectKernelTunables=true, ProtectControlGroups=true, PrivateDevices=true;

Use RuntimeDirectory= for temporary files;

You can assess the isolation level of the service with systemd-analyze security bot.service.

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:

cd /home/user/bot
pm2 start main.py --name "my-bot" --interpreter ./venv/bin/python

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!).

question_mark
Is there anything I can help you with?
question_mark
AI Assistant ×