Architecture Overview - openguard-bot/openguard GitHub Wiki

Architecture Overview

AIMod is built with a modular, scalable architecture designed for high-performance Discord moderation. This document provides a comprehensive overview of the system architecture, component relationships, and design patterns.

🏗️ System Architecture

High-Level Architecture

┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   Discord API   │    │   Web Dashboard │    │   Admin Panel   │
└─────────┬───────┘    └─────────┬───────┘    └─────────┬───────┘
          │                      │                      │
          │                      │                      │
┌─────────▼──────────────────────▼──────────────────────▼───────┐
│                     AIMod Core Bot                            │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐           │
│  │    Cogs     │  │   Events    │  │  Commands   │           │
│  └─────────────┘  └─────────────┘  └─────────────┘           │
└─────────┬─────────────────────────────────────────────────────┘
          │
┌─────────▼─────────┐    ┌─────────────────┐    ┌─────────────────┐
│   PostgreSQL      │    │     Redis       │    │   LiteLLM       │
│   Database        │    │     Cache       │    │   AI Service    │
└───────────────────┘    └─────────────────┘    └─────────────────┘

Core Components

1. Bot Core (bot.py)

  • Auto-sharded Discord bot using discord.py
  • Global error handling with notification system
  • Dynamic prefix management with caching
  • Cog loading system for modular functionality
  • Database connection management

2. Cog System

Modular architecture with specialized cogs:

Core Moderation:

  • core_ai_cog.py - AI-powered message analysis and moderation
  • config_cog.py - Guild configuration management
  • human_moderation_cog.py - Manual moderation tools

Security & Protection:

  • botdetect.py - Bot detection and automated responses
  • raiddefence.py - Raid protection and mass action detection
  • ban_appeal_cog.py - Appeal system for moderation actions

Analytics & Logging:

  • logging_cog.py - Comprehensive event logging
  • statistics.py - Usage analytics and performance metrics
  • mod_log_cog.py - Moderation action logging

Utility & Management:

  • help.py - Dynamic help system
  • ping.py - Bot status and latency monitoring
  • update.py - Bot update and maintenance tools

3. Database Layer (database/)

  • PostgreSQL as primary database
  • Redis for caching and session management
  • Async operations using asyncpg
  • Connection pooling for optimal performance
  • Migration system from JSON to PostgreSQL

4. Web Dashboard (dashboard/)

  • FastAPI backend with RESTful API
  • React frontend with TypeScript
  • Discord OAuth2 authentication
  • Real-time statistics and configuration

5. AI Integration (aimod_helpers/)

  • LiteLLM client supporting multiple AI providers
  • Media processing for image and attachment analysis
  • System prompt management with context awareness
  • Configurable AI models per guild

🔧 Component Details

Bot Core Architecture

The main bot (bot.py) implements several key patterns:

Auto-Sharding:

class MyBot(commands.AutoShardedBot):
    async def is_owner(self, user: discord.User | discord.Member):
        return user.id in OWNER_IDS

Error Handling:

  • Global exception handler with DM notifications
  • Traceback logging and error context preservation
  • Graceful degradation for non-critical failures

Prefix Management:

  • TTL cache for prefix lookups
  • Database-backed prefix storage
  • Dynamic prefix updates via Redis pub/sub

Cog System Design

Each cog follows a consistent pattern:

class ExampleCog(commands.Cog, name="Example"):
    def __init__(self, bot: commands.Bot):
        self.bot = bot
        # Initialize resources
    
    async def cog_load(self):
        # Async initialization
        pass
    
    async def cog_unload(self):
        # Cleanup resources
        pass

Key Design Principles:

  • Single Responsibility: Each cog handles one domain
  • Async/Await: All operations are asynchronous
  • Error Isolation: Cog failures don't crash the bot
  • Resource Management: Proper cleanup on unload

Database Architecture

Connection Management:

# Connection pooling
async def get_pool():
    return await asyncpg.create_pool(
        dsn=DATABASE_URL,
        min_size=5,
        max_size=20
    )

Model Layer:

  • Pydantic models for data validation
  • Type hints for all database operations
  • Async context managers for transactions

Caching Strategy:

  • Redis for frequently accessed data
  • TTL-based cache invalidation
  • Write-through caching for configuration

AI Integration Architecture

LiteLLM Integration:

def get_litellm_client():
    return LiteLLM(
        api_base="https://openrouter.ai/api/v1",
        api_key=os.getenv("OPENROUTER_API_KEY")
    )

Message Processing Flow:

  1. Message received → Event listener
  2. Guild configuration check → Database query
  3. Channel exclusion check → Config validation
  4. Content preprocessing → Media analysis
  5. AI analysis → LiteLLM API call
  6. Action determination → Rule evaluation
  7. Moderation action → Discord API
  8. Logging → Database storage

🔄 Data Flow

Message Moderation Flow

Discord Message
       ↓
   Event Listener
       ↓
   Guild Config Check ──→ Database
       ↓
   Channel Exclusion ──→ Config Cache
       ↓
   Global Ban Check ──→ Database
       ↓
   Media Processing ──→ OpenCV/PIL
       ↓
   AI Analysis ──→ LiteLLM API
       ↓
   Action Decision ──→ Rule Engine
       ↓
   Moderation Action ──→ Discord API
       ↓
   Logging ──→ Database + Webhooks

Configuration Management Flow

Dashboard Request
       ↓
   FastAPI Endpoint
       ↓
   Authentication ──→ Discord OAuth2
       ↓
   Permission Check ──→ Guild Permissions
       ↓
   Database Update ──→ PostgreSQL
       ↓
   Cache Invalidation ──→ Redis
       ↓
   Bot Notification ──→ Redis Pub/Sub

🚀 Performance Optimizations

Caching Strategy

  • Guild Configuration: 5-minute TTL cache
  • User Permissions: 1-minute TTL cache
  • AI Decisions: In-memory deque for recent decisions
  • Database Queries: Connection pooling and prepared statements

Async Operations

  • Non-blocking I/O: All database and API calls are async
  • Concurrent Processing: Multiple messages processed simultaneously
  • Background Tasks: Cleanup and maintenance tasks run separately

Resource Management

  • Memory Monitoring: Automatic cleanup of large objects
  • Connection Limits: Bounded connection pools
  • Rate Limiting: Built-in Discord API rate limit handling

🔒 Security Architecture

Authentication & Authorization

  • Discord OAuth2 for dashboard access
  • JWT tokens for API authentication
  • Role-based permissions for guild management
  • API key encryption for sensitive data

Data Protection

  • Encrypted storage for API keys
  • Secure communication via HTTPS/WSS
  • Input validation on all user inputs
  • SQL injection prevention via parameterized queries

Monitoring & Auditing

  • Comprehensive logging of all actions
  • Error tracking with notifications
  • Performance monitoring with metrics
  • Security event logging for suspicious activity

📊 Scalability Considerations

Horizontal Scaling

  • Auto-sharding for large bot deployments
  • Database clustering support
  • Load balancing for dashboard
  • Microservice architecture potential

Vertical Scaling

  • Efficient memory usage with object pooling
  • CPU optimization with async processing
  • Database indexing for query performance
  • Caching layers to reduce database load

Next: AI Moderation System - Deep dive into the AI-powered moderation engine