How azizu1012/gemini-bot-discord works
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: repository.py repository.py · run_bot.py run_bot.py · message_handler.py message_handler.py · gemini_pipeline.py gemini_pipeline.py
Components 25
Entry & Runtime
Process entrypoints and deployment/runtime launch modes.
- main.py · Thin entrypoint that delegates startup to the main runner.
main.py - run_bot.py · Primary process launcher with bot-only, bot+server, and validation modes.
run_bot.py - run_bot.sh · Shell wrapper for Linux/PM2 deployment and environment setup.
run_bot.sh - ecosystem.config.js · 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 · Bot startup, lifecycle management, and slash-command wiring.
src/handlers/bot_core.py - message_handler.py · Builds context, detects intent, and routes messages into chat, tools, or special handling.
src/handlers/message_handler.py - bot_server.py · 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 · Two-stage reasoning and synthesis pipeline with fallback behavior.
src/core/gemini_pipeline.py - gemini_api_manager.py · Manages Gemini clients, keys, pooling, and throttling.
src/core/gemini_api_manager.py - gemini_rate_limiter.py · Protects the model access layer from overuse and provider limits.
src/core/gemini_rate_limiter.py - api_router.py · Selects or proxies AI endpoints across configured model aliases.
src/core/api_router.py - prompt_loader.py · Caches instruction text loaded from the instructions directory.
src/core/prompt_loader.py - tools.py · 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 · SQLite persistence layer with schema bootstrap and recovery behavior.
src/database/repository.py - note_manager.py · Scopes notes, promotes reusable knowledge, and filters abusive content.
src/managers/note_manager.py - cache_manager.py · Centralized cache/state handling for repeated runtime lookups.
src/managers/cache_manager.py - file_index_service.py · Chunks uploads, indexes them with the LLM, and validates extracted knowledge.
src/services/file_index_service.py - file_parser.py · Parses uploaded files into content suitable for indexing.
src/services/file_parser.py - memory_service.py · Coordinates memory retrieval and persistence across the bot runtime.
src/services/memory_service.py
Operations
Preflight, logging, health, and deployment hardening.
- health_checker.py · Checks upstream service health and reports failures for operators.
src/services/health_checker.py - preflight.py · Validates dependencies and writable runtime paths before launch.
src/core/preflight.py - logger.py · Central logging setup for runtime and deployment diagnostics.
src/core/logger.py
Domain Extensions
Voice controls and premium/admin policy surfaces.
- voice_lock.py · Voice-room locking and movement controls for Discord server coordination.
src/voice/voice_lock.py - premium_manager.py · Tracks premium state and related command-time policy decisions.
src/managers/premium_manager.py - cleanup_manager.py · Handles periodic cleanup and operational housekeeping.
src/managers/cleanup_manager.py
Connections 28
- 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.