Skip to the content.

Gideon Discord Bot - Documentation

Gideon is a feature-rich Discord bot that leverages AI capabilities to provide conversation, image generation, thread management, trivia games, and more. It integrates with multiple AI services and providers (like OpenRouter, OpenAI, AI Horde, Cloudflare Workers) to deliver a comprehensive AI assistant experience within Discord.

The bot follows a modular architecture using Py-Cord’s cogs system, with state management via a singleton pattern that provides persistence across restarts using a SQLite database. It supports multiple AI models from various providers and maintains conversation context for natural interactions.

Table of Contents

  1. Overview
  2. Getting Started (User/Administrator Guide)
  3. Bot Usage (User/Administrator Guide)
  4. Architecture and Development (Developer Guide)
  5. Contributing
  6. License

1. Overview

Gideon is a versatile Discord bot designed to enhance server interactions with advanced AI capabilities. Its core functionalities include:

The bot is built on the Py-Cord library, using a modular “cog” system for organizing commands and features. State persistence (conversation history, configurations, etc.) is handled through a SQLite database, ensuring data survives bot restarts and updates.

2. Getting Started (User/Administrator Guide)

This section guides users and administrators through setting up and running the Gideon bot.

Prerequisites

Before you begin, ensure you have the following:

Installation

You can install and run Gideon using either a direct Python environment or Docker.

Method 1: Using Python

  1. Clone the Repository:
    git clone https://github.com/eoko-dev/gideon
    cd gideon
    
  2. Install Dependencies:
    pip install -r requirements.txt
    

Method 2: Using Docker

  1. Ensure Docker is Installed: Download and install Docker Desktop or Docker Engine for your operating system if you haven’t already.
  2. Clone the Repository:
    git clone https://github.com/eoko-dev/gideon
    cd gideon
    
  3. Build the Docker Image:
    docker build -t gideon-bot .
    

    This command builds the Docker image based on the Dockerfile in the repository.

Configuration

Gideon is configured primarily through environment variables, typically stored in a .env file in the root directory of the project.

  1. Create a .env file: Copy the example environment file:
    cp .env.example .env
    
  2. Edit the .env file: Open the newly created .env file in a text editor and fill in the required and optional variables.

    • Essential Variables:
      • DISCORD_TOKEN: Your Discord bot token from the Discord Developer Portal.
    • API Keys (At least one provider is needed for chat):
      • OPENROUTER_API_KEY: Your API key from OpenRouter.ai. Allows access to many models.
      • OPENAI_API_KEY: Your API key for OpenAI. Needed for OpenAI models (chat and DALL-E image generation).
      • AI_HORDE_API_KEY: Your API key for AI Horde (optional, for image generation and potentially text models).
      • CLOUDFLARE_WORKER_URL: The URL of your Cloudflare Worker for image generation (optional).
      • CLOUDFLARE_API_KEY: API key for your Cloudflare Worker (optional, if your worker requires authentication).
      • COMFYUI_URL: URL of your ComfyUI server for image generation (optional, e.g., http://127.0.0.1:8188).
    • Optional Variables:
      • SYSTEM_PROMPT: Customize the bot’s default personality. This prompt is sent to the AI model at the beginning of conversations.
      • DEFAULT_MODEL: Set the default AI model to use (e.g., openrouter/openai/gpt-4o-mini). Use the format provider/model_name. The provider part must match the keys used internally (e.g., openrouter, openai, ai_horde).
      • DATA_DIRECTORY: The directory where the SQLite database (gideon_state.db) and other data (like temporary image files) will be stored.
        • If using Python: Set this to a local path, e.g., ./data.
        • If using Docker: The default /app/data is recommended as it aligns with the Dockerfile and docker-compose.yml. You will typically map a local directory to this path when running the container to persist data.
      • INTENT_DISCOVERY: Enable or disable natural language intent detection for @mentions (default: true). Set to false to disable.
      • INTENT_DETECTION_MODEL: The AI model used for intent classification (default: anthropic/claude-3.5-haiku). Must be in provider/model format.
      • INTENT_CONFIDENCE_THRESHOLD: Minimum confidence score (0.0-1.0) required to route to specialized handlers (default: 0.7).

    Example .env:

    # Discord Bot Token
    DISCORD_TOKEN=your_discord_token_here
    
    # --- API Keys (Provide keys for the services you want to use) ---
    # OpenRouter API Key (Recommended for broad model access)
    OPENROUTER_API_KEY=your_openrouter_api_key_here
    
    # OpenAI API Key (for OpenAI models and Dall-E image generation)
    OPENAI_API_KEY=your_openai_api_key_here
    
    # AI Horde API Key (optional, for image/text generation)
    AI_HORDE_API_KEY=your_ai_horde_api_key_here
    
    # Cloudflare Worker (optional, for image generation)
    CLOUDFLARE_WORKER_URL=https://your-worker-url.workers.dev/
    CLOUDFLARE_API_KEY=your_cloudflare_api_key_here  # Optional
    
    # ComfyUI (optional, for image generation)
    COMFYUI_URL=http://127.0.0.1:8188
    
    # --- Optional Settings ---
    # System prompt for the AI assistant
    SYSTEM_PROMPT=You are Gideon, a helpful and friendly AI assistant.
    
    # Default model to use (provider/model_name format)
    DEFAULT_MODEL=openrouter/openai/gpt-4o-mini # Default uses OpenRouter
    
    # Data directory path. ONLY CHANGE THIS PATH IF YOU KNOW WHAT YOU ARE DOING! IT IS SET TO FUNCTION WITH DOCKER BY DEFAULT
    DATA_DIRECTORY=./data # Or /app/data if using Docker
    
    # --- Intent Detection Settings ---
    # Enable natural language intent detection (default: true)
    INTENT_DISCOVERY=true
    # Model for intent classification (default: anthropic/claude-3.5-haiku)
    INTENT_DETECTION_MODEL=anthropic/claude-3.5-haiku
    # Confidence threshold for intent routing (default: 0.7)
    INTENT_CONFIDENCE_THRESHOLD=0.7
    

Running the Bot

Running with Python

Navigate to the bot’s root directory in your terminal and run:

python src/__main__.py

Running with Docker

You can run the Docker image directly or use docker-compose. Using docker-compose is recommended as it handles mounting the data directory for persistence.

Using docker-compose (Recommended):

Ensure you have edited the .env file. From the bot’s root directory, run:

docker-compose up -d

This will build the image (if not already built) and start the container in detached mode. The docker-compose.yml file is configured to mount a local ./data directory to /app/data inside the container, ensuring your database and other data persist.

Running Docker Image Directly:

Ensure you have edited the .env file. From the bot’s root directory, run:

docker run -d --env-file .env -v ./data:/app/data gideon-bot

This command runs the gideon-bot image in detached mode (-d), passes environment variables from the .env file (--env-file .env), and mounts the local ./data directory to /app/data inside the container (-v ./data:/app/data).

The bot should connect to Discord and appear online in your server.

Adding to Your Server

To add the bot to your Discord server, you need to generate an invite link from the Discord Developer Portal.

  1. Go to the Discord Developer Portal.
  2. Select your bot application.
  3. Go to “OAuth2” -> “URL Generator”.
  4. Under “SCOPES”, select bot.
  5. Under “BOT PERMISSIONS”, select the necessary permissions. Recommended permissions include:
    • Read Messages/View Channels
    • Send Messages
    • Embed Links
    • Attach Files
    • Manage Messages (for clearing history, etc.)
    • Use Slash Commands
    • Manage Threads (if using native threads)
    • Read Message History
  6. Copy the generated URL and paste it into your browser. Select the server you want to add the bot to and authorize it.

3. Bot Usage (User/Administrator Guide)

Gideon uses Discord’s slash commands (/) for all interactions.

General Concepts

Help Command

AI Chat Commands

These commands are for general conversation and interaction with the AI using the configured provider and model.

Natural Language Intent Detection

Gideon features an AI-powered intent detection system that allows users to interact with the bot through natural language @mentions instead of remembering specific slash command syntax. When you @mention Gideon, the bot analyzes your message using AI to determine what you want to do and automatically routes to the appropriate feature.

How It Works

  1. Detection Process: When you @mention the bot (e.g., “@Gideon remind me to check the server tomorrow”), the message is sent to an AI model configured for intent detection.
  2. Intent Classification: The AI analyzes your message and returns:
    • Intent Type: The category of action you want (reminder, image_generation, search, conversation, or unknown)
    • Confidence Score: A value from 0.0 to 1.0 indicating how certain the AI is about the classification
    • Extracted Data: Structured parameters extracted from your natural language (e.g., reminder time, image prompt, search query)
  3. Routing Decision:
    • If confidence ≥ threshold (default 0.7), routes to the specialized handler
    • If confidence < threshold, falls back to normal conversation
  4. Execution: The appropriate handler executes with the extracted parameters

Supported Intents

1. Reminder Intent

2. Image Generation Intent

3. Search Intent

4. Conversation Intent

5. Unknown Intent

Configuration

Intent detection is configured through environment variables in your .env file:

# Enable or disable intent detection (default: true)
INTENT_DISCOVERY=true

# AI model used for intent classification (default: anthropic/claude-3.5-haiku)
INTENT_DETECTION_MODEL=anthropic/claude-3.5-haiku

# Minimum confidence threshold (0.0-1.0) to trigger intent routing (default: 0.7)
INTENT_CONFIDENCE_THRESHOLD=0.7

Configuration Details:

Implementation Details (for Developers)

The intent detection system is implemented in src/cogs/mention_commands.py:

  1. System Prompt Engineering (lines 94-151): A detailed system prompt instructs the AI on how to classify messages, what indicators to look for, and what data to extract for each intent type.

  2. Structured JSON Output (line 161): The AI returns a JSON object with intent, confidence, and data fields:
    {
      "intent": "search",
      "confidence": 0.9,
      "data": {"query": "what are the current best games on Xbox Game Pass"}
    }
    
  3. Intent Handlers: Each intent has a dedicated handler method:
    • handle_reminder_request() (existing)
    • handle_image_generation_request() (lines 287-524)
    • handle_search_request() (lines 605-773)
  4. Routing Logic (lines 947-965): After intent detection, the appropriate handler is called based on the intent type, or falls back to conversation.

  5. Conversation History: All intent-triggered actions (reminders, images, searches) are added to the channel’s conversation history, enabling contextual follow-up questions.

Thread Management Commands

Gideon leverages Discord’s native threads for focused conversations, allowing per-thread configuration.

Image Generation Commands

The /dream command provides a unified interface for generating images using different AI providers configured in the .env file.

Trivia Commands

Play interactive trivia games powered by AI-generated questions on any topic. The trivia system creates dedicated thread-based games where players simply type their answers naturally.

Game Modes:

Available Commands:

How to Play:

  1. Start a Game: Use /trivia start and select your mode, category, and difficulty
  2. Join the Thread: The bot creates a dedicated thread and posts the first question
  3. Answer Questions: Simply type your answer in the thread:
    • Type the letter (A, B, C, or D)
    • Or type the full answer text
    • The bot validates answers with fuzzy matching for spelling variations
  4. Earn Points: Score is based on:
    • Difficulty: Easy (100), Medium (200), Hard (300) base points
    • Speed Bonus: Answer faster for up to +50% bonus points
    • Streak Multiplier: Consecutive correct answers multiply your score (up to 2x)
  5. Track Progress: View your stats and compete on leaderboards
  6. Unlock Achievements: Earn badges for milestones like perfect games, speed records, and win streaks

Scoring System:

Example Achievements:

Settings Commands (Administrator)

Manage global bot configuration settings. All commands in this group require administrator permissions.

Channel Commands (Administrator)

Configure channel-specific overrides for AI behavior. All commands in this group require administrator permissions.

Admin Commands

Administrative tools and diagnostics. Most commands require administrator permissions, some require bot owner permissions.

Deprecated Configuration Commands

These commands are deprecated and will be removed in a future update. Please use the new grouped commands (/settings, /channel, /admin) instead.

Troubleshooting Common Issues

4. Architecture and Development (Developer Guide)

This section provides a deeper dive into the bot’s architecture and codebase for developers and contributors.

High-Level Architecture

The Gideon bot follows a modular design centered around Py-Cord’s Cogs, with support for multiple AI providers.

graph TD
    A[Discord API] --> B(Bot Instance);
    B --> C(Event Handlers);
    B --> D(Command Dispatcher);
    D --> E(Cogs);
    E --> F(BotStateManager);
    F --> G(DatabaseManager);
    E --> H(API Clients);
    H --> I(External AI Services<br/>OpenRouter, OpenAI, AI Horde, Cloudflare);
    E --> J(Background Tasks<br/>Auto-save, Pruning);
    G --> K(SQLite Database);
    B --> L(Configuration<br/>.env, DB Config);
    L --> F;
    L --> H;

Project Structure

gideon/
├── src/                    # Source code
│   ├── bot.py              # Main bot initialization and event handling
│   ├── config.py           # Loads configuration from environment variables
│   ├── __main__.py         # Application entry point
│   ├── cogs/               # Command modules (Cogs)
│   │   ├── __init__.py             # Makes cogs directory a Python package
│   │   ├── admin_commands.py       # Admin tools (/admin group)
│   │   ├── channel_commands.py     # Channel settings (/channel group)
│   │   ├── chat_commands.py        # AI conversation commands (/chat, /reset, etc.)
│   │   ├── config_commands.py      # Legacy commands (deprecated)
│   │   ├── diagnostic_commands.py  # Diagnostic utilities
│   │   ├── help_commands.py        # Interactive help system (/help)
│   │   ├── mention_commands.py     # Handles bot mentions
│   │   ├── settings_commands.py    # Global settings (/settings group)
│   │   ├── thread_commands.py      # Thread management (/thread group)
│   │   ├── unified_image_commands.py # Image generation (/dream, /dream_manage)
│   │   └── url_commands.py         # URL handling commands (/summarizeurl)
│   └── utils/              # Utility functions and classes
│       ├── __init__.py             # Makes utils directory a Python package
│       ├── ai_horde_client.py    # Client for AI Horde API (Image/Text)
│       ├── cloudflare_client.py  # Client for Cloudflare Worker API (Image)
│       ├── comfyui_client.py     # Client for ComfyUI API (Advanced Image Generation)
│       ├── database.py           # Handles SQLite database interactions and schema
│       ├── model_manager.py      # Manages available AI models (fetches from providers)
│       ├── openai_client.py      # Client for OpenAI API (DALL-E, Chat/Vision)
│       ├── openrouter_client.py  # Client for OpenRouter API (Chat, Vision, Web Search)
│       ├── permissions.py        # Utility functions for Discord permissions
│       └── state_manager.py      # Singleton for centralized state access and management
├── .env.example            # Template for environment variables
├── requirements.txt        # Project dependencies
├── documentation.md        # This documentation file
├── LICENSE                 # Project license
├── README.md               # Project README
├── index.md                # GitHub Pages source file
├── _config.yml             # Jekyll config (if using GitHub Pages)
├── docker-compose.yml      # Docker Compose file for easy setup
├── Dockerfile              # Defines the Docker image
└── assets/                 # Static assets (images, etc.)
    └── images/
        └── ... (screenshots and logo)

Core Components

State Management

The bot’s operational state, including conversation histories, configurations, and feature-specific data, is managed in memory by the BotStateManager and persistently stored in a SQLite database using the DatabaseManager.

API Integrations

The bot interacts with external AI services through dedicated client classes in the src/utils/ directory, typically using the aiohttp library for asynchronous HTTP requests. A key aspect is the support for multiple providers for both chat and image generation.

The ChatCommands cog determines the effective provider and model for the current context (channel/thread/global) via BotStateManager and then uses the corresponding client’s send_message_with_history method. Similarly, UnifiedImageCommands selects the appropriate image generation client based on its separate configuration.

Command System

Gideon utilizes Py-Cord’s modern application command (slash command) framework for all user interactions.

Adding New Features/Cogs

To contribute a new feature or set of commands to Gideon:

  1. Create a new Python file in the src/cogs/ directory (e.g., my_new_feature_cog.py).
  2. Define a class within this file that inherits from commands.Cog.
  3. Add commands as asynchronous methods within your new cog class. Use @discord.slash_command and @option decorators to define the command interface.
  4. Implement the logic for your commands within these methods. You can access the bot instance via self.bot and interact with the BotStateManager (self.bot.state_manager) or other utilities as needed.
  5. Include a setup function at the end of your new cog file. This function is required by Py-Cord for the bot to load your cog:
    def setup(bot):
        bot.add_cog(MyNewFeatureCog(bot))
    
  6. Ensure your new cog file is placed in the src/cogs/ directory so the bot can discover and load it on startup.

Error Handling and Logging

Security Considerations

Configuration System

Configuration in Gideon is managed through a combination of static environment variables and dynamic, persistent settings stored in the database.

5. Contributing

Contributions to the Gideon Discord Bot are welcome! If you’d like to contribute, please follow these steps:

  1. Fork the repository on GitHub: https://github.com/eoko-dev/gideon
  2. Clone your forked repository to your local machine.
  3. Create a new branch for your feature or bug fix.
  4. Make your changes, following the project’s coding style and guidelines.
  5. Write clear and concise commit messages.
  6. Test your changes thoroughly.
  7. Push your changes to your fork on GitHub.
  8. Open a Pull Request from your branch to the main branch of the original repository.
  9. Provide a clear description of your changes and why they are necessary.

Please also feel free to open issues on the GitHub repository to report bugs, suggest new features, or discuss potential improvements.

6. License

This project is licensed under the MIT License. See the LICENSE file in the repository for the full text.