Skip to main content

Technical Architecture

This page is for developers who want to dive deep into how Miku works under the hood.

Directory Structure

The project is organized according to the Modular Cogs model of discord.py:

  • main.py: Initializes the bot, loads configuration, and extensions (cogs).
  • config.py: Uses dataclasses and python-dotenv to manage configurations strictly and safely.
  • client.py: Wrapper class for NVIDIA's API, handling prompt building and image data transmission.
  • memory_store.py: Handles all interactions with SQLite via aiosqlite.
  • komifilter.py: An independent module handling security logic using Regex.
  • cogs/: Contains separate features like Chat, Ban Control, Callnames, Auto Update...

Message Processing Flow

  1. Reception: on_message or command receives a message from Discord.
  2. Check: Checks if the user is blocked (Banned).
  3. Filter (Input): KomiFilter checks if the message contains malicious code or requests for information leaks.
  4. Context: Loads chat history and user nicknames from SQLite.
  5. AI Processing: Sends data to the NVIDIA NIM API.
  6. Filter (Output): KomiFilter checks the AI's response to ensure no system information is leaked.
  7. Storage: Saves the new message to the database and updates the user's activity time.
  8. Response: Sends the processed message (e.g., math conversion) back to Discord.

Database

The project uses SQLite with 3 main tables:

  • chat_memory: Stores role, content, images_json, and user_id.
  • bot_banned_users: Stores the blacklist and reasons for banning.
  • user_call_preferences: Stores two-way nicknames.

The use of aiosqlite ensures that database I/O operations do not block the bot's Event Loop, keeping the bot responsive even when the database is busy.

Automation

  • Auto Update: The autoupdate.py cog uses subprocess to run git pull and pip install, then uses os.execv to restart the Python process.
  • Scheduled Restart: Automatically clears cache (__pycache__) and restarts the bot periodically to ensure long-term stability.