DiscordianAI is an advanced Discord bot with sophisticated AI orchestration, conversation consistency, and production-grade thread-safe architecture. It intelligently uses multiple AI services to provide the best responses with three operation modes:
- 🧠 Smart Hybrid Mode - Automatically chooses between OpenAI's GPT models and Perplexity's web search with conversation consistency
- 🤖 OpenAI Only - Uses OpenAI for all responses
- 🔍 Perplexity Only - Uses web search for all responses with proper citations
- Follow-up Detection: Automatically detects when users ask follow-up questions
- Context Preservation: Routes follow-ups to the same AI service for conversational continuity
- Metadata Tracking: Stores AI service information with each response for intelligent routing
- Semantic Analysis: Advanced pattern matching to determine optimal AI service
- Entity Detection: Recognizes proper nouns, companies, and specific topics for routing
- Time Sensitivity: Automatically detects time-sensitive queries for web search
- Configurable Intelligence: Fine-tune routing behavior with advanced configuration options
- 🌐 Clickable Citations: Perplexity responses with citations display as beautiful Discord embeds with clickable
[[1]](url)hyperlinks - 📱 Smart Embed Usage: Automatically creates embeds for citation-rich responses, plain text for conversations
- 🔧 Modern API Support: Supports latest Perplexity API format with
citationsandsearch_resultsmetadata fields - ✂️ Smart Message Splitting: Intelligently splits long responses while preserving embed functionality and content integrity
- 🔒 Thread-Safe Operations: Handles concurrent users safely without data corruption
- Thread Safety: Per-user locking prevents race conditions in concurrent scenarios
- Memory Management: Automatic cleanup of inactive user data to prevent memory leaks
- Error Recovery: Comprehensive error handling with graceful fallbacks
- Performance Optimization: Pre-compiled regex patterns, optimized data structures, and HTTP/2 connection pooling
- Centralized Configuration: Single source of truth for all patterns and settings
- HTTP/2 Support: Multiplexed connections for better throughput
- API-Specific Tuning: Optimized connection pools for OpenAI (50 max) and Perplexity (30 max)
- Shared Connections: Multiple users share connection pools efficiently
- Rate Limit Compliance: Respects OpenAI (500 RPM) and Perplexity API limits
- Memory Efficient: Supports 10k+ users with <100MB conversation memory
- Python: 3.10+ (3.10, 3.11, 3.12 supported)
- Discord Bot Token: From Discord Developer Portal
- OpenAI API Key: From OpenAI Platform (optional)
- Perplexity API Key: From Perplexity AI (optional)
- OpenAI API Key: Get from OpenAI Platform
- Perplexity API Key (for web search): Get from Perplexity
You can use one or both keys depending on your preferred operation mode
- Strict error checking: The control script exits on any error and recognizes failures in pipelines.
- Customizable configurations: The control script allows for different modes of operation and configurations.
- Error Handling: The control script logs errors and exits on failure.
- Process Handling: The control script terminates existing instances of the bot before starting a new one.
- Logging: The app logs events with timestamps for better tracking.
- Rate Limiting: Implements rate limiting to prevent users from spamming commands.
- Conversation History: Maintains conversation history for each user to provide context-aware responses.
- Activity Status: Configurable activity status to display what the bot is doing.
- Direct Message Handling: Processes direct messages separately from channel messages.
- Channel Message Handling: Processes messages in specific channels where the bot is mentioned.
- Smart Message Splitting: Intelligently splits long messages while preserving content integrity and respecting Discord's limits.
- Global Exception Handling: Catches and logs unhandled exceptions to prevent crashes.
- Shard Support: Supports sharding for better scalability and performance.
- Clone the repository to your local machine.
- Install the required packages using pip:
pip install -r requirements.txt - Rename
config.ini.exampletoconfig.iniand fill in the required configuration details.
The config.ini file supports all three operation modes with comprehensive configuration options:
The bot automatically analyzes each message and chooses the best AI service:
- Time-sensitive questions → Perplexity (web search)
- Creative/coding requests → OpenAI
- Factual queries → Perplexity
- Conversations → OpenAI
OPENAI_API_KEY=your_openai_key_here
PERPLEXITY_API_KEY=your_perplexity_key_hereUses OpenAI for all responses:
OPENAI_API_KEY=your_openai_key_here
PERPLEXITY_API_KEY=Uses web search for all responses with citations:
OPENAI_API_KEY=
PERPLEXITY_API_KEY=your_perplexity_key_hereDISCORD_TOKEN: Your Discord bot tokenALLOWED_CHANNELS: Comma-separated channel names where bot respondsBOT_PRESENCE: Bot status (online, idle, dnd, invisible)ACTIVITY_TYPE: Activity type (playing, streaming, listening, watching, competing)ACTIVITY_STATUS: Custom activity message
OPENAI_API_KEY: OpenAI API key for GPT models (leave blank to disable)OPENAI_API_URL: OpenAI API endpoint (default: https://api.openai.com/v1/)GPT_MODEL: OpenAI model (gpt-5-mini, gpt-5, gpt-5-nano, gpt-5-chat)PERPLEXITY_API_KEY: Perplexity API key for web search (leave blank to disable)PERPLEXITY_API_URL: Perplexity API endpoint (default: https://api.perplexity.ai)PERPLEXITY_MODEL: Perplexity model (sonar-pro, sonar)
INPUT_TOKENS: Maximum input context size (default: 120000)OUTPUT_TOKENS: Maximum response tokens (default: 8000)CONTEXT_WINDOW: Context window size (default: 128000)RATE_LIMIT: Messages per time period (default: 10)RATE_LIMIT_PER: Time period in seconds (default: 60)
OPENAI_MAX_CONNECTIONS: Max concurrent connections to OpenAI API (default: 50)OPENAI_MAX_KEEPALIVE: Max keepalive connections for OpenAI (default: 10)PERPLEXITY_MAX_CONNECTIONS: Max concurrent connections to Perplexity API (default: 30)PERPLEXITY_MAX_KEEPALIVE: Max keepalive connections for Perplexity (default: 5)
SYSTEM_MESSAGE: AI personality/instructionsLOG_FILE: Log file path (default: bot.log)LOG_LEVEL: Logging verbosity (INFO, DEBUG, etc.)
The bot automatically knows what to do - no manual commands needed!
Automatically uses web search for:
- "What's happening in AI today?" ← Time-sensitive
- "How's Tesla stock doing?" ← Financial data
- "Tell me about the recent SpaceX launch" ← Current events
- "What's the weather like in Tokyo?" ← Current information
Automatically uses OpenAI for:
- "Write me a poem about robots" ← Creative
- "How do I fix this Python error?" ← Technical
- "What do you think about philosophy?" ← Conversational
- "Hello! How are you?" ← Greeting
Here is the unified config.ini example:
[Discord]
DISCORD_TOKEN=your_discord_bot_token_here
ALLOWED_CHANNELS=general,bot-testing
BOT_PRESENCE=online
ACTIVITY_TYPE=watching
ACTIVITY_STATUS=you bite my shiny metal ass!
[Default]
# Both APIs for smart hybrid mode
OPENAI_API_KEY=your_openai_api_key_here
OPENAI_API_URL=https://api.openai.com/v1/
GPT_MODEL=gpt-5-mini
PERPLEXITY_API_KEY=your_perplexity_api_key_here
PERPLEXITY_MODEL=sonar-pro
INPUT_TOKENS=120000
OUTPUT_TOKENS=8000
CONTEXT_WINDOW=128000
SYSTEM_MESSAGE=You are Bender from Futurama. You automatically know when to search for current information.
#
[Limits]
RATE_LIMIT=10
RATE_LIMIT_PER=60
[Logging]
LOG_FILE=bot.log
LOG_LEVEL=INFOTo use this bot, you will need to create a Discord bot and invite it to your server. Here are the steps to do so:
- Go to the Discord Developer Portal and create a new application.
- Click on the "Bot" tab and then click "Add Bot".
- Copy the bot token and paste it into the
DISCORD_TOKENfield in theconfig.inifile. - Under the "OAuth2" tab, select the "bot" scope and then select the permissions you want the bot to have.
- Copy the generated OAuth2 URL and paste it into your web browser. This will allow you to invite the bot to your server.
To start the bot, run the following command:
python -m src.main --conf config.ini --folder /path/to/base/folder--conf: Path to the configuration file (relative to base folder if --folder is used).--folder: (Optional) Base folder for config and logs. If provided, config and log file paths are resolved relative to this folder unless absolute.
The bot will log in to Discord and start listening for messages in the configured channels. When a message is received, the bot will send the message to the OpenAI API and wait for a response. The response will be sent back to the user who sent the message.
A global exception handler is set up to log any unhandled exceptions, ensuring robust error reporting and easier debugging.
Daemon/background mode is handled by the discordian.sh shell script, which supports -d/--daemon, -c/--config, and -f/--folder arguments. See the Daemon section below for details.
For more in-depth information about the DiscordianAI project, please refer to the following documentation files in the docs/ directory:
- Architecture : System design, components, request flow diagrams, and design patterns
- Smart AI Mode : Complete guide to intelligent multi-AI operation with smart detection
- Configuration : Detailed instructions on configuring the Discord bot and AI API settings
- Setup : Step-by-step guide on how to set up and run the Discord bot
- Python Versions : Supported Python versions and compatibility notes
- OpenAI : How the bot uses OpenAI GPT API to generate responses
- Perplexity : Web search integration with Perplexity AI and citations
- Web Scraping : URL content extraction for context-aware responses
- Message Splitting : Advanced message splitting with recursion limit protection
- Embed Limits : Discord embed size limits and handling strategies
- Connection Pooling : HTTP/2 connection pooling for API performance
- Docker : Instructions on containerizing the Discord bot
- Daemon : Running the Discord bot as a background service
- Security : API key management, rate limiting, and security best practices
- Development : Modern development workflow and linting tools
pip install -e .[dev]# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=term-missing
# Run specific test file
pytest tests/test_smart_orchestrator.pyModern Approach (Recommended):
# Format code
black .
# Lint and auto-fix
ruff check --fix .
# Run tests
pytest -qFull Quality Check:
# Check formatting
black --check .
# Check linting
ruff check .
# Run tests
pytest -q# Run all environments
tox
# Run specific environment
tox -e py310
tox -e lint
tox -e test
# Run in parallel for faster execution
tox --parallel autoAll pushes and pull requests are automatically checked with:
- Black for code formatting
- Ruff for comprehensive linting and import sorting
- Pytest for testing with coverage reporting
- GitHub Actions for automated CI/CD
discordian.sh is a bash script for launching a DiscordianAI bot with customizable configurations. It is suitable for both manual execution and running via crontab.
The script accepts the following command line arguments:
-dor--daemon: Runs the bot in daemon mode with no output to the terminal.-cor--config: Allows the use of a custom configuration file. The next argument should be the path to the configuration file.-for--folder: Allows the use of a base folder. The next argument should be the path to the base folder.
./discordian.sh -d -c /path/to/config.ini -f /path/to/base/folderThis command will run the bot in daemon mode, using the configuration file at /path/to/config.ini and the base folder at /path/to/base/folder.
- Never commit API keys to version control
- Use environment variables in production:
export DISCORD_TOKEN="your_token" export OPENAI_API_KEY="your_openai_key" export PERPLEXITY_API_KEY="your_perplexity_key"
- Restrict config file permissions:
chmod 600 config.ini - Rotate API keys regularly and monitor usage
- Use separate keys for development and production
- Keep
config.iniin.gitignore(already configured) - Use strong, unique Discord bot tokens
- Regularly review and update dependencies for security patches
- Enable pre-commit hooks to prevent accidental secret commits:
pip install pre-commit pre-commit install
- Run the bot with minimal required permissions
- Use Docker for isolation and easier updates
- Monitor logs for suspicious activity
- Set up alerts for authentication failures
- Regularly backup configuration (without secrets)
The bot implements comprehensive rate limiting and error recovery:
- Per-user rate limiting: Prevents abuse (default: 10 messages per 60 seconds)
- Exponential backoff: Automatic retry with increasing delays (1s, 2s, 4s...)
- Circuit breaker pattern: Prevents cascade failures when APIs are down
- Jitter: Random delay variation prevents thundering herd problems
- Non-retryable errors: Auth errors fail fast without retries
[Limits]
RATE_LIMIT=10 # Messages per time period
RATE_LIMIT_PER=60 # Time period in seconds- Rate limit errors (429): Retry after 30 seconds
- Timeout errors: Retry after 10 seconds with exponential backoff
- Server errors (5xx): Retry after 60 seconds
- Network errors: Retry after 15 seconds
- Auth errors (401): Fail immediately (no retry)
The bot automatically handles these scenarios and provides user-friendly error messages without exposing internal details.
Contributions are welcome! Please open an issue or pull request on the GitHub repository.
If you have any questions or concerns, please contact [email protected]
This project is licensed under the Unlicense - see the LICENSE file for details.