9.0 KiB
discord_rcd_ai_bot
A robust, bug-free Discord bot using OpenAI-compatible APIs with comprehensive fallback systems and message queueing.
Core Features
- Full OpenAI API compatibility
- Image analysis capabilities
- Multiple fallback APIs (4 backup APIs)
- Automatic health checks every 10 minutes
- Dynamic API switching based on health status
- Message queueing with context preservation
- Complete data sanitization
- Comprehensive error handling
- Zero data loss guarantees
Image Analysis
- Support for image attachments and URLs
- Detailed image content analysis
- Grumpy personality with judgmental observations
- Automatic vision model selection
Installation
# Clone the repository
git clone [repository-url]
cd discord_glhf
# Install dependencies using uv
uv pip install -r requirements.txt
Configuration
Environment Variables
Create a .env file with required configuration:
System Prompt & Personality
The bot's personality and behavior are configured through system_prompt.yaml. This defines:
- Core personality traits and behavior
- Response patterns and style
- Tool usage guidelines
- Context handling rules
Example system_prompt.yaml structure:
sections:
- title: "Personality"
content: "Define the bot's character and tone"
- title: "Tools"
content: "Define how the bot uses available tools"
- title: "Context"
content: "Define how the bot handles conversation context"
The system prompt works in conjunction with the available tools to create natural, contextual interactions. When using !reset_memory, the bot reloads this configuration while preserving user data and preferences.
Environment Variables
# Required Environment Variables
DISCORD_TOKEN=your_discord_bot_token
GLHF_API_KEY=your_primary_api_key
BOT_OWNER_ID=your_discord_user_id
# Primary API Configuration (Required)
API_KEY=your_api_key # Your API key
API_BASE_URL=https://api.example.com/v1 # API base URL
API_MODEL=gpt-3.5-turbo # Default model to use
API_TIMEOUT=30.0 # Request timeout (optional)
API_MAX_RETRIES=3 # Number of retries (optional)
# Vision API Configuration (Required for image analysis)
VISION_API_KEY=your_vision_api_key # Separate API key for vision
VISION_API_BASE_URL=https://api.example.com/v1 # Vision API endpoint
VISION_MODEL=gpt-4-vision-preview # Vision-capable model
VISION_TIMEOUT=30.0 # Vision timeout (optional)
VISION_MAX_RETRIES=3 # Vision retries (optional)
MAX_VISION_TOKENS=1000 # Max tokens (optional)
# Fallback APIs (Optional)
FALLBACK{n}_API_KEY=your_fallback_api_key
FALLBACK{n}_BASE_URL=https://fallback.api.url/v1
FALLBACK{n}_MODEL=gpt-3.5-turbo
# Optional Configuration with Defaults
API_HEALTH_CHECK_INTERVAL=600 # 10 minutes
CIRCUIT_BREAKER_FAILURE_THRESHOLD=5
CIRCUIT_BREAKER_RECOVERY_TIMEOUT=60.0
CIRCUIT_BREAKER_HALF_OPEN_TIMEOUT=30.0
STREAM_REQUEST_TIMEOUT=60.0
MAX_STREAMING_ATTEMPTS=2
RATE_LIMIT_BACKOFF_TIME=60
Safety Features
1. Message Sanitization
- HTML escaping for all content
- Markdown sanitization
- Mention sanitization
- Control character removal
- Length validation
- Content validation
2. Database Safety
- Connection pooling with automatic cleanup
- Transaction safety with rollback
- Prepared statements for all queries
- Input validation
- UUID validation
- Data integrity checks
- Automatic cleanup of old data
3. Queue Safety
- Priority-based message ordering
- Message deduplication
- Abandoned message cleanup
- Rate limiting per user
- Queue size limits
- Error recovery
- Request timeout handling
4. API Safety
- Health checks every 10 minutes
- Automatic failover to healthy APIs
- Circuit breaker pattern
- Rate limit handling
- Error recovery
- Request timeout handling
- Response validation
5. Context Preservation
- Complete message context storage
- Thread tracking
- User context preservation
- Channel context preservation
- Metadata storage
- Reference tracking
Message Flow
-
Message Reception
- Content sanitization
- Mention resolution
- Context capture
- Priority assignment
-
Queue Processing
- Priority-based ordering
- Rate limiting
- User quota management
- Abandoned message cleanup
-
Database Operations
- Transaction safety
- Data validation
- Context storage
- Thread tracking
-
API Interaction
- Health checking
- Automatic failover
- Circuit breaking
- Error handling
-
Response Handling
- Content sanitization
- Context preservation
- Safe delivery
- Error recovery
Error Handling
-
Database Errors
- Transaction rollback
- Connection recovery
- Data validation errors
- Constraint violations
-
API Errors
- Rate limits
- Timeouts
- Invalid responses
- Network errors
-
Discord Errors
- Permission issues
- Network problems
- Rate limits
- Message delivery failures
-
Queue Errors
- Overflow handling
- Timeout recovery
- Priority conflicts
- Resource exhaustion
Monitoring
The bot includes comprehensive monitoring:
-
Health Metrics
- API status
- Queue length
- Processing times
- Error rates
-
Error Reporting
- Detailed error context
- Stack traces
- User context
- System state
-
Performance Metrics
- Response times
- Queue latency
- API latency
- Database performance
-
Tool Usage Monitoring
- Detection of tool invocations
- Tool execution tracking
- Success/failure logging
- Comprehensive logging for:
- User mentions
- Thread creation
- Emoji reactions
- Emoticon conversions
- Tool usage summaries per message
Bot Commands
Owner Commands
!reset_memory- Reset the bot's memory back to initial system prompt- Tracks number of resets per user
- Preserves user interaction history and preferences
- Shows reset count in response
Bot Tools & Capabilities
The bot uses a natural language tool system that allows it to perform actions based on conversation context:
Available Tools
-
User Mentions (@username)
- Naturally mention users in conversation
- Example: "Hey @john, what do you think?"
- Automatically resolves nicknames and usernames
-
Emoji Reactions
- Add emoji reactions to messages
- Supports Unicode emojis, custom emojis, and standard Discord emojis
- Example: "That's awesome! 👍" (will add thumbs up reaction)
- Can convert emoticons like :) to proper emojis
-
Rich Embeds
- Create formatted embed messages
- Supports titles, descriptions, and custom colors
- Example:
[Embed] Poll Results First place: X Second place: Y [/Embed]
-
Threading
- Automatically creates discussion threads
- Supports various conversation patterns:
- Comparisons: "X vs Y"
- Reviews: "This coaster is overrated"
- Topics: "Safety discussion" or "Maintenance review"
- Automatically formats thread names for consistency
Tool Usage
The bot uses these tools naturally in conversation without requiring explicit commands. It can:
- Recognize when to mention users based on context
- Add appropriate emoji reactions to messages
- Create organized threads for discussions
- Format information in embeds for better readability
All tools are used through natural language processing, making interactions feel more conversational and intuitive.
Running the Bot
# Start the bot
uv run discord_glhf.py
The bot will:
- Initialize database connections
- Start health check system
- Initialize message queue
- Connect to Discord
- Begin processing messages
Shutdown Process
The bot implements a graceful shutdown process:
- Stop accepting new messages
- Complete processing of queued messages
- Close API connections
- Close database connections
- Clean up resources
Debugging
For debugging, the bot provides:
- Detailed logging
- Error reporting to bot owner
- State inspection
- Queue inspection
- Database inspection
Best Practices
- Always use environment variables for configuration
- Never hardcode sensitive values
- Keep the database clean with regular maintenance
- Monitor error logs
- Update API configurations as needed
Requirements
- Python 3.8+
- Discord.py
- SQLite 3
- UV package manager
- Environment variables properly configured
Safety Checklist
Before deploying:
- ✓ Environment variables set
- ✓ Database initialized
- ✓ API keys validated
- ✓ Permissions configured
- ✓ Error reporting configured
- ✓ Monitoring set up
- ✓ Backup APIs configured
- ✓ Rate limits configured
- ✓ Queue limits set
- ✓ Cleanup intervals configured
Maintenance
Regular maintenance tasks:
- Database cleanup (automatic)
- Log rotation (automatic)
- API health checks (automatic)
- Queue monitoring (automatic)
- Error log review (manual)
The bot is designed to be completely bug-free and production-ready, with comprehensive safety features and error handling at every level.