Installation Guide - openguard-bot/openguard GitHub Wiki

Installation Guide

This comprehensive guide covers the complete installation and setup process for AIMod, from basic development setup to production deployment.

๐Ÿš€ Quick Start

Prerequisites

System Requirements:

  • Operating System: Linux (Ubuntu 20.04+ recommended), macOS, or Windows 10+
  • Python: 3.11 or higher
  • Node.js: 18.0 or higher (for dashboard)
  • PostgreSQL: 13 or higher
  • Redis: 6.0 or higher
  • Memory: Minimum 2GB RAM, 4GB+ recommended
  • Storage: 10GB+ available space

Required Accounts:

  • Discord Developer Account - For bot token
  • AI Provider Account - OpenRouter, OpenAI, or GitHub Copilot
  • Domain Name (for production) - For dashboard hosting

Basic Installation

1. Clone the Repository

git clone https://github.com/discordaimod/aimod.git
cd aimod

2. Install Python Dependencies

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

3. Set Up Environment Variables

# Copy environment template
cp .env.example .env

# Edit environment file
nano .env

Required Environment Variables:

# Discord Configuration
DISCORD_TOKEN=your_bot_token_here
DISCORD_CLIENT_ID=your_client_id
DISCORD_CLIENT_SECRET=your_client_secret

# Database Configuration
DATABASE_URL=postgresql://aimod_user:password@localhost:5432/aimod_bot
REDIS_URL=redis://localhost:6379

# AI Provider Configuration
OPENROUTER_API_KEY=your_openrouter_key
# OR
OPENAI_API_KEY=your_openai_key
# OR
GITHUB_TOKEN=your_github_token

# Security
JWT_SECRET=your_jwt_secret_here
ENCRYPTION_KEY=your_encryption_key_here

# Optional: External Services
MOD_LOG_API_SECRET=your_mod_log_secret
WEBHOOK_URL=your_webhook_url

4. Set Up Database

Install PostgreSQL:

# Ubuntu/Debian
sudo apt update
sudo apt install postgresql postgresql-contrib

# macOS (with Homebrew)
brew install postgresql
brew services start postgresql

# Windows
# Download from https://www.postgresql.org/download/windows/

Create Database:

# Run the setup script
./setup_postgresql.sh

# Or manually:
sudo -u postgres psql
CREATE DATABASE aimod_bot;
CREATE USER aimod_user WITH PASSWORD 'your_password';
GRANT ALL PRIVILEGES ON DATABASE aimod_bot TO aimod_user;
\q

5. Set Up Redis

Install Redis:

# Ubuntu/Debian
sudo apt install redis-server

# macOS (with Homebrew)
brew install redis
brew services start redis

# Windows
# Download from https://redis.io/download

Start Redis:

redis-server

6. Initialize Database Schema

# Run database migrations
python migrate_json_to_postgresql.py

# Or if starting fresh:
python -c "
from database.connection import initialize_database
import asyncio
asyncio.run(initialize_database())
"

7. Start the Bot

python bot.py

๐Ÿ”ง Development Setup

IDE Configuration

VS Code Setup:

// .vscode/settings.json
{
    "python.defaultInterpreterPath": "./venv/bin/python",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "python.formatting.provider": "black",
    "python.formatting.blackArgs": ["--line-length", "88"],
    "files.exclude": {
        "**/__pycache__": true,
        "**/*.pyc": true
    }
}

PyCharm Setup:

  1. Open project in PyCharm
  2. Configure Python interpreter to use ./venv/bin/python
  3. Enable Black formatter in Settings โ†’ Tools โ†’ External Tools
  4. Configure database connection in Database tool window

Development Dependencies

# Install development dependencies
pip install -r requirements-dev.txt

# Install pre-commit hooks
pre-commit install

requirements-dev.txt:

pytest>=7.0.0
pytest-asyncio>=0.21.0
black>=23.0.0
pylint>=2.17.0
mypy>=1.0.0
pre-commit>=3.0.0
coverage>=7.0.0

Testing Setup

# Run all tests
pytest

# Run with coverage
pytest --cov=. --cov-report=html

# Run specific test file
pytest test_postgresql_migration.py

# Run tests with verbose output
pytest -v

Database Development

Development Database:

# Create development database
createdb aimod_bot_dev

# Run migrations on dev database
DATABASE_URL=postgresql://aimod_user:password@localhost:5432/aimod_bot_dev python migrate_json_to_postgresql.py

Database Tools:

# Connect to database
psql -h localhost -U aimod_user -d aimod_bot

# Backup database
pg_dump -h localhost -U aimod_user aimod_bot > backup.sql

# Restore database
psql -h localhost -U aimod_user -d aimod_bot < backup.sql

๐ŸŒ Dashboard Setup

Frontend Development

# Navigate to dashboard frontend
cd dashboard/frontend

# Install dependencies
npm install

# Start development server
npm start

Package.json Configuration:

{
  "name": "aimod-dashboard",
  "version": "2.0.0",
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "typescript": "^5.0.0",
    "tailwindcss": "^3.3.0",
    "axios": "^1.4.0",
    "react-router-dom": "^6.11.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

Backend Development

# Navigate to dashboard backend
cd dashboard/backend

# Install Python dependencies (if not already done)
pip install fastapi uvicorn python-multipart

# Start development server
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Environment Configuration

Frontend (.env):

REACT_APP_API_URL=http://localhost:8000/api
REACT_APP_DISCORD_CLIENT_ID=your_client_id

Backend (.env):

# Same as main bot configuration
DATABASE_URL=postgresql://aimod_user:password@localhost:5432/aimod_bot
REDIS_URL=redis://localhost:6379
DISCORD_CLIENT_ID=your_client_id
DISCORD_CLIENT_SECRET=your_client_secret
DISCORD_REDIRECT_URI=http://localhost:3000/api/callback

๐Ÿ” Discord Bot Setup

Creating a Discord Application

  1. Go to Discord Developer Portal:

  2. Configure Bot Settings:

    • Go to "Bot" section
    • Click "Add Bot"
    • Copy the bot token (keep this secret!)
    • Enable required intents:
      • โœ… Presence Intent
      • โœ… Server Members Intent
      • โœ… Message Content Intent
  3. Set Bot Permissions:

    • Go to "OAuth2" โ†’ "URL Generator"
    • Select "bot" and "applications.commands" scopes
    • Select required permissions:
      • โœ… Administrator (recommended for full functionality)
      • Or specific permissions:
        • Ban Members
        • Kick Members
        • Manage Messages
        • Manage Channels
        • Manage Roles
        • View Audit Log
        • Send Messages
        • Use Slash Commands
  4. OAuth2 Configuration:

    • Add redirect URI: http://localhost:3000/api/callback (development)
    • For production: https://yourdomain.com/api/callback

Inviting the Bot

  1. Use the generated OAuth2 URL from step 3 above
  2. Select your server
  3. Authorize the bot with required permissions
  4. Verify the bot appears in your server's member list

๐Ÿ”‘ AI Provider Setup

OpenRouter (Recommended)

  1. Create Account:

  2. Get API Key:

    • Go to "Keys" section
    • Create a new API key
    • Copy the key to your .env file as OPENROUTER_API_KEY
  3. Configure Model:

    # In your .env file
    OPENROUTER_API_KEY=sk-or-v1-your-key-here
    DEFAULT_AI_MODEL=github_copilot/gpt-4.1
    

GitHub Copilot

  1. GitHub Copilot Subscription:

    • Ensure you have an active GitHub Copilot subscription
    • Generate a personal access token with appropriate scopes
  2. Configuration:

    # In your .env file
    GITHUB_TOKEN=ghp_your-token-here
    DEFAULT_AI_MODEL=github_copilot/gpt-4.1
    

OpenAI

  1. OpenAI Account:

  2. API Key:

    # In your .env file
    OPENAI_API_KEY=sk-your-openai-key-here
    DEFAULT_AI_MODEL=openai/gpt-4
    

๐Ÿงช Testing Installation

Basic Functionality Test

# Test database connection
python -c "
from database.connection import get_pool
import asyncio

async def test_db():
    pool = await get_pool()
    if pool:
        print('โœ… Database connection successful')
    else:
        print('โŒ Database connection failed')

asyncio.run(test_db())
"

# Test Redis connection
python -c "
from database.cache import get_redis_client
import asyncio

async def test_redis():
    redis = get_redis_client()
    await redis.set('test', 'value')
    result = await redis.get('test')
    if result == 'value':
        print('โœ… Redis connection successful')
    else:
        print('โŒ Redis connection failed')

asyncio.run(test_redis())
"

# Test AI provider
python test_litellm_integration.py

Bot Functionality Test

  1. Start the bot:

    python bot.py
    
  2. Test basic commands in Discord:

    /ping
    /config setting:enabled
    /stats
    
  3. Test AI moderation:

    /aitest message:"This is a test message"
    

Dashboard Test

  1. Start backend:

    cd dashboard/backend
    uvicorn main:app --reload
    
  2. Start frontend:

    cd dashboard/frontend
    npm start
    
  3. Test authentication:

๐Ÿ”ง Troubleshooting

Common Issues

Database Connection Errors:

# Check PostgreSQL status
sudo systemctl status postgresql

# Check if database exists
psql -h localhost -U aimod_user -l

# Reset database permissions
sudo -u postgres psql
GRANT ALL PRIVILEGES ON DATABASE aimod_bot TO aimod_user;
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO aimod_user;

Redis Connection Errors:

# Check Redis status
redis-cli ping

# Start Redis if not running
redis-server

# Check Redis configuration
redis-cli config get "*"

Bot Permission Errors:

  • Verify bot has required permissions in Discord server
  • Check bot role hierarchy (bot role should be above roles it needs to manage)
  • Ensure bot has "Use Slash Commands" permission

AI Provider Errors:

# Test API key
curl -H "Authorization: Bearer $OPENROUTER_API_KEY" \
     https://openrouter.ai/api/v1/models

# Check rate limits and credits
# Verify model availability

Log Analysis

Bot Logs:

# View recent logs
tail -f bot.log

# Search for errors
grep -i error bot.log

# Check specific component
grep -i "core_ai_cog" bot.log

Database Logs:

# PostgreSQL logs (Ubuntu)
sudo tail -f /var/log/postgresql/postgresql-13-main.log

# Check slow queries
grep "slow query" /var/log/postgresql/postgresql-13-main.log

Performance Optimization

Database Optimization:

-- Check database performance
SELECT * FROM pg_stat_activity WHERE state = 'active';

-- Analyze query performance
EXPLAIN ANALYZE SELECT * FROM guild_config WHERE guild_id = 123456789;

-- Update table statistics
ANALYZE guild_config;

Memory Optimization:

# Monitor memory usage
htop

# Check Python memory usage
python -c "
import psutil
process = psutil.Process()
print(f'Memory usage: {process.memory_info().rss / 1024 / 1024:.2f} MB')
"

Next: Production Deployment - Production environment setup and deployment