Skip to content

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

  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:

sudo adduser --disabled-login botuser
sudo chown -R botuser:botuser /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:

sudo apt update && sudo apt install screen -y

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 KY

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
    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
    

  3. Enable the service:

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

  4. 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, 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:

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 ×