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
bot.py
)
1. Bot Core (- 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 moderationconfig_cog.py
- Guild configuration managementhuman_moderation_cog.py
- Manual moderation tools
Security & Protection:
botdetect.py
- Bot detection and automated responsesraiddefence.py
- Raid protection and mass action detectionban_appeal_cog.py
- Appeal system for moderation actions
Analytics & Logging:
logging_cog.py
- Comprehensive event loggingstatistics.py
- Usage analytics and performance metricsmod_log_cog.py
- Moderation action logging
Utility & Management:
help.py
- Dynamic help systemping.py
- Bot status and latency monitoringupdate.py
- Bot update and maintenance tools
database/
)
3. Database Layer (- 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
dashboard/
)
4. Web Dashboard (- FastAPI backend with RESTful API
- React frontend with TypeScript
- Discord OAuth2 authentication
- Real-time statistics and configuration
aimod_helpers/
)
5. AI Integration (- 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:
- Message received → Event listener
- Guild configuration check → Database query
- Channel exclusion check → Config validation
- Content preprocessing → Media analysis
- AI analysis → LiteLLM API call
- Action determination → Rule evaluation
- Moderation action → Discord API
- 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