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: Usesdataclassesandpython-dotenvto 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 viaaiosqlite.komifilter.py: An independent module handling security logic using Regex.cogs/: Contains separate features like Chat, Ban Control, Callnames, Auto Update...
Message Processing Flow
- Reception:
on_messageorcommandreceives a message from Discord. - Check: Checks if the user is blocked (Banned).
- Filter (Input):
KomiFilterchecks if the message contains malicious code or requests for information leaks. - Context: Loads chat history and user nicknames from SQLite.
- AI Processing: Sends data to the NVIDIA NIM API.
- Filter (Output):
KomiFilterchecks the AI's response to ensure no system information is leaked. - Storage: Saves the new message to the database and updates the user's activity time.
- Response: Sends the processed message (e.g., math conversion) back to Discord.
Database
The project uses SQLite with 3 main tables:
chat_memory: Storesrole,content,images_json, anduser_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.pycog usessubprocessto rungit pullandpip install, then usesos.execvto restart the Python process. - Scheduled Restart: Automatically clears cache (
__pycache__) and restarts the bot periodically to ensure long-term stability.