Skip to content

06. Deployment Guide

ad1107 edited this page May 25, 2025 · 2 revisions

Deployment Guide

Complete deployment guide for UtilsBot+ covering Docker, VPS, cloud platforms, and production best practices.

📋 Table of Contents


Quick Start

Prerequisites

  • Python 3.11+ (Python 3.12 recommended)
  • Git for cloning the repository
  • Discord Bot Token (Create here)
  • Google Gemini API Key (Free tier here)

Minimum System Requirements

Resource Minimum Recommended
RAM 512MB 1GB+
CPU 1 core 2+ cores
Storage 2GB 5GB+
Network 1Mbps 10Mbps+

Docker Deployment

Using Docker Compose (Recommended)

1. Clone and Setup:

git clone https://github.com/ad1107/utils-bot-plus.git
cd utils-bot-plus
cp .env.example .env
# Edit .env with your configuration

2. Configure Environment:

# .env file
BOT_TOKEN=your_discord_bot_token
DEV_IDS=your_discord_id
GEMINI_API_KEY=your_gemini_api_key
SECRET_KEY=your_32_char_secret_key

# Production settings
DEBUG=false
LOG_LEVEL=INFO
DATABASE_URL=sqlite+aiosqlite:///data/bot.db

3. Deploy with Docker Compose:

# Build and start the bot
docker-compose up -d

# View logs
docker-compose logs -f bot

# Stop the bot
docker-compose down

Docker Compose Configuration

docker-compose.yml:

version: '3.8'

services:
  bot:
    build: .
    container_name: utils-bot-plus
    restart: unless-stopped
    environment:
      - BOT_TOKEN=${BOT_TOKEN}
      - DEV_IDS=${DEV_IDS}
      - GEMINI_API_KEY=${GEMINI_API_KEY}
      - SECRET_KEY=${SECRET_KEY}
      - DEBUG=false
      - LOG_LEVEL=INFO
    volumes:
      - ./data:/app/data
      - ./logs:/app/logs
    networks:
      - bot-network

  # Optional: PostgreSQL database
  postgres:
    image: postgres:15-alpine
    container_name: utils-bot-postgres
    restart: unless-stopped
    environment:
      POSTGRES_DB: utilsbot
      POSTGRES_USER: botuser
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - bot-network
    ports:
      - "5432:5432"

  # Optional: Redis for caching
  redis:
    image: redis:7-alpine
    container_name: utils-bot-redis
    restart: unless-stopped
    networks:
      - bot-network
    ports:
      - "6379:6379"

volumes:
  postgres_data:

networks:
  bot-network:
    driver: bridge

Single Container Deployment

# Build the image
docker build -t utils-bot-plus .

# Run the container
docker run -d \
  --name utils-bot-plus \
  --restart unless-stopped \
  -e BOT_TOKEN="your_token" \
  -e DEV_IDS="your_id" \
  -e GEMINI_API_KEY="your_key" \
  -v $(pwd)/data:/app/data \
  -v $(pwd)/logs:/app/logs \
  utils-bot-plus

VPS Deployment

Ubuntu/Debian Setup

1. System Preparation:

# Update system
sudo apt update && sudo apt upgrade -y

# Install Python 3.11+
sudo apt install python3.11 python3.11-pip python3.11-venv git -y

# Create user for the bot
sudo useradd -m -s /bin/bash utilsbot
sudo su - utilsbot

2. Application Setup:

# Clone repository
git clone https://github.com/ad1107/utils-bot-plus.git
cd utils-bot-plus

# Create virtual environment
python3.11 -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

3. Configuration:

# Copy and edit configuration
cp .env.example .env
nano .env

# Run setup script
chmod +x setup.sh
./setup.sh

# Initialize database
python migrations/init_db.py

4. Create Systemd Service:

Create /etc/systemd/system/utils-bot-plus.service:

[Unit]
Description=UtilsBot+ Discord Bot
After=network.target

[Service]
Type=simple
User=utilsbot
Group=utilsbot
WorkingDirectory=/home/utilsbot/utils-bot-plus
Environment=PATH=/home/utilsbot/utils-bot-plus/venv/bin
ExecStart=/home/utilsbot/utils-bot-plus/venv/bin/python main.py
Restart=always
RestartSec=10

# Security settings
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/home/utilsbot/utils-bot-plus/data /home/utilsbot/utils-bot-plus/logs

[Install]
WantedBy=multi-user.target

5. Start Service:

# Enable and start service
sudo systemctl enable utils-bot-plus
sudo systemctl start utils-bot-plus

# Check status
sudo systemctl status utils-bot-plus

# View logs
sudo journalctl -u utils-bot-plus -f

CentOS/RHEL Setup

# Install Python 3.11
sudo dnf install python3.11 python3.11-pip git -y

# Follow same steps as Ubuntu with systemd service

Cloud Platform Deployment

Railway

1. Prepare Repository:

# Ensure Procfile exists
echo "web: python main.py" > Procfile

# Ensure requirements.txt is up to date
pip freeze > requirements.txt

2. Deploy to Railway:

  1. Connect GitHub repository to Railway
  2. Set environment variables in Railway dashboard
  3. Deploy automatically from main branch

Environment Variables for Railway:

BOT_TOKEN=your_discord_bot_token
DEV_IDS=your_discord_id
GEMINI_API_KEY=your_gemini_api_key
SECRET_KEY=auto_generated_key
DATABASE_URL=postgresql://user:pass@host:port/db
PYTHON_VERSION=3.11.7

Heroku

1. Setup Heroku CLI:

# Install Heroku CLI
curl https://cli-assets.heroku.com/install.sh | sh

# Login to Heroku
heroku login

2. Create and Deploy:

# Create Heroku app
heroku create your-bot-name

# Set environment variables
heroku config:set BOT_TOKEN=your_token
heroku config:set DEV_IDS=your_id
heroku config:set GEMINI_API_KEY=your_key

# Add PostgreSQL addon
heroku addons:create heroku-postgresql:mini

# Deploy
git push heroku main

# View logs
heroku logs --tail

DigitalOcean App Platform

1. Create app.yaml:

name: utils-bot-plus
services:
- name: bot
  source_dir: /
  github:
    repo: ad1107/utils-bot-plus
    branch: main
  run_command: python main.py
  environment_slug: python
  instance_count: 1
  instance_size_slug: basic-xxs
  envs:
  - key: BOT_TOKEN
    scope: RUN_TIME
    type: SECRET
  - key: DEV_IDS
    scope: RUN_TIME
    type: SECRET
  - key: GEMINI_API_KEY
    scope: RUN_TIME
    type: SECRET
databases:
- name: bot-db
  engine: PG
  num_nodes: 1
  size: db-s-dev-database

AWS EC2

1. Launch EC2 Instance:

  • Choose Ubuntu 22.04 LTS
  • t3.micro or larger
  • Configure security group (no inbound ports needed)

2. Connect and Setup:

# Connect via SSH
ssh -i your-key.pem ubuntu@your-instance-ip

# Follow VPS deployment steps

Production Configuration

Environment Variables

Production .env:

# Bot Configuration
BOT_TOKEN=your_production_bot_token
DEV_IDS=your_discord_id
DEV_GUILD_ID=your_test_server_id

# API Keys
GEMINI_API_KEY=your_gemini_api_key
SCREENSHOT_API_KEY=your_screenshot_api_key
RAPIDAPI_KEY=your_rapidapi_key

# Security
SECRET_KEY=your_32_character_secret_key
CLOSED_BETA=false

# Database (Production)
DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/dbname

# Feature Toggles
ENABLE_GAMES=true
ENABLE_NETWORK_TOOLS=true
ENABLE_AI_COMMANDS=true
ENABLE_SYSTEM_COMMANDS=true

# Logging
LOG_LEVEL=INFO
DEBUG=false
ENABLE_METRICS=true

# Monitoring
SENTRY_DSN=your_sentry_dsn
HEALTH_CHECK_URL=https://your-healthcheck-url

# Performance
REDIS_URL=redis://localhost:6379
CACHE_TTL=300
GLOBAL_RATE_LIMIT=10
COOLDOWN_RATE=2

Database Configuration

PostgreSQL Production Setup:

# Install PostgreSQL
sudo apt install postgresql postgresql-contrib -y

# Create database and user
sudo -u postgres psql
CREATE DATABASE utilsbot;
CREATE USER botuser WITH ENCRYPTED PASSWORD 'secure_password';
GRANT ALL PRIVILEGES ON DATABASE utilsbot TO botuser;
\q

# Update connection string
DATABASE_URL=postgresql+asyncpg://botuser:secure_password@localhost:5432/utilsbot

Reverse Proxy (Optional)

Nginx Configuration (if serving web interface):

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Monitoring & Maintenance

Health Checks

Built-in Health Check:

# Add to main.py
@bot.event
async def on_ready():
    # Health check endpoint
    if settings.health_check_url:
        async with aiohttp.ClientSession() as session:
            await session.get(f"{settings.health_check_url}/start")

Log Monitoring

Log Rotation:

# Create logrotate configuration
sudo nano /etc/logrotate.d/utils-bot-plus

/home/utilsbot/utils-bot-plus/logs/*.log {
    daily
    missingok
    rotate 7
    compress
    notifempty
    create 644 utilsbot utilsbot
    postrotate
        systemctl reload utils-bot-plus
    endscript
}

Backup Strategy

Database Backup:

#!/bin/bash
# backup.sh
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/home/utilsbot/backups"

# Create backup directory
mkdir -p $BACKUP_DIR

# Backup PostgreSQL
pg_dump -h localhost -U botuser -d utilsbot > $BACKUP_DIR/backup_$DATE.sql

# Backup SQLite (if using)
cp /home/utilsbot/utils-bot-plus/data/bot.db $BACKUP_DIR/bot_backup_$DATE.db

# Clean old backups (keep 7 days)
find $BACKUP_DIR -name "backup_*" -mtime +7 -delete

Automated Backups:

# Add to crontab
crontab -e

# Backup daily at 2 AM
0 2 * * * /home/utilsbot/backup.sh

Updates and Maintenance

Update Script:

#!/bin/bash
# update.sh
cd /home/utilsbot/utils-bot-plus

# Stop service
sudo systemctl stop utils-bot-plus

# Backup current version
cp -r . ../utils-bot-plus-backup-$(date +%Y%m%d)

# Pull updates
git pull origin main

# Update dependencies
source venv/bin/activate
pip install -r requirements.txt

# Run migrations if needed
python migrations/migrate.py

# Start service
sudo systemctl start utils-bot-plus

# Check status
sudo systemctl status utils-bot-plus

Security Considerations

Firewall Configuration

# UFW firewall setup
sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow SSH (adjust port as needed)
sudo ufw allow 22/tcp

# No other ports needed for Discord bot

SSL/TLS Configuration

For web interfaces (if applicable):

# Install Certbot
sudo apt install certbot python3-certbot-nginx -y

# Get SSL certificate
sudo certbot --nginx -d your-domain.com

Secrets Management

Using Docker Secrets:

# docker-compose.yml
services:
  bot:
    secrets:
      - bot_token
      - gemini_api_key
    environment:
      - BOT_TOKEN_FILE=/run/secrets/bot_token

secrets:
  bot_token:
    external: true
  gemini_api_key:
    external: true

Security Hardening

# Disable root login
sudo sed -i 's/PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

# Change SSH port (optional)
sudo sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config

# Restart SSH
sudo systemctl restart ssh

# Install fail2ban
sudo apt install fail2ban -y
sudo systemctl enable fail2ban

🔗 Related Pages


📝 What's Next?

Clone this wiki locally