9591d81f7a438abb5f29cb8c49ff1fcefac01e02
Discord GLHF 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
All configuration is done through environment variables. Create a .env file:
# 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
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.
Languages
Python
97%
HTML
2.4%
Shell
0.4%
JavaScript
0.2%