Find us on social media
Pythondiscord.pyDeploy5 min read
Deploy Discord bot with Python
Configure and run a Python bot (discord.py) with virtual environment and systemd.
Prerequisites
- VPS or Discord Bot hosting plan at Baires Host
- Your bot token from the Discord Developer Portal
- Python bot code ready to deploy
- SSH access to your server
Step 1: Install Python
bash
sudo apt update
sudo apt install -y python3 python3-pip python3-venv
python3 --versionStep 2: Create project structure
bash
mkdir -p /opt/bots/my-bot
cd /opt/bots/my-botRecommended structure:
terminal
my-bot/
├── bot/
│ ├── __init__.py
│ ├── main.py
│ ├── cogs/
│ │ ├── __init__.py
│ │ ├── moderation.py
│ │ └── utility.py
│ └── utils/
│ └── helpers.py
├── .env
├── requirements.txt
├── run.py
└── update.shStep 3: Set up virtual environment
bash
python3 -m venv venv
source venv/bin/activateStep 4: Install dependencies
Create requirements.txt:
terminal
discord.py>=2.3.0
python-dotenv>=1.0.0
aiohttp>=3.9.0Install:
bash
pip install -r requirements.txtStep 5: Configure environment variables
bash
nano .envenv
DISCORD_TOKEN=your_bot_token_here
PREFIX=!
OWNER_ID=your_discord_user_idStep 6: Create the run script
bash
nano run.pypython
import os
from dotenv import load_dotenv
from bot.main import MyBot
load_dotenv()
if __name__ == "__main__":
bot = MyBot()
bot.run(os.getenv("DISCORD_TOKEN"))Step 7: Create a systemd service
bash
sudo nano /etc/systemd/system/discord-bot.serviceini
[Unit]
Description=Discord Bot (Python)
After=network.target
[Service]
User=deploy
WorkingDirectory=/opt/bots/my-bot
ExecStart=/opt/bots/my-bot/venv/bin/python run.py
Restart=always
RestartSec=10
EnvironmentFile=/opt/bots/my-bot/.env
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.targetEnable and start:
bash
sudo systemctl daemon-reload
sudo systemctl enable discord-bot
sudo systemctl start discord-botStep 8: Create an update script
bash
nano update.shbash
#!/bin/bash
set -e
echo "[$(date)] Starting update..."
# Pull latest code
git pull origin main
# Update dependencies
source venv/bin/activate
pip install -r requirements.txt
# Restart the service
sudo systemctl restart discord-bot
echo "[$(date)] Update complete!"
sudo systemctl status discord-bot --no-pagerbash
chmod +x update.shManaging the bot
bash
# Check status
sudo systemctl status discord-bot
# View logs
journalctl -u discord-bot -f
# View last 50 lines
journalctl -u discord-bot -n 50
# Restart
sudo systemctl restart discord-bot
# Stop
sudo systemctl stop discord-botTips
- Use cogs to organize commands into modules for easier maintenance
- Log to file in addition to journald for easier debugging
- Pin dependency versions in requirements.txt for reproducible deployments
- Set up a webhook to notify you in Discord when the bot restarts
- Use
discord.pyintents properly - enable only what you need in the Developer Portal
Was this guide helpful?