# azizu1012/gemini-bot-discord architecture

> Architecture diagram of the GitHub repository azizu1012/gemini-bot-discord, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-24). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/azizu1012/gemini-bot-discord
- Repository: https://github.com/azizu1012/gemini-bot-discord

## Overview

1. **What this repo is**
   - This is a production-oriented **Discord bot** centered on a **two-stage Gemini pipeline**: first a reasoning/tool loop, then a final synthesis pass.
   - The bot is not just chat: it includes long-term memory, file ingestion/indexing, admin moderation, voice-room controls, and operational hardening for server deployment.

2. **Entrypoints and process model**
   - `main.py` is a thin entrypoint that delegates to `run_bot.py`.
   - `run_bot.py` is the primary launcher and supports multiple modes: bot-only, bot + server, and preflight validation.
   - `run_bot.sh` and `ecosystem.config.js` are the Linux/PM2 deployment layer, with support for fixed `cwd`, fresh starts, and environment injection.

3. **Top-level runtime boundary**
   - The code is organized into a clear runtime stack:
     - **Handlers** manage Discord-facing events and commands.
     - **Core** contains AI pipeline, model routing, config, logging, prompts, and preflight checks.
     - **Services** handle file indexing, parsing, memory, and health checks.
     - **Database** is a SQLite repository layer.
     - **Tools** expose model-callable capabilities.
     - **Managers** implement domain policies like cache, notes, premium state, and cleanup.
   - This separation is important: Discord I/O is kept apart from AI orchestration and persistence.

4. **Discord event handling**
   - `src/handlers/bot_core.py` owns bot lifecycle and slash-command wiring.
   - `src/handlers/message_handler.py` is the main message router: it builds context, detects intent, and decides whether a message should enter the Gemini pipeline, tool loop, or special handling path.
   - `src/handlers/bot_server.py` likely hosts the optional server mode alongside the bot process.

5. **AI orchestration pipeline**
   - `src/core/gemini_pipeline.py` is the heart of response generation.
   - The runtime flow is:
     1. incoming message/context preparation
     2. reasoning loop with tools
     3. final synthesis into user-facing output
     4. fallback path if the primary pipeline fails
   - This makes the architecture a **multi-pass LLM system**, not a single prompt/response call.

6. **Model access and rate control**
   - `src/core/gemini_api_manager.py` manages Gemini API keys, client pooling, and throttling.
   - `src/core/gemini_rate_limiter.py` adds protection against overuse and provider limits.
   - `src/core/api_router.py` and `src/core/api_proxy.py` suggest a routing layer for selecting or proxying AI endpoints.
   - Operationally, the repo supports multiple model aliases through environment config, allowing reasoning and final synthesis to use different models.

7. **Tool boundary**
   - `src/tools/tools.py` is the tool registry/dispatcher for model-initiated actions.
   - Tools currently include search, weather, calculator, note storage/retrieval, and image recognition.
   - This is a strong architectural boundary: the model can request actions, but actual side effects and external calls are centralized in one tool layer.

8. **Memory and persistence**
   - `src/database/repository.py` is the SQLite persistence layer, with fresh schema bootstrap and recovery behavior for stale or broken schemas.
   - `src/managers/note_manager.py` implements the memory policy:
     - most notes are user-scoped
     - potentially reusable knowledge can be promoted to global scope
     - abuse-like content is filtered out before promotion
   - The memory model is therefore **DB-first with scoped knowledge**, not a generic vector-store-only design.

9. **File ingestion and knowledge extraction**
   - `src/services/file_index_service.py` and `src/services/file_parser.py` handle uploaded files.
   - The pipeline described in the README is: chunk file content → LLM-based indexing → validation.
   - This creates a separate ingestion path from normal chat, so attachments become structured knowledge rather than just raw context.

10. **Prompt and instruction management**
   - Prompts are externalized under `src/instructions/`.
   - `src/core/prompt_loader.py` provides cached prompt loading so prompt text can be edited without changing code.
   - The repo uses distinct prompts for system identity, lite reasoning, fallback synthesis, retrieval, and file-index validation, which reinforces the multi-stage AI architecture.

11. **Operational resilience**
   - `src/core/preflight.py` validates dependencies and writable runtime paths before startup.
   - `src/core/logger.py` centralizes logging.
   - Runtime paths are normalized to `PROJECT_ROOT`, and required folders are created before use.
   - This matters architecturally because the bot is designed to survive deployment variability on Linux/PM2 and avoid cwd-dependent failures.

12. **Search/cache behavior**
   - The README describes a hardened web search path with canonical query keys, TTL-based cache, inflight deduplication, cooldowns for failures, and deep-read retries.
   - That means external retrieval is treated as an unreliable, expensive subsystem with explicit caching and backoff boundaries.

13. **Domain-specific admin features**
   - Slash commands support chat resets, premium state, sending messages to specific users, reviewing global notes, demoting global notes, and donor QR delivery.
   - `/health_check` ties into `src/services/health_checker.py`, which watches an OpenAI custom endpoint and can report failures to admins.
   - These admin flows sit above the core AI loop and give operators direct control over memory and service health.

14. **Voice and room management**
   - `src/voice/voice_lock.py` suggests a separate voice-room control subsystem.
   - Commands like lock/unlock/move/set-room/private-room management indicate this is not purely text chat; it also acts as a Discord server moderation/coordination bot.

15. **Assets and secure artifacts**
   - `assets/encrypted/` stores encrypted donation QR assets, with the encryption key supplied via env.
   - This is a small but important boundary: sensitive/static assets are committed only in encrypted form, while the decryption key stays outside the repo.

16. **How to read the architecture diagram**
   - A good diagram would show:
     - Discord events entering `handlers`
     - context and memory retrieval from `database` and `managers`
     - optional file ingestion through `services/file_index_service`
     - tool invocation through `tools`
     - model access through `core/gemini_*`
     - persistence back to SQLite
     - ops controls through launcher/preflight/PM2 and health checks
   - The key idea is that the bot is a **stateful, tool-using LLM system with explicit operational controls**, not a stateless command bot.

Main entry points: [`src/database/repository.py`](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/database/repository.py) (repository.py), [`run_bot.py`](https://github.com/azizu1012/gemini-bot-discord/blob/main/run_bot.py) (run_bot.py), [`src/handlers/message_handler.py`](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/message_handler.py) (message_handler.py), [`src/core/gemini_pipeline.py`](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_pipeline.py) (gemini_pipeline.py)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_g_entry["Entry & Runtime"]
  node_main_py["main.py<br/>entrypoint<br/>[main.py]"]
  node_run_bot_py["run_bot.py<br/>launcher<br/>[run_bot.py]"]
  node_run_bot_sh["run_bot.sh<br/>deploy script<br/>[run_bot.sh]"]
  node_pm2_cfg["ecosystem.config.js<br/>pm2 config"]
end

subgraph group_g_discord["Discord Surface"]
  node_bot_core["bot_core.py<br/>discord lifecycle<br/>[bot_core.py]"]
  node_message_handler["message_handler.py<br/>message router<br/>[message_handler.py]"]
  node_bot_server["bot_server.py<br/>server mode<br/>[bot_server.py]"]
end

subgraph group_g_ai["AI Orchestration"]
  node_gemini_pipeline["gemini_pipeline.py<br/>llm pipeline<br/>[gemini_pipeline.py]"]
  node_api_manager["gemini_api_manager.py<br/>api manager"]
  node_rate_limiter["gemini_rate_limiter.py<br/>rate control"]
  node_api_router["api_router.py<br/>routing layer<br/>[api_router.py]"]
  node_prompt_loader["prompt_loader.py<br/>prompt loader<br/>[prompt_loader.py]"]
  node_tools["tools.py<br/>tool registry<br/>[tools.py]"]
end

subgraph group_g_data["Data & Memory"]
  node_repository[("repository.py<br/>sqlite repo<br/>[repository.py]")]
  node_note_manager["note_manager.py<br/>memory policy<br/>[note_manager.py]"]
  node_cache_manager["cache_manager.py<br/>cache policy<br/>[cache_manager.py]"]
  node_file_index_service["file_index_service.py<br/>ingestion service"]
  node_file_parser["file_parser.py<br/>[file_parser.py]"]
  node_memory_service["memory_service.py<br/>memory service<br/>[memory_service.py]"]
end

subgraph group_g_ops["Operations"]
  node_health_checker["health_checker.py<br/>health monitor<br/>[health_checker.py]"]
  node_preflight["preflight.py<br/>startup checks<br/>[preflight.py]"]
  node_logger["logger.py<br/>logging<br/>[logger.py]"]
end

subgraph group_g_domain["Domain Extensions"]
  node_voice_lock["voice_lock.py<br/>voice control<br/>[voice_lock.py]"]
  node_premium_manager["premium_manager.py<br/>policy state<br/>[premium_manager.py]"]
  node_cleanup_manager["cleanup_manager.py<br/>maintenance<br/>[cleanup_manager.py]"]
end

node_main_py -->|"delegates to"| node_run_bot_py
node_run_bot_sh -->|"executes"| node_run_bot_py
node_pm2_cfg -->|"processes"| node_run_bot_py
node_run_bot_py -->|"checks"| node_preflight
node_run_bot_py -->|"starts"| node_bot_core
node_run_bot_py -->|"optionally starts"| node_bot_server
node_bot_core -->|"routes messages"| node_message_handler
node_bot_core -->|"registers controls"| node_voice_lock
node_message_handler -->|"loads context"| node_memory_service
node_message_handler -->|"invokes"| node_gemini_pipeline
node_message_handler -->|"allows tools"| node_tools
node_message_handler -->|"ingests files"| node_file_index_service
node_gemini_pipeline -->|"loads prompts"| node_prompt_loader
node_gemini_pipeline -->|"selects endpoint"| node_api_router
node_api_router -->|"uses clients"| node_api_manager
node_api_manager -->|"throttles"| node_rate_limiter
node_gemini_pipeline -->|"tool loop"| node_tools
node_tools -->|"reads/writes"| node_repository
node_memory_service -->|"persists"| node_repository
node_note_manager -->|"stores notes"| node_repository
node_cache_manager -->|"backed by"| node_repository
node_file_index_service -->|"parses"| node_file_parser
node_file_index_service -->|"validates with LLM"| node_gemini_pipeline
node_health_checker -->|"reports status"| node_bot_core
node_preflight -->|"logs"| node_logger
node_voice_lock -->|"stores state"| node_repository
node_premium_manager -->|"reads state"| node_repository
node_cleanup_manager -->|"cleans state"| node_repository

click node_main_py "https://github.com/azizu1012/gemini-bot-discord/blob/main/main.py"
click node_run_bot_py "https://github.com/azizu1012/gemini-bot-discord/blob/main/run_bot.py"
click node_run_bot_sh "https://github.com/azizu1012/gemini-bot-discord/blob/main/run_bot.sh"
click node_pm2_cfg "https://github.com/azizu1012/gemini-bot-discord/blob/main/ecosystem.config.js"
click node_bot_core "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/bot_core.py"
click node_message_handler "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/message_handler.py"
click node_bot_server "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/bot_server.py"
click node_gemini_pipeline "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_pipeline.py"
click node_api_manager "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_api_manager.py"
click node_rate_limiter "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_rate_limiter.py"
click node_api_router "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/api_router.py"
click node_prompt_loader "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/prompt_loader.py"
click node_repository "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/database/repository.py"
click node_note_manager "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/note_manager.py"
click node_cache_manager "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/cache_manager.py"
click node_file_index_service "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/file_index_service.py"
click node_file_parser "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/file_parser.py"
click node_memory_service "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/memory_service.py"
click node_health_checker "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/health_checker.py"
click node_preflight "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/preflight.py"
click node_logger "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/logger.py"
click node_voice_lock "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/voice/voice_lock.py"
click node_premium_manager "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/premium_manager.py"
click node_cleanup_manager "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/cleanup_manager.py"
click node_tools "https://github.com/azizu1012/gemini-bot-discord/blob/main/src/tools/tools.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main_py,node_run_bot_py,node_run_bot_sh,node_pm2_cfg toneBlue
class node_bot_core,node_message_handler,node_bot_server toneAmber
class node_gemini_pipeline,node_api_manager,node_rate_limiter,node_api_router,node_prompt_loader,node_tools toneMint
class node_repository,node_note_manager,node_cache_manager,node_file_index_service,node_file_parser,node_memory_service toneRose
class node_health_checker,node_preflight,node_logger toneIndigo
class node_voice_lock,node_premium_manager,node_cleanup_manager toneTeal
```

## Components

### Entry & Runtime

Process entrypoints and deployment/runtime launch modes.

- [main.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/main.py): entrypoint · Thin entrypoint that delegates startup to the main runner. · `main.py`
- [run_bot.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/run_bot.py): launcher · Primary process launcher with bot-only, bot+server, and validation modes. · `run_bot.py`
- [run_bot.sh](https://github.com/azizu1012/gemini-bot-discord/blob/main/run_bot.sh): deploy script · Shell wrapper for Linux/PM2 deployment and environment setup. · `run_bot.sh`
- [ecosystem.config.js](https://github.com/azizu1012/gemini-bot-discord/blob/main/ecosystem.config.js): pm2 config · PM2 process configuration for fixed cwd, restarts, and env injection. · `ecosystem.config.js`

### Discord Surface

Bot lifecycle, message routing, and server-side Discord interactions.

- [bot_core.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/bot_core.py): discord lifecycle · Bot startup, lifecycle management, and slash-command wiring. · `src/handlers/bot_core.py`
- [message_handler.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/message_handler.py): message router · Builds context, detects intent, and routes messages into chat, tools, or special handling. · `src/handlers/message_handler.py`
- [bot_server.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/handlers/bot_server.py): server mode · Optional server-mode host alongside the bot process. · `src/handlers/bot_server.py`

### AI Orchestration

Model access, prompt loading, tool use, routing, and response synthesis.

- [gemini_pipeline.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_pipeline.py): llm pipeline · Two-stage reasoning and synthesis pipeline with fallback behavior. · `src/core/gemini_pipeline.py`
- [gemini_api_manager.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_api_manager.py): api manager · Manages Gemini clients, keys, pooling, and throttling. · `src/core/gemini_api_manager.py`
- [gemini_rate_limiter.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/gemini_rate_limiter.py): rate control · Protects the model access layer from overuse and provider limits. · `src/core/gemini_rate_limiter.py`
- [api_router.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/api_router.py): routing layer · Selects or proxies AI endpoints across configured model aliases. · `src/core/api_router.py`
- [prompt_loader.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/prompt_loader.py): prompt loader · Caches instruction text loaded from the instructions directory. · `src/core/prompt_loader.py`
- [tools.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/tools/tools.py): tool registry · Registry and dispatcher for model-callable actions like search, weather, notes, and image recognition. · `src/tools/tools.py`

### Data & Memory

SQLite persistence, scoped notes, file ingestion, and cache/state services.

- [repository.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/database/repository.py): sqlite repo · SQLite persistence layer with schema bootstrap and recovery behavior. · `src/database/repository.py`
- [note_manager.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/note_manager.py): memory policy · Scopes notes, promotes reusable knowledge, and filters abusive content. · `src/managers/note_manager.py`
- [cache_manager.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/cache_manager.py): cache policy · Centralized cache/state handling for repeated runtime lookups. · `src/managers/cache_manager.py`
- [file_index_service.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/file_index_service.py): ingestion service · Chunks uploads, indexes them with the LLM, and validates extracted knowledge. · `src/services/file_index_service.py`
- [file_parser.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/file_parser.py): parser · Parses uploaded files into content suitable for indexing. · `src/services/file_parser.py`
- [memory_service.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/memory_service.py): memory service · Coordinates memory retrieval and persistence across the bot runtime. · `src/services/memory_service.py`

### Operations

Preflight, logging, health, and deployment hardening.

- [health_checker.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/services/health_checker.py): health monitor · Checks upstream service health and reports failures for operators. · `src/services/health_checker.py`
- [preflight.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/preflight.py): startup checks · Validates dependencies and writable runtime paths before launch. · `src/core/preflight.py`
- [logger.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/core/logger.py): logging · Central logging setup for runtime and deployment diagnostics. · `src/core/logger.py`

### Domain Extensions

Voice controls and premium/admin policy surfaces.

- [voice_lock.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/voice/voice_lock.py): voice control · Voice-room locking and movement controls for Discord server coordination. · `src/voice/voice_lock.py`
- [premium_manager.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/premium_manager.py): policy state · Tracks premium state and related command-time policy decisions. · `src/managers/premium_manager.py`
- [cleanup_manager.py](https://github.com/azizu1012/gemini-bot-discord/blob/main/src/managers/cleanup_manager.py): maintenance · Handles periodic cleanup and operational housekeeping. · `src/managers/cleanup_manager.py`

## Connections

- main.py → run_bot.py: delegates to · Thin entrypoint hands off execution to the launcher.
- run_bot.sh → run_bot.py: executes · Shell wrapper starts the Python launcher in deployment mode.
- ecosystem.config.js → run_bot.py: processes · PM2 config points at the launcher and controls runtime behavior.
- run_bot.py → preflight.py: checks · Launcher can run preflight validation before starting services.
- run_bot.py → bot_core.py: starts · Primary mode starts the Discord bot runtime.
- run_bot.py → bot_server.py: optionally starts · Launcher can bring up the server companion process.
- bot_core.py → message_handler.py: routes messages · Bot lifecycle hands incoming messages to the message router.
- bot_core.py → voice_lock.py: registers controls · Bot wiring exposes voice and room-management actions.
- message_handler.py → memory_service.py: loads context · Message handling consults memory and conversation state.
- message_handler.py → gemini_pipeline.py: invokes · Router sends eligible requests into the multi-pass Gemini pipeline.
- message_handler.py → tools.py: allows tools · Tool-eligible intents are dispatched through the centralized tool layer.
- message_handler.py → file_index_service.py: ingests files · Attachment paths are handed to the file ingestion pipeline.
- gemini_pipeline.py → prompt_loader.py: loads prompts · Pipeline retrieves stage-specific system and fallback instructions.
- gemini_pipeline.py → api_router.py: selects endpoint · Pipeline chooses the appropriate model route or proxy path.
- api_router.py → gemini_api_manager.py: uses clients · Routing ultimately relies on Gemini client and key management.
- gemini_api_manager.py → gemini_rate_limiter.py: throttles · Client access is guarded by provider-aware rate control.
- gemini_pipeline.py → tools.py: tool loop · Reasoning stage can request model-callable actions through the registry.
- tools.py → repository.py: reads/writes · Tool actions can persist or retrieve shared state in SQLite.
- memory_service.py → repository.py: persists · Memory service stores and fetches durable state in the repository.
- note_manager.py → repository.py: stores notes · Scoped note policy is implemented on top of SQLite persistence.
- cache_manager.py → repository.py: backed by · Cache/state helpers consult the persistent store when needed.
- file_index_service.py → file_parser.py: parses · Uploaded files are normalized before indexing.
- file_index_service.py → gemini_pipeline.py: validates with LLM · Indexing uses the model pipeline for reasoning and validation.
- health_checker.py → bot_core.py: reports status · Operational health checks surface issues through bot admin flows.
- preflight.py → logger.py: logs · Startup validation uses shared logging.
- voice_lock.py → repository.py: stores state · Voice-room policy can persist coordination state when needed.
- premium_manager.py → repository.py: reads state · Premium policy decisions depend on persisted user or guild state.
- cleanup_manager.py → repository.py: cleans state · Maintenance routines remove or reconcile stored data.
