{"id":36710744,"url":"https://github.com/theholyonez/discord-bot-framework","last_synced_at":"2026-02-25T19:14:40.146Z","repository":{"id":321446005,"uuid":"1085883773","full_name":"TheHolyOneZ/discord-bot-framework","owner":"TheHolyOneZ","description":"A powerful, modular Discord bot framework with dynamic extension loading, interactive help menus, and comprehensive logging. Perfect for developers who want to build feature-rich Discord bots with a clean, organized structure. + It got a Web Dashboard","archived":false,"fork":false,"pushed_at":"2026-02-10T20:47:48.000Z","size":26300,"stargazers_count":5,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-10T20:48:06.092Z","etag":null,"topics":["beginner-friendly","bot-framework","bot-template","cogs","dashboard","discord","discord-api","discord-bot","discord-bot-framework","discord-bot-template","discord-commands","discord-framework","discord-py","discordpy","extensions","help-menu","interactive","logging","modular","python"],"latest_commit_sha":null,"homepage":"https://github.com/TheHolyOneZ/discord-bot-framework?tab=coc-ov-file","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/TheHolyOneZ.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-29T16:35:07.000Z","updated_at":"2026-02-10T20:47:51.000Z","dependencies_parsed_at":null,"dependency_job_id":"52283fa0-c1ee-489a-87aa-6f5ccd59e174","html_url":"https://github.com/TheHolyOneZ/discord-bot-framework","commit_stats":null,"previous_names":["theholyonez/discord-bot-framework"],"tags_count":18,"template":false,"template_full_name":null,"purl":"pkg:github/TheHolyOneZ/discord-bot-framework","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheHolyOneZ%2Fdiscord-bot-framework","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheHolyOneZ%2Fdiscord-bot-framework/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheHolyOneZ%2Fdiscord-bot-framework/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheHolyOneZ%2Fdiscord-bot-framework/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/TheHolyOneZ","download_url":"https://codeload.github.com/TheHolyOneZ/discord-bot-framework/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/TheHolyOneZ%2Fdiscord-bot-framework/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29629625,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-19T18:02:07.722Z","status":"ssl_error","status_checked_at":"2026-02-19T18:01:46.144Z","response_time":117,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["beginner-friendly","bot-framework","bot-template","cogs","dashboard","discord","discord-api","discord-bot","discord-bot-framework","discord-bot-template","discord-commands","discord-framework","discord-py","discordpy","extensions","help-menu","interactive","logging","modular","python"],"created_at":"2026-01-12T11:47:42.701Z","updated_at":"2026-02-19T20:00:41.815Z","avatar_url":"https://github.com/TheHolyOneZ.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\r\n  \u003cimg src=\"assets/banner.png\" alt=\"Zoryx Discord Bot Framework Banner\" /\u003e\r\n\u003c/p\u003e\r\n\r\n\u003ch1 align=\"center\"\u003e🤖 Zoryx Discord Bot Framework\u003c/h1\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  \u003cstrong\u003eAdvanced • Modular • Production-Ready\u003c/strong\u003e\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  \u003ca href=\"https://www.python.org/downloads/\"\u003e\r\n    \u003cimg src=\"https://img.shields.io/badge/python-3.12+-blue.svg\" /\u003e\r\n  \u003c/a\u003e\r\n  \u003ca href=\"https://github.com/Rapptz/discord.py\"\u003e\r\n    \u003cimg src=\"https://img.shields.io/badge/discord.py-2.0+-blue.svg\" /\u003e\r\n  \u003c/a\u003e\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  A production-ready, enterprise-grade Discord bot framework featuring atomic file operations, advanced permission systems, dynamic extension loading, comprehensive monitoring, modular framework cogs, and an integrated extension marketplace.\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  **✨ NEW FEATURE (v1.7.0.0): Advanced Shard System \u0026 Backup/Restore**\r\n  \u003cbr\u003eReal-time shard health monitoring with interactive dashboards, IPC-based cross-shard communication, and full guild backup/restore with interactive dashboards — all togglable via .env!\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  **🎯 PREVIOUS: @Mention Prefix \u0026 Per-Guild Configuration (v1.6.1.0)**\r\n  \u003cbr\u003eUsers can now invoke commands using @BotName, and server admins can configure bot behavior per-guild with the new Guild Settings cog!\r\n\u003c/p\u003e\r\n\r\n\u003cp align=\"center\"\u003e\r\n  🌐 \u003ca href=\"https://zsync.eu/zdbf/\"\u003eWebsite\u003c/a\u003e\r\n\u003c/p\u003e\r\n\u003cdiv align=\"center\"\u003e\r\n\r\n## 🆕 NEW: Free Dashboard Hosting for ZDBF!\r\n\r\n**🚀 ZORYX DashHost** - Host your Zoryx Discord Bot Framework dashboard for FREE  \r\nNo PHP hosting required • Instant setup • All features included\r\n\r\n🔗 [Get Started](https://zsync.eu/zframedash/) • 📺 [Watch Tutorial](https://www.youtube.com/watch?v=TfSIV4mc_fo)\r\n\r\n---\r\n\r\n\u003c/div\u003e\r\n---\r\n\r\n## 📑 Table of Contents\r\n\r\n\u003cdetails\u003e\r\n\u003csummary\u003e\u003cstrong\u003eClick to expand\u003c/strong\u003e\u003c/summary\u003e\r\n  \r\n- [Important Notice / Data Protection](#important-notice--data-protection)\r\n- [🌟 What Makes This Framework Special](#-what-makes-this-framework-special)\r\n  - [🏗️ Enterprise-Grade Architecture](#️-enterprise-grade-architecture)\r\n  - [🎯 Developer Experience](#-developer-experience)\r\n  - [🔌 Modular Framework Cogs](#-modular-framework-cogs)\r\n  - [🛒 Integrated Extension Marketplace](#-integrated-extension-marketplace)\r\n  - [🎨 Modern User Interface](#-modern-user-interface)\r\n  - [🔒 Advanced Security](#-advanced-security)\r\n  - [📊 Comprehensive Monitoring](#-comprehensive-monitoring)\r\n  - [🔧 Developer Tools](#-developer-tools)\r\n- [🎯 Core Features](#-core-features)\r\n- [📋 Requirements](#-requirements)\r\n- [🐳 Docker Setup](#-docker-setup)\r\n- [🚀 Quick Start](#-quick-start)\r\n- [📁 Project Structure](#-project-structure)\r\n- [🎮 Built-in Commands](#-built-in-commands)\r\n  - [👥 User Commands](#-user-commands)\r\n  - [⚙️ Guild Settings Commands](#️-guild-settings-commands)\r\n  - [🛒 Marketplace Commands](#-marketplace-commands)\r\n  - [Atomic File System Commands](#atomic-file-system-commands)\r\n  - [🔌 Plugin Registry Commands](#-plugin-registry-commands)\r\n  - [📊 Framework Diagnostics Commands](#-framework-diagnostics-commands)\r\n  - [🪝 Event Hooks Commands](#-event-hooks-commands)\r\n  - [📡 Live Monitor Commands](#-live-monitor-commands)\r\n  - [🤖 AI Assistant Commands](#-ai-assistant-commands)\r\n  - [📊 Shard Monitor Commands](#-shard-monitor-commands)\r\n  - [🌐 Shard Manager Commands](#-shard-manager-commands)\r\n  - [💾 Backup \u0026 Restore Commands](#-backup--restore-commands)\r\n  - [🔧 Owner-Only Commands](#-owner-only-commands)\r\n- [🛒 Extension Marketplace](#-extension-marketplace)\r\n- [🔧 Creating Extensions](#-creating-extensions)\r\n- [⚙️ Configuration Guide](#️-configuration-guide)\r\n- [🗄️ Database System](#️-database-system)\r\n- [📊 Framework Cogs System](#-framework-cogs-system)\r\n- [📊 Shard Monitor System](#-shard-monitor-system)\r\n- [🌐 Shard Manager System](#-shard-manager-system)\r\n- [💾 Backup \u0026 Restore System](#-backup--restore-system)\r\n- [🛠 Troubleshooting](#-troubleshooting)\r\n- [📈 Performance Tips](#-performance-tips)\r\n- [📜 License](#-license)\r\n- [🤝 Contributing](#-contributing)\r\n- [💬 Support](#-support)\r\n- [📚 Additional Resources](#-additional-resources)\r\n- [🎉 Showcase](#-showcase)\r\n- [👤 Author](#-author)\r\n\r\n\u003c/details\u003e\r\n\r\n---\r\n\r\n## 🌟 What Makes This Framework Special\r\n\r\n### 🏗️ Enterprise-Grade Architecture\r\n\r\n**Atomic File Operations**\r\n- Thread-safe file handling with built-in LRU caching (300s TTL, 1000 entry limit)\r\n- Automatic lock management with cleanup threshold (500 locks)\r\n- Zero data corruption through tempfile-based atomic writes\r\n- Cache invalidation and TTL-based expiration\r\n- Cross-platform compatibility (Windows/Linux)\r\n\r\n**Advanced Database Management**\r\n- Per-guild SQLite databases with automatic connection pooling\r\n- WAL (Write-Ahead Logging) mode for concurrent access\r\n- Automatic backup system on shutdown\r\n- Orphaned connection cleanup\r\n- Global and guild-specific data separation\r\n- Command usage analytics and statistics tracking\r\n\r\n**Safe Log Rotation**\r\n- Automatic size-based rotation (10MB default)\r\n- Configurable backup count (5 backups default)\r\n- Age-based cleanup (30-day retention)\r\n- Dual-mode logging: permanent + current session\r\n- Structured logging with timestamps and levels\r\n\r\n### 🎯 Developer Experience\r\n\r\n**Hot-Reload System**\r\n- File-watching based auto-reload (30s interval)\r\n- Extension modification timestamps tracked\r\n- Zero downtime during development\r\n- Load time tracking per extension\r\n- Graceful error handling during reload\r\n\r\n**Intelligent Extension Loading**\r\n- Automatic whitespace handling (converts spaces to underscores)\r\n- Extension blacklist support\r\n- Load time tracking and diagnostics\r\n- Conflict detection through Plugin Registry\r\n- Dependency resolution system\r\n\r\n**Hybrid Command System**\r\n- Seamless prefix and slash command support\r\n- **@Mention prefix support** - Users can invoke commands with `@BotName command`\r\n- **Per-guild mention prefix configuration** - Admins control @mention availability per server\r\n- Automatic command type indicators in help menu\r\n- Slash command limit protection (100 command cap)\r\n- Graceful degradation to prefix-only mode\r\n- Visual indicators: ⚡ (hybrid), 🔸 (prefix-only), 🔹 (limit reached)\r\n- Help menu adapts to show available invocation methods\r\n\r\n**Web-Based Monitoring Dashboard**\r\n- Real-time bot status via Live Monitor cog (~12,000+ lines)\r\n- 15+ dashboard tabs: Dashboard, Commands, Plugins, Hooks, Files, Chat, Guilds, Events, System, and more\r\n- Remote extension management (load/unload/reload from browser)\r\n- Full file browser with read/write/delete operations\r\n- Chat console to send Discord messages from dashboard\r\n- Role-based access control (Owner/Helper/Visitor)\r\n- One-command dashboard deployment (`/livemonitor quickstart`)\r\n- 2-second update interval for near real-time data\r\n- Requires PHP hosting (Strato, Hostinger, any cPanel host)\r\n\r\n### 🔌 Modular Framework Cogs\r\n\r\n**Event Hooks System** (`cogs/event_hooks.py`)\r\n- Internal event system for framework lifecycle events\r\n- Priority-based callback execution\r\n- **Asynchronous queue processing:**\r\n  - 1000 event capacity with backpressure (5s wait before drop)\r\n  - Queue delay tracking for performance monitoring\r\n  - Worker auto-restart on crash (up to 10 attempts)\r\n- **Circuit Breaker Pattern:**\r\n  - Opens after 5 failures in 5 minutes\r\n  - Disables hook for 60 seconds\r\n  - Automatic recovery with manual override\r\n  - Prevents cascading failures\r\n- **Hook timeout protection:**\r\n  - 10-second timeout per hook execution\r\n  - Prevents blocking the entire queue\r\n  - Timeout triggers circuit breaker\r\n- **Performance monitoring:**\r\n  - Execution time tracking per hook\r\n  - Success/failure counts\r\n  - Average execution time calculations\r\n  - Queue delay metrics\r\n- **Hook management:**\r\n  - Disable/enable hooks without code changes\r\n  - Status indicators (🔴 disabled, ⚠️ circuit open)\r\n  - Manual circuit breaker reset\r\n- **Alert system:**\r\n  - Queue full notifications\r\n  - Circuit breaker triggers\r\n  - Worker crash alerts\r\n  - Configurable alert channel\r\n- Hook execution history (100 total, 20 per event)\r\n- Built-in events: bot_ready, guild_joined, guild_left, command_executed, command_error\r\n- Custom event emission support\r\n\r\n\r\n**Plugin Registry** (`cogs/plugin_registry.py`)\r\n- Automatic metadata extraction from extensions with error logging\r\n- **Dependency validation and enforcement:**\r\n  - Version comparison support (`\u003e=`, `\u003e`, `==`, `\u003c=`, `\u003c`)\r\n  - Missing dependency detection\r\n  - Version mismatch detection\r\n- **Conflict detection and prevention:**\r\n  - Bidirectional conflict checking\r\n  - Automatic conflict alerts\r\n- **Circular dependency detection:**\r\n  - Prevents infinite dependency loops\r\n  - Shows full dependency cycle path\r\n- Command and cog enumeration\r\n- Load time tracking per plugin\r\n- Auto-registration on extension load via event hooks\r\n- JSON-based registry persistence with enforcement settings\r\n- **Alert system:**\r\n  - Configurable alert channel\r\n  - Validation issue warnings\r\n  - Scan error notifications\r\n- **Status indicators:**\r\n  - ✅ Valid plugin\r\n  - ⚠️ Warnings (conflicts, scan errors)\r\n  - ❌ Missing dependencies\r\n  - 🔄 Circular dependencies\r\n- **Toggleable enforcement:**\r\n  - Enable/disable dependency checking\r\n  - Enable/disable conflict checking\r\n\r\n\r\n**Framework Diagnostics** (`cogs/framework_diagnostics.py`)\r\n- Real-time system health monitoring with three-tier status (healthy/degraded/critical)\r\n- CPU, memory, threads, open files, and connections tracking\r\n- Command/error rate metrics with automatic calculation\r\n- Event loop lag monitoring (checks every second)\r\n- Uptime and latency monitoring\r\n- Extension load time analysis\r\n- Automatic diagnostics generation every 5 minutes\r\n- Alert system with configurable channel (`!fw_alert_channel`)\r\n- Automatic alerts for:\r\n  - Critical health status (≥10% error rate)\r\n  - Degraded health status (≥5% error rate)\r\n  - Event loop blocking/lag\r\n  - Consecutive write failures (≥3 failures)\r\n- Comprehensive diagnostics saved to JSON files:\r\n  - `framework_diagnostics.json` - Full system report\r\n  - `framework_health.json` - Real-time health metrics\r\n\r\n**Slash Command Limiter** (`cogs/slash_command_limiter.py`)\r\n- **Intelligent Discord 100-command limit management with automatic conversion**\r\n- **Thread-safe singleton pattern** - Only one instance allowed per bot\r\n- **Configurable thresholds:**\r\n  - Warning threshold (default: 90/100)\r\n  - Safe limit (default: 95/100) \r\n  - Hard limit (100/100)\r\n- **Multi-layered interception system:**\r\n  - `tree.add_command()` monkey-patching for dynamic command blocking\r\n  - `Cog._inject()` interception for cog-level slash stripping\r\n  - Prevents commands from ever reaching Discord's API\r\n- **Intelligent command type detection:**\r\n  - ✅ **Skips `HybridCommand`** - Already have prefix support, no conversion needed\r\n  - ✅ **Skips `commands.Command`** - Already prefix-only\r\n  - ✅ **Skips `app_commands.Group`** - Command groups cannot be converted\r\n  - 🔄 **Converts `app_commands.Command`** - Pure slash commands to prefix equivalents\r\n- **Advanced parameter conversion system:**\r\n  - Automatic type detection from function signatures\r\n  - **Discord object conversion:**\r\n    - `discord.Member` / `discord.User` - Converts @mentions and IDs to Member objects\r\n    - `discord.Role` - Converts role mentions and IDs to Role objects\r\n    - `discord.TextChannel` / `discord.VoiceChannel` - Converts #channel mentions to Channel objects\r\n  - **Primitive type handling:**\r\n    - `int` - String to integer conversion\r\n    - `float` - String to float conversion  \r\n    - `bool` - Handles \"true\", \"yes\", \"1\", \"y\", \"on\" variations\r\n  - **Intelligent error messages:**\r\n    - Missing required parameters with usage examples\r\n    - Type conversion failures with helpful hints\r\n    - Guild context validation (DM protection)\r\n- **Production-ready MockInteraction wrapper:**\r\n  - Emulates full `discord.Interaction` object for seamless compatibility\r\n  - Handles `interaction.response.send_message()`, `interaction.followup.send()`\r\n  - Supports embeds, files, views (buttons/dropdowns), and all Discord features\r\n  - Proper attribute forwarding: `guild`, `user`, `channel`, `permissions`, `command`\r\n  - Modal support with graceful degradation message\r\n- **Comprehensive tracking and logging:**\r\n  - Blocked commands registry with timestamps and caller info\r\n  - Converted commands tracking with conversion type metadata\r\n  - Warning threshold system with automatic reset\r\n  - Debug logging to `botlogs/debug_slashlimiter.log`\r\n  - Caller tracking shows which file/line triggered blocking\r\n- **Self-protection mechanisms:**\r\n  - Limiter's own commands (`slashlimit`) exempted from blocking\r\n  - Async startup to prevent bot hang during initialization  \r\n  - Non-blocking background tasks for scanning\r\n  - Graceful degradation on conversion failures\r\n- **User-friendly status display (`/slashlimit`):**\r\n  - Visual progress bars showing command usage\r\n  - Color-coded status (green=safe, yellow=warning, red=critical)\r\n  - Lists blocked and converted commands\r\n  - Shows system status and verification state\r\n- **Integration with help system:**\r\n  - Command type indicators: ⚡ (hybrid), 🔸 (prefix-only), 🔹 (converted from slash)\r\n  - Automatic updates when commands are converted\r\n  - Real-time command count tracking\r\n\r\n**🤖 AI Assistant (`cogs/GeminiService.py`)**\r\n- **Powered by Google Gemini Pro:**\r\n  - This cog integrates the advanced capabilities of the Google Gemini to serve as an intelligent AI assistant for the Zoryx Discord Bot Framework. It provides natural language understanding and generation, making complex bot operations and data accessible through simple queries.\r\n- **Deep Contextual Awareness:**\r\n  - The AI assistant's power lies in its ability to dynamically pull real-time data and context from various core framework components, enabling it to provide highly accurate and relevant answers.\r\n  - **Seamless Integration with Framework Cogs:**\r\n    - **`PluginRegistry`:** Fetches live data on all installed extensions, their metadata, dependencies, and potential conflicts to answer questions about your bot's plugins.\r\n    - **`FrameworkDiagnostics`:** Accesses current health reports, performance metrics (CPU, memory, event loop lag), and error rates to provide on-demand diagnostic summaries.\r\n    - **`SlashCommandLimiter`:** Understands the bot's slash command usage, including which commands have been converted to prefix commands due to Discord's API limits, and why.\r\n    - **`EventHooks` \u0026 `EventHooksCreater`:** Provides insights into the internal event system, registered hooks, execution history, and user-created automations, helping you understand how the bot responds to events.\r\n  - **Direct File \u0026 Database Introspection:**\r\n    - **File Content Analysis:** Can read and summarize the content of any specified file within the bot's directory (with robust security checks to prevent path traversal), allowing the AI to explain code, configurations, or logs.\r\n    - **Database Schema Querying:** Interacts with the bot's SQLite databases to answer natural language questions about table schemas, data structure, and even specific data points (e.g., \"How many users have configured custom prefixes?\").\r\n    - **`README.md` Smart Search:** Utilizes advanced search capabilities to find and synthesize information directly from the bot's `README.md` file, making documentation queries instant and efficient.\r\n- **Key Features for Enhanced Bot Management:**\r\n  - **Natural Language Interaction:** Users can ask complex questions in plain English, eliminating the need to memorize specific commands or data structures.\r\n  - **Interactive Help Menu:** A paginated, button-driven help menu guides users through the `/ask_zdbf` command's extensive capabilities, ensuring ease of discovery and use.\r\n  - **Robust Error Handling \u0026 Timeout Prevention:** Implements immediate deferral of Discord interactions and comprehensive error handling, ensuring a smooth user experience even during lengthy AI processing times.\r\n  - **Secure Operations:** All file and data access through the AI assistant is safeguarded by the framework's atomic file system and strict path validation, ensuring data integrity and preventing unauthorized access.\r\n\r\n**⚙️ Guild Settings (`cogs/guild_settings.py`)**\r\n- **Per-Guild Configuration Management:**\r\n  - Server administrators control bot behavior independently for their server\r\n  - Settings stored in per-guild database with automatic persistence\r\n  - Graceful fallback to global configuration if no guild-specific setting exists\r\n- **@Mention Prefix Configuration:**\r\n  - Enable/disable @mention prefix (`@BotName command`) per server\r\n  - Check current status with detailed command invocation methods display\r\n  - Independent control over user experience preferences\r\n- **Comprehensive Settings Dashboard:**\r\n  - View all server configuration at a glance with `!serversettings`\r\n  - Shows custom prefix, mention prefix status, and server information\r\n  - Lists all available command invocation methods for users\r\n- **Administrator-Only Access:**\r\n  - All configuration commands require Administrator permission\r\n  - Guild context validation (cannot be used in DMs)\r\n  - Comprehensive error handling with clear feedback\r\n- **Extensible Architecture:**\r\n  - Built on modular design for easy addition of more guild settings\r\n  - Clean separation of concerns with dedicated cog\r\n  - Full audit logging for all configuration changes\r\n- **User-Friendly Interface:**\r\n  - Rich embed responses with visual indicators\r\n  - Clear success/error messages\r\n  - Status checking before changes\r\n- **Commands:**\r\n  - `!mentionprefix enable/disable/status` - Control @mention prefix\r\n  - `!serversettings` - View all server configuration\r\n\r\n**📊 Shard Monitor (`cogs/shard_monitor.py`)**\r\n- **Real-Time Shard Health Monitoring** (Bot Owner Only)\r\n  - Interactive dashboard with button navigation (Overview, Health, Latency, Events tabs)\r\n  - Per-shard metrics: latency, uptime, messages, commands, connects, disconnects\r\n  - Automatic health checks every 60 seconds with three-tier status (🟢🟡🔴)\r\n  - Configurable alert system with persistent channel configuration\r\n- **Comprehensive Health Checks:**\r\n  - Latency threshold detection (\u003e1s warning, \u003e2s critical)\r\n  - Activity monitoring (no events for 5+ minutes triggers warning)\r\n  - Consecutive failure tracking with configurable threshold\r\n  - Disconnect/reconnect tracking with downtime calculation\r\n- **Background Tasks:**\r\n  - Metrics collection every 30 seconds\r\n  - Health check evaluation every 60 seconds\r\n  - Persistent metrics saved to disk every 5 minutes\r\n- **Event Tracking:**\r\n  - `on_shard_connect`, `on_shard_disconnect`, `on_shard_resumed`, `on_shard_ready`\r\n  - Per-shard message and command counters\r\n  - Guild join/leave tracking per shard\r\n- **.env Toggleable:** `ENABLE_SHARD_MONITOR=true/false`\r\n- **Commands:**\r\n  - `!shardmonitor` - Interactive dashboard with button navigation\r\n  - `!sharddetails \u003cid\u003e` - Deep-dive into a specific shard\r\n  - `!shardhealth` - Quick health report for all shards\r\n  - `!shardalerts #channel [threshold]` - Configure alert system\r\n  - `!shardreset [shard_id]` - Reset collected metrics\r\n\r\n**🌐 Shard Manager (`cogs/shard_manager.py`)**\r\n- **Multi-Process \u0026 Multi-Server Sharding** (Bot Owner Only)\r\n  - IPC (Inter-Process Communication) system for cross-shard coordination\r\n  - Run shards across multiple processes on the same machine or different servers\r\n  - TCP-based length-prefixed protocol with authentication\r\n  - Automatic reconnection with exponential backoff (5s → 120s max)\r\n- **Cluster Architecture:**\r\n  - One primary cluster (IPC server mode) + one or more secondary clusters (IPC client mode)\r\n  - Shared secret authentication prevents unauthorized connections\r\n  - Heartbeat system with 30-second intervals for connection health\r\n  - Automatic cluster join/leave notifications\r\n- **Cross-Shard Communication:**\r\n  - Stats broadcasting between all clusters every 60 seconds\r\n  - Global guild/user/shard count aggregation\r\n  - Broadcast messaging to all connected clusters\r\n  - Safe preset query system (no arbitrary code execution)\r\n- **Security:**\r\n  - Authentication via shared secret (SHARD_IPC_SECRET)\r\n  - 1MB message size limit, nonce-based deduplication\r\n  - 10-second auth timeout for unauthenticated connections\r\n- **.env Toggleable:** `ENABLE_SHARD_MANAGER=true/false` (disabled by default)\r\n- **Commands:**\r\n  - `!clusters` - Show all connected clusters with stats and health\r\n  - `!ipcstatus` - IPC connection diagnostics\r\n  - `!broadcastmsg \u003cmessage\u003e` - Broadcast to all clusters\r\n\r\n**💾 Backup \u0026 Restore (`cogs/backup_restore.py`) — v2.1.0**\r\n- **Full Guild Configuration Snapshots** (Administrator / Bot Owner)\r\n  - Captures roles, channels, categories, permissions, emojis, stickers, server settings, bot settings\r\n  - **Member role assignments** — saves which members have which roles (requires Members Intent)\r\n  - Supports text, voice, forum, and stage channels with full permission overwrites\r\n  - Atomic file system integration for zero-corruption storage\r\n- **Interactive Dashboard (`/backup`)** with **5 tabs:**\r\n  - 📊 Overview — Storage, latest backup, server stats, cooldown timer\r\n  - 📦 Backups — Paginated list with member snapshot counts\r\n  - 🔍 Compare — Drift analysis: current state vs latest backup\r\n  - 📜 Audit Log — All backup operations tracked\r\n  - 📈 Analytics — Trends, frequency, top creators\r\n  - 🗑️ Quick Delete — Dropdown selector from dashboard with pin protection\r\n- **Selective Restore Engine:**\r\n  - Toggle components: roles, categories, channels, member roles, bot settings\r\n  - **Role Sync toggle** (off by default): full rewind adds missing + removes extra roles per member\r\n  - Creates only missing items, reapplies member role assignments\r\n  - Recreates permission overwrites with role ID mapping\r\n  - Real-time progress updates and detailed results\r\n- **Auto-Backup Scheduler** with per-guild intervals, pinning, notes, integrity verification\r\n- **13 Hybrid Commands:**\r\n  - `!backup` / `!backupcreate` / `!backuprestore` / `!backupview` / `!backupdelete` / `!backuplist`\r\n  - `!backuppin` / `!backupnote` / `!backupverify` / `!backupschedule` / `!backupdiff`\r\n  - `!backupexport` / `!backupstats` (Bot Owner only)\r\n\r\n**📡 Live Monitor (`cogs/live_monitor.py`)**\r\n\r\n- **Web-based dashboard for real-time bot monitoring and remote management**  \r\n  _(~12,000+ lines of functionality)_\r\n- **Acts as a bridge between the running Discord bot and an external PHP-powered monitoring interface**\r\n- **⚠️ IMPORTANT:** The **Credits tab and visual design** are © 2025 **TheHolyOneZ**  \r\n  These elements are **NOT covered by the MIT license** and **MUST remain visible and unmodified**\r\n\r\n\u003e 📺 **YouTube Tutorial \u0026 Showcase**  \r\n\u003e The full video tutorial is **now live** 🎉  \r\n\u003e It provides a complete walkthrough of the Live Monitor dashboard, showcases all features in action, and includes a step-by-step setup guide.  \r\n\u003e  \r\n\u003e 👉 **Watch here:**  \r\n\u003e https://www.youtube.com/watch?v=ir3AsxZOshw\r\n\r\n**Server Requirements:**\r\n- PHP 7.4+ hosting (shared hosting works fine - e.g., Strato, Hostinger, Bluehost, any cPanel host)\r\n- SQLite3 PHP extension (usually pre-installed)\r\n- HTTPS recommended for security\r\n- No database server required (uses SQLite files)\r\n\r\n**Dashboard Tabs (15 total):**\r\n| Tab | Description |\r\n|-----|-------------|\r\n| Dashboard | Real-time bot stats, latency, uptime, guild/user counts |\r\n| Commands | All prefix/slash/hybrid commands with usage stats |\r\n| Plugins \u0026 Extensions | Loaded extensions, dependencies, conflicts, versions |\r\n| Event Hooks | Hook status, circuit breakers, execution metrics |\r\n| File System | Directory statistics, cache hits/misses, file counts |\r\n| File Browser | Full file explorer with read/write/delete/rename/create |\r\n| Chat Console (EXPERIMENTAL) | Send messages to Discord channels from dashboard |\r\n| Guilds / Servers | All servers with member counts, channels, join dates |\r\n| Events | Recent command executions, errors, guild joins/leaves |\r\n| System | CPU, memory, threads, connections, platform info |\r\n| Bot Invite Helper | Generate invite links with permission calculator |\r\n| Database | Browse guild SQLite databases and tables |\r\n| Roles \u0026 Access | Manage dashboard user roles (Owner/Helper/Visitor) |\r\n| Security \u0026 Logs | Audit logs, login history, security events |\r\n| Credits | Framework attribution (required to remain visible) |\r\n\r\n\u003e **NOTE** The number of tabs, and the tabs themselves, may be greater in the latest version! Right now, there are around 18 tabs. I couldn't update the readme, though, so I made this quick note right here. Just know that there are more tabs and more features!\r\n\r\n\r\n**Generated PHP Files (quickstart creates these in `./live_monitor_website/`):**\r\n| File | Purpose |\r\n|------|---------|\r\n| `index.php` | Main dashboard interface with all tabs |\r\n| `receive.php` | Receives bot data via HTTP POST |\r\n| `get_commands.php` | Bot polls this for pending commands |\r\n| `send_command.php` | Dashboard sends commands to bot |\r\n| `lm_bootstrap.php` | Core initialization and config |\r\n| `lm_db.php` | SQLite database helper functions |\r\n| `lm_auth.php` | Authentication and session management |\r\n| `setup.php` | First-time claim wizard |\r\n| `login.php` | Discord OAuth login page |\r\n| `oauth_callback.php` | OAuth callback handler |\r\n| `logout.php` | Session logout handler |\r\n| `owner_audit.php` | Admin audit log viewer |\r\n| `owner_roles.php` | Role management panel |\r\n| `owner_db.php` | Database management panel |\r\n| `backup_dashboard.php` | Bot backup interface |\r\n\r\n**Slash Command (`/livemonitor`):**\r\n```\r\n/livemonitor action:\u003cchoice\u003e [url:\u003ctext\u003e] [interval:\u003cnumber\u003e]\r\n\r\nActions:\r\n  • Quick Start (Setup + Files) - Generate dashboard files and configure\r\n  • Status                      - Show current configuration and connection status\r\n  • Enable                      - Start sending data to dashboard\r\n  • Disable                     - Stop data transmission\r\n  • Get Files                   - Regenerate dashboard files\r\n```\r\n\r\n**Prefix Command (`!livemonitor`):**\r\n```\r\n!livemonitor \u003caction\u003e [url] [interval]\r\n  • !livemonitor status\r\n  • !livemonitor quickstart https://yoursite.com/monitor\r\n  • !livemonitor enable\r\n  • !livemonitor disable\r\n  • !livemonitor files\r\n```\r\n\r\n**Comprehensive data collection:**\r\n  - Bot metadata (username, ID, guilds, users, latency, uptime, loaded cogs/extensions)\r\n  - System resources via `psutil` (CPU%, memory MB/%, threads, open files, network connections, platform)\r\n  - Guild summaries with member counts, text channels (with NSFW status), owner info, join dates\r\n  - Command usage statistics with execution counts, last used timestamps, error tracking\r\n  - Integration status of framework cogs (EventHooks, SlashLimiter, PluginRegistry, FrameworkDiagnostics)\r\n  - Atomic File System cache stats (hits, misses, active locks, read/write counts)\r\n  - Health metrics from FrameworkDiagnostics when available\r\n  - Detailed plugin information via PluginRegistry integration\r\n  - Available extensions scan from `./extensions` directory\r\n  - Framework version info and documentation links\r\n- **Event logging system:**\r\n  - Listens to: `on_command`, `on_command_error`, `on_guild_join`, `on_guild_remove`, `on_message`, `on_app_command_completion`\r\n  - Configurable event log capacity (`_max_event_log`: 1000 entries)\r\n  - Hook execution history (`_max_hook_execution_log`: 1000 entries)\r\n  - Message activity aggregation for engagement metrics\r\n- **Remote command execution from web dashboard:**\r\n\r\n| Command | Permission | Description |\r\n|---------|------------|-------------|\r\n| `reload_extension` | Helper+ | Hot-reload an extension |\r\n| `load_extension` | Helper+ | Load a new extension |\r\n| `unload_extension` | Helper+ | Unload an extension |\r\n| `clear_cache` | Helper+ | Clear bot caches |\r\n| `write_file` | Helper+ | Write/create files |\r\n| `read_file` | Helper+ | Read file contents |\r\n| `list_dir` | Helper+ | List directory contents |\r\n| `rename_file` | Helper+ | Rename files |\r\n| `create_dir` | Helper+ | Create directories |\r\n| `delete_path` | Helper+ | Delete files/directories |\r\n| `send_chat_message` | Helper+ | Send message to Discord channel |\r\n| `shutdown_bot` | Owner | Gracefully stop the bot |\r\n| `leave_guild` | Owner | Leave a Discord server |\r\n| `backup_bot_directory` | Owner | Create bot backup archive |\r\n| `fetch_marketplace_extensions` | Permission | Browse marketplace |\r\n| `download_marketplace_extension` | Permission | Download from marketplace |\r\n\r\n- **Role-based access control:**\r\n  - **Owner** - Full access to all dashboard features including shutdown\r\n  - **Helper** - Extension management, file operations, chat console\r\n  - **Visitor** - Read-only access, view chat history\r\n  - Granular permissions: `control_core`, `control_plugins`, `control_files`, `control_chat`, `control_hooks`, `control_guilds`, `control_backup`, `control_marketplace`\r\n- **Task loop system (`send_status_loop`):**\r\n  - 2-second update interval for near real-time monitoring\r\n  - Multi-payload JSON packaging (core, commands, plugins, hooks, filesystem, etc.)\r\n  - HTTP POST to configured `receive.php` endpoint\r\n  - Command polling from `get_commands.php` endpoint\r\n  - `aiohttp` client session management with configurable timeouts\r\n  - Failure tracking (`send_failures`) with success state (`last_send_success`)\r\n  - Graceful task cancellation on `asyncio.CancelledError`\r\n  - Asset syncing (branding images) to remote server\r\n- **Configuration (`data/live_monitor_config.json`):**\r\n  - `enabled` - Toggle monitoring on/off\r\n  - `website_url` - Dashboard URL\r\n  - `secret_token` - Bot↔Server authentication token\r\n  - `setup_token` - One-time dashboard claim token\r\n  - `update_interval` - Seconds between updates (5-60)\r\n- **Thread-safe file operations:**\r\n  - `asyncio.Lock` (`_fileops_lock`) prevents race conditions\r\n  - `asyncio.to_thread` for blocking I/O operations\r\n  - Response tracking via `_fileops_response` dictionary\r\n  - Concurrent command execution with `asyncio.create_task`\r\n- **Security features:**\r\n  - Token-based API authentication (32-byte cryptographic tokens)\r\n  - Discord OAuth integration for dashboard login\r\n  - One-time setup token prevents unauthorized claiming\r\n  - Role-based command restrictions\r\n  - Audit logging for all sensitive operations\r\n  - HTTPS recommended for production\r\n  \r\n### 🛒 Integrated Extension Marketplace\r\n\r\n**Direct Extension Installation**\r\n- Browse official extensions from within Discord\r\n- Search by keywords, categories, or status\r\n- One-click installation with confirmation\r\n- Automatic file writing to `./extensions` directory\r\n- Post-install instructions with load commands\r\n\r\n**ZygnalID System**\r\n- Unique 16-character bot identifier\r\n- Automatic generation on first use\r\n- Required for extension downloads\r\n- Enables dedicated support and tracking\r\n- Stored securely in `./data/marketplace/ZygnalID.txt`\r\n\r\n**License Agreement**\r\n- Mandatory acceptance before marketplace access\r\n- Per-user tracking of acceptance\r\n- Usage restrictions enforcement\r\n- Extension-specific licensing support\r\n- Terms displayed in interactive embed\r\n\r\n**Dependency Management**\r\n- `!marketplace fixdeps` command\r\n- Automatic log parsing for `ModuleNotFoundError`\r\n- pip-based dependency installation\r\n- Success/failure reporting per package\r\n- Duplicate installation prevention\r\n\r\n**Advanced Features**\r\n- Extension categories: Working, Beta, Broken\r\n- Custom URL support for extensions\r\n- Version tracking and display\r\n- Author attribution\r\n- Extension status indicators\r\n- Pagination for large lists (5 per page)\r\n- Dropdown menus for selection\r\n- Cache system (300s TTL) for API calls\r\n- Rate limit handling with retry logic\r\n\r\n### 🎨 Modern User Interface\r\n\r\n**Interactive Help System**\r\n- Dropdown-based category navigation\r\n- Pagination for large command lists (5 per page)\r\n- Visual command type indicators\r\n- Automatic cog organization\r\n- User-specific interaction validation\r\n- Credits button with framework info\r\n- Dynamic back navigation\r\n- Real-time command count per category\r\n\r\n**Rich Embeds Everywhere**\r\n- Color-coded responses (success=green, error=red, warning=yellow)\r\n- Consistent styling across all commands\r\n- Timestamp inclusion\r\n- Footer information\r\n- Thumbnail support\r\n- Field-based organization\r\n- Progress bars for visual feedback\r\n\r\n**Auto-Delete Messages**\r\n- Configurable delete timers (5-15s)\r\n- Success message cleanup\r\n- Error message cleanup\r\n- Reduces channel clutter\r\n- User-friendly experience\r\n\r\n### 🔒 Advanced Security\r\n\r\n**Multi-Tier Permission System**\r\n1. **Bot Owner**: Full access (from BOT_OWNER_ID env variable)\r\n2. **Guild Owner**: Server management commands\r\n3. **Role-Based**: Per-command role requirements\r\n4. **Discord Permissions**: Native permission integration\r\n5. **Hardcoded Restrictions**: Owner-only command list\r\n\r\n**Interaction Security**\r\n- User-specific button/dropdown validation\r\n- Interaction author verification\r\n- Ephemeral error messages\r\n- Timeout-based view expiration (180-300s)\r\n- Session-based state management\r\n\r\n**Data Protection**\r\n- Atomic file operations prevent corruption\r\n- Database WAL mode for ACID compliance\r\n- Automatic backups before shutdown\r\n- Guild configuration snapshots with checksums\r\n- File locking mechanism\r\n- Cache invalidation on writes\r\n- Secure temporary file handling\r\n\r\n### 📊 Comprehensive Monitoring\r\n\r\n**Metrics Collection**\r\n- Real-time command tracking (LRU cache, 100 command limit)\r\n- Message processing statistics\r\n- Error rate monitoring\r\n- Uptime tracking\r\n- Top command analytics\r\n- Per-command usage counts in database\r\n\r\n**Health Monitoring**\r\n- Error rate calculation\r\n- Status determination (healthy/degraded)\r\n- Latency tracking\r\n- Extension load time analysis\r\n- Database connection monitoring\r\n- Cache performance metrics\r\n- Per-shard health checks with three-tier status (🟢🟡🔴)\r\n- Automatic shard health alerts to configurable channels\r\n\r\n**Diagnostics Dashboard**\r\n- System information (Python version, platform, architecture)\r\n- Bot statistics (guilds, users, channels)\r\n- Extension analysis (count, load times)\r\n- Command registration (prefix + slash)\r\n- Performance metrics (CPU, memory, threads)\r\n- Database health status\r\n\r\n### 🔧 Developer Tools\r\n\r\n**Atomic File Testing**\r\n- Built-in `!atomictest` command\r\n- Write/read/cache performance benchmarking\r\n- Concurrent operation testing (10 simultaneous writes)\r\n- Data integrity verification\r\n- Cache statistics display\r\n\r\n**Cache Management**\r\n- `!cachestats` command for monitoring\r\n- File cache size tracking\r\n- Lock count monitoring\r\n- Prefix cache statistics\r\n- Metrics cache info\r\n- Database connection counts\r\n\r\n**Integrity Checks**\r\n- `!integritycheck` command\r\n- File system validation\r\n- Database connection testing\r\n- Cache system verification\r\n- Extension loading checks\r\n- Shard status monitoring\r\n- Memory usage analysis\r\n\r\n**System Cleanup**\r\n- `!cleanup` command\r\n- __pycache__ directory removal\r\n- Expired prefix cache cleanup\r\n- File lock cleanup\r\n- Orphaned database connection removal\r\n- Statistics reporting\r\n\r\n---\r\n\r\n## 🎯 Core Features\r\n\r\n### System Architecture\r\n\r\n✅ **Atomic File Operations** - Thread-safe file handling with LRU caching and retry logic\r\n- Zero data corruption through tempfile-based writes\r\n- 300s TTL, 1000 entry LRU cache\r\n- Automatic lock cleanup (500 lock threshold)\r\n- 3-attempt retry with exponential backoff\r\n- Comprehensive metrics and health monitoring\r\n- Diagnostic commands: `!atomicstats`, `!atomictest`\r\n- Cache hit rate tracking and optimization\r\n- Cross-platform compatibility (Windows/Linux)\r\n\r\n\r\n✅ **SQLite Database** - Optimized with WAL mode and connection pooling  \r\n✅ **Safe Log Rotation** - Automatic management with size and age limits  \r\n✅ **Hot-Reload System** - File-watching based auto-reload (optional)  \r\n✅ **Metrics Collection** - Real-time command tracking and analytics  \r\n✅ **Framework Cogs** - Modular internal components with event system  \r\n✅ **Auto-Sharding** - Built-in support for large-scale deployments  \r\n✅ **Shard Monitor** - Real-time health, latency, and event tracking per shard  \r\n✅ **Shard Manager** - IPC-based multi-process and multi-server shard coordination  \r\n✅ **Backup \u0026 Restore** - Full guild snapshots with interactive dashboard and smart restore  \r\n\r\n### Command System\r\n\r\n✅ **Hybrid Commands** - Both prefix and slash command support  \r\n✅ **@Mention Prefix** - Invoke commands with @BotName syntax (configurable per-guild)  \r\n✅ **Permission Framework** - Multi-tier role-based access control  \r\n✅ **AI Assistant** - Gemini-powered natural language introspection  \r\n✅ **Command Autocomplete** - Dynamic suggestions for slash commands  \r\n✅ **Cooldown Management** - Built-in rate limiting  \r\n✅ **Auto-Delete Messages** - Automatic cleanup of responses  \r\n✅ **Slash Limit Protection** - Automatic prefix-only fallback  \r\n✅ **Command Type Indicators** - Visual markers in help menu  \r\n\r\n### Extension Marketplace\r\n\r\n✅ **Integrated Browser** - Browse extensions from Discord  \r\n✅ **Search \u0026 Filter** - Find extensions by keywords or category  \r\n✅ **One-Click Install** - Direct installation to bot  \r\n✅ **License Agreement** - Mandatory acceptance system  \r\n✅ **ZygnalID Support** - Unique bot identification  \r\n✅ **Dependency Auto-Fix** - Automatic missing package installation  \r\n✅ **Version Tracking** - Extension versioning support  \r\n\r\n### User Interface\r\n\r\n✅ **Interactive Help** - Dropdown navigation with pagination  \r\n✅ **Rich Embeds** - Modern Discord UI with color coding  \r\n✅ **User Validation** - Security-checked interactions  \r\n✅ **Progress Bars** - Visual feedback for operations  \r\n✅ **Category Organization** - Automatic command grouping  \r\n\r\n### Configuration\r\n\r\n✅ **Per-Guild Settings** - Custom prefixes, @mention controls, and configurations  \r\n✅ **Guild Settings Dashboard** - View all server settings at a glance  \r\n✅ **JSON Config System** - Centralized configuration  \r\n✅ **Command Permissions** - Granular role requirements  \r\n✅ **Extension Blacklist** - Selective loading control  \r\n✅ **Framework Cog Control** - Enable/disable components  \r\n\r\n### Monitoring \u0026 Analytics\r\n\r\n✅ **Command Usage Stats** - Track popular commands  \r\n✅ **Error Tracking** - Comprehensive error logging  \r\n✅ **Uptime Monitoring** - Real-time bot statistics  \r\n✅ **Performance Metrics** - Load times and query tracking  \r\n✅ **Health Monitoring** - System diagnostics and alerts  \r\n✅ **Hook History** - Event system execution tracking  \r\n✅ **Shard Monitoring** - Real-time per-shard health, latency, and event tracking  \r\n✅ **Multi-Cluster Stats** - Cross-shard stat aggregation via IPC  \r\n✅ **Backup Snapshots** - Full guild configuration backup with integrity checksums  \r\n\r\n---\r\n\r\n## 📋 Requirements\r\n\r\n**Python**: 3.8+ (Built and tested with 3.12.7)  \r\n**discord.py**: 2.0+ (Built with 2.6.3)\r\n```\r\naiofiles==24.1.0\r\naiohttp==3.12.14\r\naiosqlite==0.21.0\r\ndiscord.py==2.6.3\r\npython-dotenv==1.0.0\r\npsutil==5.9.6\r\nrich==14.0.0\r\n\r\n```\r\n\r\n---\r\n\r\n## 🐳 Docker Setup\r\n\r\n\r\n## 1. Clone the repository\r\n```\r\ngit clone https://github.com/TheHolyOneZ/discord-bot-framework.git\r\ncd discord-bot-framework\r\n```\r\n## 2. Build the Docker image\r\n###    'discord-bot-framework' here is just the name you give the image. You can call it anything.\r\n```\r\ndocker build -t discord-bot-framework .\r\n```\r\n## 3. Run the container\r\n###    '```--name mybot```' gives a name to the running container. This is not your Python script name.\r\n###    You can use this name to stop or remove the container later.\r\n```\r\ndocker run -d --name mybot discord-bot-framework\r\n```\r\n\r\n---\r\n\r\n## 🚀 Quick Start\r\n\r\n### 1. Clone Repository\r\n```bash\r\ngit clone https://github.com/TheHolyOneZ/discord-bot-framework.git\r\ncd discord-bot-framework\r\n```\r\n\r\n### 2. Install Dependencies\r\n```bash\r\npip install -r requirements.txt\r\n```\r\n\r\n### 3. Create `.env` File\r\n\r\nCreate `.env` in the root directory:\r\n```env\r\nDISCORD_TOKEN=Bot_Token\r\nBOT_OWNER_ID=Your_DiscordID\r\n\r\n\r\n# Sharding Configuration\r\nSHARD_COUNT=1\r\n\r\n# Can be commented out depending on your needs. If you want to use auto-sharding, leave (SHARD_IDS) commented out. \r\n# SHARD_IDS=0,1\r\n\r\n# Shard Monitor (real-time shard health monitoring)\r\nENABLE_SHARD_MONITOR=true\r\nSHARD_ALERT_THRESHOLD=3\r\n\r\n# Shard Manager (multi-process/multi-server IPC — disabled by default)\r\nENABLE_SHARD_MANAGER=false\r\nSHARD_IPC_MODE=server\r\nSHARD_IPC_HOST=127.0.0.1\r\nSHARD_IPC_PORT=20000\r\nSHARD_IPC_SECRET=change_me_please\r\nSHARD_CLUSTER_NAME=cluster-0\r\n\r\n# Backup \u0026 Restore (enabled by default)\r\nENABLE_BACKUP_RESTORE=true\r\nBACKUP_MAX_PER_GUILD=25\r\nBACKUP_COOLDOWN=300\r\nBACKUP_AUTO_INTERVAL=0\r\nBACKUP_RETENTION_DAYS=0\r\n```\r\n\r\n**Getting Your User ID:**\r\n1. Enable Developer Mode: User Settings → Advanced → Developer Mode\r\n2. Right-click your username → Copy ID\r\n\r\n**Getting Bot Token:**\r\n1. Go to [Discord Developer Portal](https://discord.com/developers/applications)\r\n2. Create New Application\r\n3. Go to Bot section → Reset Token → Copy token\r\n\r\n### 4. Configure Bot Intents\r\n\r\nIn the Discord Developer Portal:\r\n1. Go to your application → Bot section\r\n2. Enable these Privileged Gateway Intents:\r\n   - ✅ Presence Intent\r\n   - ✅ Server Members Intent\r\n   - ✅ Message Content Intent\r\n\r\n\u003e **Note:** Server Members Intent is required for the Backup \u0026 Restore system to capture member role assignments. Without it, backups will still work but member roles will be empty.\r\n\r\n### 5. Run the Bot\r\n```bash\r\npython main.py\r\n```\r\n\r\nYou should see a Rich console panel with bot statistics!\r\n\r\n### 6. Invite Bot to Server\r\n\r\nGenerate invite URL in Developer Portal:\r\n1. OAuth2 → URL Generator\r\n2. Select Scopes: `bot`, `applications.commands`\r\n3. Select Permissions: Administrator (or specific permissions)\r\n4. Copy generated URL and open in browser\r\n\r\n---\r\n\r\n## 📁 Project Structure\r\n```\r\ndiscord-bot-framework/\r\n│\r\n├── main.py                      # Core bot logic and built-in commands\r\n├── atomic_file_system.py        # Atomic operations and data management\r\n│\r\n├── extensions/                  # Your extension modules (auto-loaded)\r\n│   ├── Put_Cogs_Extensions_here.txt\r\n│   ├── example_logger.py        # Example extension\r\n│   └── marketplace.py           # Extension Marketplace cog\r\n│\r\n├── cogs/                        # Framework internal cogs\r\n│   ├── event_hooks.py           # Internal event system\r\n│   ├── plugin_registry.py       # Plugin metadata \u0026 dependency tracking\r\n│   ├── framework_diagnostics.py # Health monitoring\r\n│   ├── live_monitor.py          # Web dashboard \u0026 remote management\r\n│   ├── slash_command_limiter.py # Slash command protection\r\n│   ├── shard_monitor.py         # Real-time shard health monitoring\r\n│   ├── shard_manager.py         # Multi-process IPC shard management\r\n│   ├── backup_restore.py        # Backup \u0026 Restore system\r\n│   ├── SHARD_MONITOR_DOCS.md   # Shard Monitor documentation\r\n│   ├── SHARD_MANAGER_DOCS.md   # Shard Manager documentation\r\n│   └── GeminiService.py         # AI assistant powered by Google Gemini\r\n│\r\n├── data/                        # Auto-generated data directory\r\n│   ├── main.db                  # Global SQLite database\r\n│   ├── main.db-wal              # WAL file for main DB\r\n│   ├── main.db-shm              # Shared memory for main DB\r\n│   ├── [guild_id]/              # Per-guild databases\r\n│   │   ├── guild.db\r\n│   │   └── guild_backup_*.db\r\n│   ├── plugin_registry.json     # Plugin metadata cache\r\n│   ├── framework_diagnostics.json # System diagnostics\r\n│   ├── framework_health.json    # Health monitoring data\r\n│   ├── live_monitor_config.json # Live Monitor settings\r\n│   ├── shard_monitor/           # Shard monitor data\r\n│   │   ├── shard_metrics.json   # Periodic metrics snapshot\r\n│   │   └── alert_config.json    # Alert channel \u0026 threshold config\r\n│   ├── shard_manager/           # Shard manager data (reserved)\r\n│   ├── backups/                 # Backup snapshots\r\n│   │   └── [guild_id]/          # Per-guild backup data\r\n│   │       ├── index.json       # Backup index/metadata\r\n│   │       ├── audit_log.json   # Backup audit trail (last 200 entries)\r\n│   │       ├── schedule.json    # Auto-backup schedule config\r\n│   │       └── [backup_id].json # Individual snapshots (with member roles)\r\n│   └── marketplace/\r\n│       ├── ZygnalID.txt         # Unique bot identifier\r\n│       └── license_accepted.json # License acceptance tracking\r\n│\r\n├── botlogs/                     # Log files\r\n│   ├── permanent.log            # Persistent log (rotates at 10MB)\r\n│   ├── permanent.log.1-5        # Backup logs\r\n│   └── current_run.log          # Current session only\r\n│\r\n├── images/                      # Documentation images\r\n│   ├── Terminal-1.png\r\n│   ├── HelpMenu-Example.png\r\n│   └── ... (showcase images)\r\n│\r\n├── assets/                      # Live Monitor dashboard assets (optional branding)\r\n│   ├── zoryx-framework.png      # Dashboard logo\r\n│   ├── zoryx-framework.ico      # Favicon\r\n│   └── banner.png               # Banner image\r\n│\r\n├── live_monitor_website/        # Generated dashboard files (upload to PHP server)\r\n│   ├── index.php                # Main dashboard interface (~10,000+ lines)\r\n│   ├── receive.php              # Bot data reception endpoint\r\n│   ├── get_commands.php         # Command polling endpoint\r\n│   ├── send_command.php         # Command submission with role checks\r\n│   ├── lm_bootstrap.php         # Core initialization and tokens\r\n│   ├── lm_db.php                # SQLite database helpers\r\n│   ├── lm_auth.php              # Authentication and sessions\r\n│   ├── setup.php                # One-time claim wizard\r\n│   ├── login.php                # Discord OAuth login\r\n│   ├── oauth_callback.php       # OAuth callback handler\r\n│   ├── logout.php               # Session logout\r\n│   ├── owner_audit.php          # Admin audit log viewer\r\n│   ├── owner_roles.php          # Role management panel\r\n│   ├── owner_db.php             # Database admin panel\r\n│   ├── backup_dashboard.php     # Bot backup interface\r\n│   └── assets/                  # Copied branding assets\r\n│\r\n├── config.json                  # Bot configuration (auto-generated)\r\n├── .env                         # Environment variables (YOU CREATE THIS)\r\n├── .env.example                 # Environment variable reference template\r\n├── requirements.txt             # Python dependencies\r\n├── README.md                    # This file\r\n├── LICENSE                      # MIT License\r\n├── SECURITY.md                  # Security policy\r\n├── CODE_OF_CONDUCT.md           # Code of conduct\r\n└── CONTRIBUTING.md              # Contribution guidelines\r\n```\r\n\r\n---\r\n\r\n## 🎮 Built-in Commands\r\n\r\n### 👥 User Commands\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!help` / `/help` | Interactive help menu with dropdown navigation | 10s | ✅ |\r\n| `!stats` / `/stats` | Bot statistics, metrics, and framework info | 10s | ✅ |\r\n| `!extensions` / `/extensions` | List loaded user extensions and framework cogs | 10s | ✅ |\r\n| `!discordbotframework` | Framework information and feature list | 10s | ✅ |\r\n| `!shardinfo` / `/shardinfo` | Shard information and distribution | 10s | ✅ |\r\n| `!setprefix \u003cprefix\u003e` | Set custom prefix for your server (Admin only) | - | ✅ |\r\n| `!config [cmd] [role]` | Configure command permissions (Owner only) | - | ✅ |\r\n\r\n### ⚙️ Guild Settings Commands\r\n\r\n| Command | Description | Permission | Hybrid |\r\n|---------|-------------|------------|--------|\r\n| `!mentionprefix enable` / `/mentionprefix enable` | Enable @mention prefix for this server | Administrator | ✅ |\r\n| `!mentionprefix disable` / `/mentionprefix disable` | Disable @mention prefix for this server | Administrator | ✅ |\r\n| `!mentionprefix status` / `/mentionprefix status` | Check current @mention prefix setting | Administrator | ✅ |\r\n| `!serversettings` / `/serversettings` | View all server configuration settings | Administrator | ✅ |\r\n\r\n**Note:** The @mention prefix feature allows users to invoke commands using `@BotName command` syntax. Server administrators can enable or disable this independently for their server. If no setting is configured, the bot uses the global default from `config.json`.\r\n\r\n### 🛒 Marketplace Commands\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!marketplace` / `/marketplace` | Main marketplace menu with quick actions | 5s | ✅ |\r\n| `!marketplace browse` | Browse all available extensions | 10s | ✅ |\r\n| `!marketplace search \u003cquery\u003e` | Search extensions by keywords | 10s | ✅ |\r\n| `!marketplace install \u003cid\u003e` | Install extension by ID | 30s | ✅ |\r\n| `!marketplace info \u003cid\u003e` | View detailed extension information | 5s | ✅ |\r\n| `!marketplace refresh` | Refresh extension cache | 60s | ✅ |\r\n| `!marketplace fixdeps` | Auto-install missing dependencies (Owner) | 60s | ✅ |\r\n| `!marketplace myid` | View your ZygnalID (Owner only) | - | ✅ |\r\n\r\n\r\n### Atomic File System Commands\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!atomicstats` / `/atomicstats` | Display atomic file system statistics (Owner) | - | Yes |\r\n| `!atomictest` / `/atomictest` | Run comprehensive atomic operations test suite (Owner) | - | Yes |\r\n\r\n\r\n\r\n### 🔌 Plugin Registry Commands\r\n\r\n| Command | Description | AI Query |\r\n|---------|-------------|----------|\r\n| `!pr_list` / `/pr_list` | List all registered plugins with status indicators | `/ask_zdbf action:plugins` |\r\n| `!pr_info \u003cname\u003e` / `/pr_info` | Detailed information about a specific plugin | `/ask_zdbf action:plugins query:\"tell me about [plugin]\"` |\r\n| `!pr_validate \u003cname\u003e` | Validate plugin dependencies and conflicts (Owner) | `/ask_zdbf action:plugins query:\"does [plugin] have issues?\"` |\r\n| `!pr_enforce \u003cmode\u003e` | Toggle dependency/conflict enforcement (Owner) | - |\r\n| `!pr_alert_channel [channel]` | Set alert channel for registry warnings (Owner) | - |\r\n\r\n### 📊 Framework Diagnostics Commands\r\n\r\n| Command | Description | AI Query |\r\n|---------|-------------|----------|\r\n| `!fw_diagnostics` / `/fw_diagnostics` | Display framework health and diagnostics (Owner) | `/ask_zdbf action:diagnose` |\r\n| `!fw_alert_channel` / `/fw_alert_channel` | Set alert channel for framework diagnostics (Owner) | - |\r\n| `!slashlimit` / `/slashlimit` | Check slash command usage and limits | `/ask_zdbf action:slash` |\r\n\r\n\r\n### 🪝 Event Hooks Commands\r\n\r\n| Command | Description | AI Query |\r\n|---------|-------------|----------|\r\n| `!eh_list` / `/eh_list` | Display registered hooks with metrics (Owner) | `/ask_zdbf action:hooks` |\r\n| `!eh_history [limit]` / `/eh_history` | Display hook execution history (Owner) | `/ask_zdbf action:hooks query:\"show hook history\"` |\r\n| `!eh_disable \u003chook_id\u003e` | Disable a problematic hook (Owner) | - |\r\n| `!eh_enable \u003chook_id\u003e` | Re-enable a disabled hook (Owner) | - |\r\n| `!eh_reset_circuit \u003chook_id\u003e` | Reset circuit breaker for hook (Owner) | - |\r\n| `!eh_alert_channel [channel]` | Set alert channel for event hooks (Owner) | - |\r\n\r\n### 📡 Live Monitor Commands\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `/livemonitor quickstart \u003curl\u003e` | Generate dashboard files and configure monitoring | - | ✅ |\r\n| `/livemonitor status` | Show current configuration, connection status, failure count | - | ✅ |\r\n| `/livemonitor enable` | Start sending data to dashboard (2-second intervals) | - | ✅ |\r\n| `/livemonitor disable` | Stop all data transmission and command polling | - | ✅ |\r\n| `/livemonitor files` | Regenerate dashboard PHP/HTML/JS files | - | ✅ |\r\n\r\n**Note:** Live Monitor requires a PHP web server (e.g., Strato, Hostinger, any cPanel host). See the [Using Live Monitor](#using-live-monitor) section for complete setup instructions.\r\n\r\n### 🤖 AI Assistant Commands\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `/ask_zdbf \u003caction\u003e [query]` | Ask the AI assistant about the bot, its code, or data | 15s | ❌ (Slash Only) |\r\n\r\n**Actions for `/ask_zdbf`:**\r\n- **`help`**: Shows an interactive help menu for the AI assistant.\r\n- **`framework`**: Ask a general question about the bot's architecture.\r\n- **`plugins`**: Get an AI-powered analysis of installed plugins.\r\n- **`diagnose`**: Receive a health report summary from the AI.\r\n- **`database`**: Ask a question about the database schema in natural language.\r\n- **`file`**: Ask a question about a specific file's content.\r\n- **`extension`**: Inspect an extension file from the `/extensions` folder.\r\n- **`slash`**: Inquire about the slash command auto-conversion system.\r\n- **`hooks`**: Ask about the internal framework (EventHooks) event system.\r\n- **`automations`**: Ask about user-created automations.\r\n- **`readme`**: Ask a question about the bot's `README.md` file.\r\n- **`permission`**: (Owner Only) Manage permissions for the AI assistant.\r\n\r\n### 📊 Shard Monitor Commands\r\n\r\n\u003e **All commands are Bot Owner Only** (`BOT_OWNER_ID` from `.env`)  \r\n\u003e Toggle: `ENABLE_SHARD_MONITOR=true/false` in `.env`\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!shardmonitor` / `/shardmonitor` | Interactive dashboard with button navigation (Overview, Health, Latency, Events) | 10s | ✅ |\r\n| `!sharddetails \u003cid\u003e` / `/sharddetails` | Detailed metrics for a specific shard (guilds, members, latency, reliability, errors) | 10s | ✅ |\r\n| `!shardhealth` / `/shardhealth` | Health check report for all shards with critical/warning/healthy breakdown | 30s | ✅ |\r\n| `!shardalerts [#channel] [threshold]` / `/shardalerts` | Configure alert channel and failure threshold for automatic health alerts | - | ✅ |\r\n| `!shardreset [shard_id]` / `/shardreset` | Reset metrics for a specific shard or all shards (-1 for all) | - | ✅ |\r\n\r\n**Interactive Dashboard Tabs (`/shardmonitor`):**\r\n\r\n| Tab | Button | What It Shows |\r\n|-----|--------|---------------|\r\n| Overview | 📊 | Cluster stats, per-shard summary, alert config |\r\n| Health | 🏥 | Health report with healthy/warning/critical breakdown |\r\n| Latency | 📡 | Visual latency bars per shard, cluster latency statistics |\r\n| Events | 📈 | Per-shard event counters (messages, commands, connects, errors) |\r\n| Refresh | 🔄 | Refreshes the currently active tab with latest data |\r\n\r\n**Health Check Thresholds:**\r\n\r\n| Condition | Status | Icon |\r\n|-----------|--------|------|\r\n| Average latency \u003e 1000ms | Warning | 🟡 |\r\n| Average latency \u003e 2000ms | Critical | 🔴 |\r\n| No activity for 5+ minutes | Warning | 🟡 |\r\n| 3+ consecutive failures | Warning | 🟡 |\r\n| 5+ consecutive failures | Critical | 🔴 |\r\n| Currently disconnected | Critical | 🔴 |\r\n| Recently disconnected (\u003c60s) | Warning | 🟡 |\r\n\r\n### 🌐 Shard Manager Commands\r\n\r\n\u003e **All commands are Bot Owner Only** (`BOT_OWNER_ID` from `.env`)  \r\n\u003e Toggle: `ENABLE_SHARD_MANAGER=true/false` in `.env` (disabled by default)  \r\n\u003e Only needed for multi-process or multi-server deployments\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!clusters` / `/clusters` | Show all connected shard clusters with stats, health, and global totals | 10s | ✅ |\r\n| `!ipcstatus` / `/ipcstatus` | IPC system diagnostics (mode, host, port, connected clients, heartbeats) | 10s | ✅ |\r\n| `!broadcastmsg \u003cmessage\u003e` / `/broadcastmsg` | Broadcast a text message to all connected clusters via IPC | - | ✅ |\r\n\r\n### 💾 Backup \u0026 Restore Commands\r\n\r\n\u003e **Administrator** permission required (Bot Owner has full access)\r\n\u003e Toggle: `ENABLE_BACKUP_RESTORE=true/false` in `.env` (enabled by default)\r\n\u003e Useful for server migrations, disaster recovery, configuration auditing, and member role recovery\r\n\r\n| Command | Description | Cooldown | Hybrid |\r\n|---------|-------------|----------|--------|\r\n| `!backup` / `/backup` | Interactive dashboard with Overview, Backups, Compare, Audit, and Analytics tabs | 10s | ✅ |\r\n| `!backupcreate [label]` / `/backupcreate` | Create a full guild snapshot (roles, channels, member roles, permissions, settings) | 5min/guild | ✅ |\r\n| `!backuprestore \u003cid\u003e` / `/backuprestore` | Selective restore with component toggles (roles, categories, channels, member roles, bot settings) | - | ✅ |\r\n| `!backupview \u003cid\u003e` / `/backupview` | Detailed backup inspection (contents, roles, settings, member count, checksum) | - | ✅ |\r\n| `!backupdelete \u003cid\u003e` / `/backupdelete` | Delete a backup with confirmation (respects pin protection) | - | ✅ |\r\n| `!backuplist` / `/backuplist` | Paginated list of all backups with metadata | - | ✅ |\r\n| `!backuppin \u003cid\u003e` / `/backuppin` | Pin/unpin a backup to protect from deletion and retention cleanup | - | ✅ |\r\n| `!backupnote \u003cid\u003e \u003ctext\u003e` / `/backupnote` | Add or update a note on a backup (up to 500 chars) | - | ✅ |\r\n| `!backupverify \u003cid\u003e` / `/backupverify` | Verify backup integrity via SHA-256 checksum | - | ✅ |\r\n| `!backupschedule \u003caction\u003e` / `/backupschedule` | Configure auto-backup schedule (enable/disable/status, 1-168h interval) | - | ✅ |\r\n| `!backupdiff \u003ca\u003e \u003cb\u003e` / `/backupdiff` | Compare two backups side by side (roles, channels, members added/removed) | - | ✅ |\r\n| `!backupexport \u003cid\u003e` / `/backupexport` | Export backup as downloadable JSON file | - | ✅ (Bot Owner only) |\r\n| `!backupstats` / `/backupstats` | Global backup statistics across all guilds | - | ✅ (Bot Owner only) |\r\n\r\n**Interactive Dashboard Tabs (`/backup`):**\r\n\r\n| Tab | Button | What It Shows |\r\n|-----|--------|---------------|\r\n| Overview | 📊 | Storage usage bar, latest backup, current guild stats, cooldown timer |\r\n| Backups | 📦 | Paginated list of all backups with ID, label, author, member snapshots, size |\r\n| Compare | 🔍 | Drift analysis: current state vs latest backup with change recommendation |\r\n| Audit Log | 📜 | Chronological log of all backup operations (create, delete, restore, pin, verify) |\r\n| Analytics | 📈 | Trends over time, top creators, backup frequency, member snapshot stats |\r\n| Refresh | 🔄 | Refreshes the currently active tab |\r\n| Delete | 🗑️ | Quick-delete via dropdown selector (ephemeral, respects pin protection) |\r\n| ◀ ▶ | Pagination | Navigate through paginated list and audit pages |\r\n\r\n**What Gets Backed Up:**\r\n\r\n| Category | Details |\r\n|----------|---------|\r\n| Roles | Name, color, hoist, mentionable, permissions value, position |\r\n| Categories | Name, position, NSFW flag, full permission overwrites (target, allow, deny) |\r\n| Text Channels | Name, topic, slowmode, NSFW, category, auto-archive duration, full permission overwrites |\r\n| Voice Channels | Name, bitrate, user limit, RTC region, category, full permission overwrites |\r\n| Forum Channels | Name, topic, NSFW, slowmode, category, permission overwrites |\r\n| Stage Channels | Name, topic, category, permission overwrites |\r\n| Emojis | Name, animated flag, URL, managed status |\r\n| Stickers | Name, description, emoji |\r\n| Server Settings | Verification level, notification level, content filter, AFK timeout/channel, system channel, locale, boost bar |\r\n| **Member Roles** | **Per-member role assignments for all non-bot members (requires Members Intent)** |\r\n| Bot Settings | Custom prefix, mention prefix enabled/disabled |\r\n\r\n### 🔧 Owner-Only Commands\r\n\r\n| Command | Description | Access |\r\n|---------|-------------|--------|\r\n| `!sync` / `/sync` | Force sync slash commands globally | Bot Owner |\r\n| `!reload \u003cextension\u003e` | Hot-reload specific extension | Bot Owner |\r\n| `!load \u003cextension\u003e` | Load extension | Bot Owner |\r\n| `!unload \u003cextension\u003e` | Unload extension | Bot Owner |\r\n| `!fw_diagnostics` | Display framework diagnostics and health | Bot Owner |\r\n| `!fw_alert_channel \u003cchannel\u003e` | Set alert channel for framework diagnostics | Bot Owner |\r\n| `!cachestats` | Display cache statistics | Bot Owner |\r\n| `!dbstats` | Display database connection stats | Bot Owner |\r\n| `!integritycheck` | Run full system integrity check | Bot Owner |\r\n| `!cleanup` | Clean up system cache and temp files | Bot Owner |\r\n| `!shardmonitor` | Interactive shard monitoring dashboard | Bot Owner |\r\n| `!sharddetails \u003cid\u003e` | Detailed metrics for specific shard | Bot Owner |\r\n| `!shardhealth` | Health check report for all shards | Bot Owner |\r\n| `!shardalerts [#ch] [n]` | Configure shard alert channel and threshold | Bot Owner |\r\n| `!shardreset [id]` | Reset shard metrics (-1 for all) | Bot Owner |\r\n| `!clusters` | Show all connected shard clusters (requires Shard Manager) | Bot Owner |\r\n| `!ipcstatus` | IPC system diagnostics (requires Shard Manager) | Bot Owner |\r\n| `!broadcastmsg \u003cmsg\u003e` | Broadcast message to all clusters (requires Shard Manager) | Bot Owner |\r\n| `!backupexport \u003cid\u003e` | Export backup as JSON file | Bot Owner |\r\n| `!backupstats` | Global backup statistics across all guilds | Bot Owner |\r\n\r\n---\r\n\r\n## 🛒 Extension Marketplace\r\n\r\n### Overview\r\n\r\nThe integrated Extension Marketplace allows you to browse, search, and install official extensions directly from Discord without manual file downloads.\r\n\r\n### Features\r\n\r\n✅ **Browse Extensions** - View all available extensions with pagination  \r\n✅ **Search Functionality** - Find extensions by keywords  \r\n✅ **Category Filtering** - Filter by status (Working, Beta, Broken)  \r\n✅ **One-Click Install** - Direct installation to `./extensions` directory  \r\n✅ **License Agreement** - Mandatory acceptance before use  \r\n✅ **ZygnalID System** - Unique bot identification for support  \r\n✅ **Dependency Management** - Automatic missing package installation  \r\n✅ **Version Tracking** - View extension versions and update dates  \r\n\r\n### First-Time Setup\r\n\r\n1. **Run marketplace command:**\r\n```bash\r\n!marketplace\r\n```\r\n\r\n2. **Accept License Agreement:**\r\n   - Read the terms carefully\r\n   - Click \"✅ Accept License\" button\r\n   - Acceptance is tracked per-user\r\n\r\n3. **Browse Extensions:**\r\n   - Use dropdown menu or buttons\r\n   - Search by keywords\r\n   - Filter by categories\r\n\r\n### Installing Extensions\r\n\r\n**Method 1: Interactive Menu**\r\n```bash\r\n!marketplace\r\n# Click \"Browse All\" button\r\n# Select extension from dropdown\r\n# Click \"📦 Install Extension\"\r\n# Confirm installation\r\n```\r\n\r\n**Method 2: Direct Install**\r\n```bash\r\n!marketplace install \u003cextension_id\u003e\r\n```\r\n\r\n**Post-Installation:**\r\nAfter successful installation:\r\n```bash\r\n# Load the extension immediately\r\n!load extension_name\r\n\r\n# Or reload if already loaded\r\n!reload extension_name\r\n\r\n# Or restart bot for auto-load\r\n```\r\n\r\n### ZygnalID System\r\n\r\n**What is ZygnalID?**\r\n- Unique 16-character identifier for your bot\r\n- Auto-generated on first marketplace use\r\n- Required for extension downloads\r\n- Enables dedicated support and tracking\r\n\r\n**View Your ID:**\r\n```bash\r\n!marketplace myid\r\n```\r\n(Owner only, sent via DM for security)\r\n\r\n**Activation:**\r\nIf your ID is invalid or not activated:\r\n1. Join ZygnalBot Discord: `gg/sgZnXca5ts`\r\n2. Verify yourself\r\n3. Open ticket for \"Zygnal ID Activation\"\r\n4. Provide your ZygnalID from `!marketplace myid`\r\n\r\n### Dependency Management\r\n\r\n**Automatic Fix:**\r\nIf extensions fail to load due to missing Python packages:\r\n```bash\r\n!marketplace fixdeps\r\n```\r\n\r\nThis command:\r\n1. Scans `botlogs/current_run.log` for `ModuleNotFoundError`\r\n2. Extracts missing package names\r\n3. Automatically runs `pip install \u003cpackage\u003e`\r\n4. Reports success/failure per package\r\n5. Provides next steps for loading extensions\r\n\r\n**Manual Installation:**\r\n```bash\r\npip install package_name\r\n!reload extension_name\r\n```\r\n\r\n### Marketplace Categories\r\n\r\n**Working** ✅\r\n- Fully functional extensions\r\n- Tested and verified\r\n- Production-ready\r\n\r\n**Beta** ⚠️\r\n- Experimental features\r\n- May have minor issues\r\n- Actively developed\r\n\r\n**Broken** ❌\r\n- Known issues\r\n- Not recommended for use\r\n- Awaiting fixes\r\n\r\n### Extension Information\r\n\r\nView detailed information about any extension:\r\n```bash\r\n!marketplace info \u003cextension_id\u003e\r\n```\r\n\r\nDisplays:\r\n- Full description\r\n- Version number\r\n- Status (Working/Beta/Broken)\r\n- File type (PY/TXT)\r\n- Upload date\r\n- Custom URL (if available)\r\n- Installation instructions\r\n\r\n### Searching Extensions\r\n\r\n**By Keyword:**\r\n```bash\r\n!marketplace search moderation\r\n```\r\n\r\n**By Title or Description:**\r\nThe search is case-insensitive and matches:\r\n- Extension titles\r\n- Description text\r\n- Details field\r\n\r\n### Cache Management\r\n\r\nThe marketplace caches API responses for 300 seconds (5 minutes).\r\n\r\n**Force Refresh:**\r\n```bash\r\n!marketplace refresh\r\n```\r\n\r\nUse this when:\r\n- New extensions are added\r\n- Extension details are updated\r\n- Cache shows outdated information\r\n\r\n---\r\n\r\n## 🔧 Creating Extensions\r\n\r\n### Basic Extension Template\r\n```python\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom discord import app_commands\r\n\r\nclass MyExtension(commands.Cog):\r\n    \"\"\"Description of your extension\"\"\"\r\n    \r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n        print(f\"{self.__class__.__name__} initialized\")\r\n    \r\n    @commands.hybrid_command(\r\n        name=\"example\",\r\n        help=\"An example command that works with both prefix and slash\"\r\n    )\r\n    @commands.cooldown(1, 5, commands.BucketType.user)\r\n    async def example_command(self, ctx):\r\n        \"\"\"Command implementation\"\"\"\r\n        embed = discord.Embed(\r\n            title=\"✅ Success\",\r\n            description=\"This is an example command!\",\r\n            color=0x00ff00\r\n        )\r\n        await ctx.send(embed=embed)\r\n    \r\n    @commands.Cog.listener()\r\n    async def on_message(self, message):\r\n        \"\"\"Event listener example\"\"\"\r\n        if message.author.bot:\r\n            return\r\n        # Your logic here\r\n    \r\n    def cog_unload(self):\r\n        \"\"\"Cleanup when extension is unloaded\"\"\"\r\n        print(f\"{self.__class__.__name__} unloaded\")\r\n\r\nasync def setup(bot):\r\n    \"\"\"Required setup function\"\"\"\r\n    await bot.add_cog(MyExtension(bot))\r\n```\r\n\r\n### Using Atomic File Operations in Extensions\r\n\r\n**Basic File Operations:**\r\n```python\r\nfrom atomic_file_system import global_file_handler\r\n\r\nclass MyExtension(commands.Cog):\r\n    async def save_data(self, data: dict):\r\n        # Atomic write with cache invalidation\r\n        success = await global_file_handler.atomic_write_json(\r\n            \"./data/my_extension_data.json\",\r\n            data,\r\n            invalidate_cache_after=True\r\n        )\r\n        return success\r\n    \r\n    async def load_data(self) -\u003e dict:\r\n        # Read with caching enabled (300s TTL)\r\n        data = await global_file_handler.atomic_read_json(\r\n            \"./data/my_extension_data.json\",\r\n            use_cache=True\r\n        )\r\n        return data or {}\r\n```\r\n\r\n**Advanced Usage with Manual Cache Control:**\r\n```python\r\nclass AdvancedExtension(commands.Cog):\r\n    async def update_config(self, key: str, value: str):\r\n        # Read current config (cached)\r\n        config = await global_file_handler.atomic_read_json(\r\n            \"./data/config.json\",\r\n            use_cache=True\r\n        ) or {}\r\n        \r\n        # Update config\r\n        config[key] = value\r\n        \r\n        # Write and keep in cache (frequent reads)\r\n        await global_file_handler.atomic_write_json(\r\n            \"./data/config.json\",\r\n            config,\r\n            invalidate_cache_after=False  # Keep in cache\r\n        )\r\n    \r\n    async def force_reload(self):\r\n        # Bypass cache for critical reads\r\n        config = await global_file_handler.atomic_read_json(\r\n            \"./data/config.json\",\r\n            use_cache=False\r\n        )\r\n        \r\n        # Or manually invalidate cache\r\n        global_file_handler.invalidate_cache(\"./data/config.json\")\r\n```\r\n\r\n**Cache Statistics in Extensions:**\r\n```python\r\nclass MonitoringExtension(commands.Cog):\r\n    @commands.command()\r\n    async def check_cache(self, ctx):\r\n        stats = global_file_handler.get_cache_stats()\r\n        \r\n        await ctx.send(f\"\"\"\r\n        Cache Performance:\r\n        - Size: {stats['cache_size']}/{stats['max_cache_size']}\r\n        - Hit Rate: {stats['hit_rate']}%\r\n        - Total Ops: {stats['total_reads'] + stats['total_writes']}\r\n        - Failures: {stats['write_failures'] + stats['read_failures']}\r\n        \"\"\")\r\n```\r\n\r\n\r\n### Extension with Plugin Metadata\r\n```python\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\n# Plugin metadata (recommended for Plugin Registry)\r\n__version__ = \"1.0.0\"\r\n__author__ = \"YourName\"\r\n__description__ = \"A cool extension that does amazing things\"\r\n__dependencies__ = []  # List of required extensions\r\n__conflicts__ = []     # List of incompatible extensions\r\n\r\nclass MyExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n        \r\n        # Register with Plugin Registry (if available)\r\n        if hasattr(bot, 'register_plugin'):\r\n            bot.register_plugin(\r\n                name=\"my_extension\",\r\n                version=__version__,\r\n                author=__author__,\r\n                description=__description__,\r\n                dependencies=__dependencies__,\r\n                conflicts_with=__conflicts__\r\n            )\r\n    \r\n    @commands.hybrid_command(name=\"example\")\r\n    async def example_command(self, ctx):\r\n        await ctx.send(\"Hello from my extension!\")\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(MyExtension(bot))\r\n```\r\n\r\n### Using Framework Event Hooks\r\n```python\r\nfrom discord.ext import commands\r\nimport discord\r\n\r\nclass HookedExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n        \r\n        # Register hooks if Event Hooks system is available\r\n        if hasattr(bot, 'register_hook'):\r\n            # Priority: higher executes first (default: 0)\r\n            bot.register_hook(\"extension_loaded\", self.on_ext_loaded, priority=5)\r\n            bot.register_hook(\"command_executed\", self.on_cmd_used)\r\n            bot.register_hook(\"bot_ready\", self.on_bot_ready)\r\n    \r\n    async def on_ext_loaded(self, bot, extension_name: str, **kwargs):\r\n        \"\"\"Called when any extension is loaded\"\"\"\r\n        print(f\"Extension loaded: {extension_name}\")\r\n    \r\n    async def on_cmd_used(self, bot, command_name: str, author, **kwargs):\r\n        \"\"\"Called when any command is executed\"\"\"\r\n        print(f\"Command {command_name} used by {author}\")\r\n    \r\n    async def on_bot_ready(self, bot, bot_user, **kwargs):\r\n        \"\"\"Called when bot becomes ready\"\"\"\r\n        print(f\"Bot is ready: {bot_user}\")\r\n    \r\n    def cog_unload(self):\r\n        \"\"\"Cleanup: Unregister hooks when cog unloads\"\"\"\r\n        if hasattr(self.bot, 'unregister_hook'):\r\n            self.bot.unregister_hook(\"extension_loaded\", self.on_ext_loaded)\r\n            self.bot.unregister_hook(\"command_executed\", self.on_cmd_used)\r\n            self.bot.unregister_hook(\"bot_ready\", self.on_bot_ready)\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(HookedExtension(bot))\r\n```\r\n\r\n### Using Database System\r\n```python\r\nfrom discord.ext import commands\r\nimport discord\r\n\r\nclass DatabaseExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n    \r\n    @commands.hybrid_command(name=\"savedata\")\r\n    async def save_data(self, ctx, key: str, value: str):\r\n        \"\"\"Save data to guild database\"\"\"\r\n        # Get guild-specific database connection\r\n        conn = await self.bot.db._get_guild_connection(ctx.guild.id)\r\n        \r\n        # Create table if not exists\r\n        await conn.execute(\"\"\"\r\n            CREATE TABLE IF NOT EXISTS custom_data (\r\n                key TEXT PRIMARY KEY,\r\n                value TEXT,\r\n                user_id INTEGER,\r\n                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\r\n            )\r\n        \"\"\")\r\n        \r\n        # Insert or replace data\r\n        await conn.execute(\r\n            \"INSERT OR REPLACE INTO custom_data (key, value, user_id) VALUES (?, ?, ?)\",\r\n            (key, value, ctx.author.id)\r\n        )\r\n        await conn.commit()\r\n        \r\n        await ctx.send(f\"✅ Saved: {key} = {value}\")\r\n    \r\n    @commands.hybrid_command(name=\"getdata\")\r\n    async def get_data(self, ctx, key: str):\r\n        \"\"\"Retrieve data from guild database\"\"\"\r\n        conn = await self.bot.db._get_guild_connection(ctx.guild.id)\r\n        \r\n        async with conn.execute(\r\n            \"SELECT value, user_id FROM custom_data WHERE key = ?\",\r\n            (key,)\r\n        ) as cursor:\r\n            row = await cursor.fetchone()\r\n            \r\n            if row:\r\n                await ctx.send(f\"📄 {key} = {row['value']} (saved by \u003c@{row['user_id']}\u003e)\")\r\n            else:\r\n                await ctx.send(f\"❌ No data found for key: {key}\")\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(DatabaseExtension(bot))\r\n```\r\n\r\n### Integration with Atomic File System\r\n\r\nThe database system uses the atomic file handler for:\r\n- **Configuration persistence** - `config.json` written atomically\r\n- **Plugin registry storage** - Registry JSON with ACID compliance\r\n- **Framework diagnostics** - Diagnostic reports saved safely\r\n- **Extension data** - Any JSON-based extension storage\r\n\r\n**Benefits:**\r\n- Zero data corruption even during crashes\r\n- Concurrent access safety\r\n- Automatic retry on transient failures\r\n- Cache acceleration for frequently accessed files\r\n- Lock-free reads (when cached)\r\n\r\n**Performance Optimization:**\r\n```python\r\n# High-frequency reads (use cache)\r\nprefix = await bot.config.get(\"prefix\")  # Cached\r\n\r\n# Critical writes (bypass cache)\r\nawait bot.config.file_handler.atomic_write_json(\r\n    path, \r\n    data, \r\n    invalidate_cache_after=True\r\n)\r\n\r\n# Batch operations (manual cache management)\r\nfor item in items:\r\n    await process_item(item)\r\nglobal_file_handler.clear_all_cache()  # Clear after batch\r\n```\r\n\r\n\r\n\r\n### Using Atomic File Operations\r\n```python\r\nfrom discord.ext import commands\r\nimport discord\r\nfrom atomic_file_system import global_file_handler\r\nfrom datetime import datetime\r\n\r\nclass FileExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n        self.data_file = \"./data/my_extension_data.json\"\r\n    \r\n    @commands.hybrid_command(name=\"saveconfig\")\r\n    async def save_config(self, ctx, setting: str, value: str):\r\n        \"\"\"Save configuration atomically\"\"\"\r\n        \r\n        # Read existing data (with caching)\r\n        existing_data = await global_file_handler.atomic_read_json(\r\n            self.data_file,\r\n            use_cache=True\r\n        ) or {}\r\n        \r\n        # Update data\r\n        existing_data[setting] = {\r\n            \"value\": value,\r\n            \"set_by\": ctx.author.id,\r\n            \"timestamp\": datetime.now().isoformat()\r\n        }\r\n        \r\n        # Atomic write (invalidates cache)\r\n        success = await global_file_handler.atomic_write_json(\r\n            self.data_file,\r\n            existing_data,\r\n            invalidate_cache_after=True\r\n        )\r\n        \r\n        if success:\r\n            await ctx.send(f\"✅ Configuration saved: {setting} = {value}\")\r\n        else:\r\n            await ctx.send(\"❌ Failed to save configuration\")\r\n    \r\n    @commands.hybrid_command(name=\"getconfig\")\r\n    async def get_config(self, ctx, setting: str = None):\r\n        \"\"\"Retrieve configuration\"\"\"\r\n        \r\n        # Read with caching enabled (300s TTL)\r\n        data = await global_file_handler.atomic_read_json(\r\n            self.data_file,\r\n            use_cache=True\r\n        )\r\n        \r\n        if not data:\r\n            await ctx.send(\"❌ No configuration found\")\r\n            return\r\n        \r\n        if setting:\r\n            if setting in data:\r\n                config = data[setting]\r\n                await ctx.send(\r\n                    f\"📄 {setting} = {config['value']}\\n\"\r\n                    f\"Set by: \u003c@{config['set_by']}\u003e\\n\"\r\n                    f\"Time: {config['timestamp']}\"\r\n                )\r\n            else:\r\n                await ctx.send(f\"❌ Setting not found: {setting}\")\r\n        else:\r\n            # Display all settings\r\n            embed = discord.Embed(\r\n                title=\"⚙️ All Configurations\",\r\n                color=0x5865f2\r\n            )\r\n            for key, config in data.items():\r\n                embed.add_field(\r\n                    name=key,\r\n                    value=f\"Value: {config['value']}\\nSet by: \u003c@{config['set_by']}\u003e\",\r\n                    inline=False\r\n                )\r\n            await ctx.send(embed=embed)\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(FileExtension(bot))\r\n```\r\n\r\n\r\n### Advanced Extension with Permissions\r\n\r\n```python\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom discord import app_commands\r\n\r\nclass ModerationExtension(commands.Cog, name=\"Moderation\"):\r\n    \"\"\"Moderation commands for server management\"\"\"\r\n    \r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n    \r\n    @commands.hybrid_command(\r\n        name=\"ban\",\r\n        help=\"Ban a user from the server\"\r\n    )\r\n    @commands.has_permissions(ban_members=True)\r\n    @commands.bot_has_permissions(ban_members=True)\r\n    @commands.guild_only()\r\n    async def ban_user(\r\n        self,\r\n        ctx,\r\n        member: discord.Member,\r\n        *,\r\n        reason: str = \"No reason provided\"\r\n    ):\r\n        \"\"\"Ban a member with reason\"\"\"\r\n        \r\n        # Safety check\r\n        if member.top_role \u003e= ctx.author.top_role:\r\n            await ctx.send(\"❌ You cannot ban this user (role hierarchy)\")\r\n            return\r\n        \r\n        # Perform ban\r\n        await member.ban(reason=f\"{reason} (By: {ctx.author})\")\r\n        \r\n        # Log to database\r\n        await self.bot.db.increment_command_usage(\"ban\")\r\n        \r\n        # Send confirmation\r\n        embed = discord.Embed(\r\n            title=\"🔨 User Banned\",\r\n            description=f\"**User:** {member.mention}\\n**Reason:** {reason}\",\r\n            color=0xff0000,\r\n            timestamp=discord.utils.utcnow()\r\n        )\r\n        embed.set_footer(text=f\"Banned by {ctx.author}\")\r\n        \r\n        await ctx.send(embed=embed)\r\n        \r\n        # Try to DM the user\r\n        try:\r\n            dm_embed = discord.Embed(\r\n                title=\"You were banned\",\r\n                description=f\"**Server:** {ctx.guild.name}\\n**Reason:** {reason}\",\r\n                color=0xff0000\r\n            )\r\n            await member.send(embed=dm_embed)\r\n        except:\r\n            pass  # User has DMs disabled\r\n    \r\n    @commands.hybrid_command(\r\n        name=\"kick\",\r\n        help=\"Kick a user from the server\"\r\n    )\r\n    @commands.has_permissions(kick_members=True)\r\n    @commands.bot_has_permissions(kick_members=True)\r\n    @commands.guild_only()\r\n    async def kick_user(\r\n        self,\r\n        ctx,\r\n        member: discord.Member,\r\n        *,\r\n        reason: str = \"No reason provided\"\r\n    ):\r\n        \"\"\"Kick a member with reason\"\"\"\r\n        \r\n        if member.top_role \u003e= ctx.author.top_role:\r\n            await ctx.send(\"❌ You cannot kick this user (role hierarchy)\")\r\n            return\r\n        \r\n        await member.kick(reason=f\"{reason} (By: {ctx.author})\")\r\n        await self.bot.db.increment_command_usage(\"kick\")\r\n        \r\n        embed = discord.Embed(\r\n            title=\"👢 User Kicked\",\r\n            description=f\"**User:** {member.mention}\\n**Reason:** {reason}\",\r\n            color=0xff9900,\r\n            timestamp=discord.utils.utcnow()\r\n        )\r\n        embed.set_footer(text=f\"Kicked by {ctx.author}\")\r\n        \r\n        await ctx.send(embed=embed)\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(ModerationExtension(bot))\r\n```\r\n\r\n\r\n### Extension with Background Tasks\r\n```python\r\nimport discord\r\nfrom discord.ext import commands, tasks\r\nfrom datetime import datetime\r\n\r\nclass TaskExtension(commands.Cog):\r\n    \"\"\"Extension with background tasks\"\"\"\r\n    \r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n        self.message_count = 0\r\n        self.hourly_report.start()\r\n    \r\n    def cog_unload(self):\r\n        \"\"\"Stop tasks when unloading\"\"\"\r\n        self.hourly_report.cancel()\r\n    \r\n    @tasks.loop(hours=1)\r\n    async def hourly_report(self):\r\n        \"\"\"Send hourly statistics report\"\"\"\r\n        channel_id = self.bot.config.get(\"reports_channel_id\")\r\n        if not channel_id:\r\n            return\r\n        \r\n        channel = self.bot.get_channel(channel_id)\r\n        if not channel:\r\n            return\r\n        \r\n        embed = discord.Embed(\r\n            title=\"📊 Hourly Report\",\r\n            description=f\"Messages tracked: {self.message_count}\",\r\n            color=0x5865f2,\r\n            timestamp=datetime.utcnow()\r\n        )\r\n        \r\n        stats = self.bot.metrics.get_stats()\r\n        embed.add_field(\r\n            name=\"Bot Statistics\",\r\n            value=f\"Commands: {stats['commands_processed']}\\nErrors: {stats['error_count']}\",\r\n            inline=False\r\n        )\r\n        \r\n        await channel.send(embed=embed)\r\n        self.message_count = 0  # Reset counter\r\n    \r\n    @hourly_report.before_loop\r\n    async def before_hourly_report(self):\r\n        \"\"\"Wait until bot is ready\"\"\"\r\n        await self.bot.wait_until_ready()\r\n    \r\n    @commands.Cog.listener()\r\n    async def on_message(self, message):\r\n        \"\"\"Track messages\"\"\"\r\n        if not message.author.bot:\r\n            self.message_count += 1\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(TaskExtension(bot))\r\n```\r\n### Extension with Custom Checks\r\n```python\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\ndef is_admin_or_owner():\r\n    \"\"\"Custom check for admin or bot owner\"\"\"\r\n    async def predicate(ctx):\r\n        if ctx.author.id == ctx.bot.bot_owner_id:\r\n            return True\r\n        if ctx.guild and ctx.author.guild_permissions.administrator:\r\n            return True\r\n        raise commands.CheckFailure(\"You must be an administrator or bot owner\")\r\n    return commands.check(predicate)\r\n\r\ndef has_any_role(*role_names):\r\n    \"\"\"Custom check for any of the specified roles\"\"\"\r\n    async def predicate(ctx):\r\n        if not ctx.guild:\r\n            raise commands.CheckFailure(\"This command cannot be used in DMs\")\r\n        \r\n        member_roles = [role.name for role in ctx.author.roles]\r\n        if any(role in member_roles for role in role_names):\r\n            return True\r\n        \r\n        raise commands.CheckFailure(f\"You need one of these roles: {', '.join(role_names)}\")\r\n    return commands.check(predicate)\r\n\r\nclass CustomChecksExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n    \r\n    @commands.hybrid_command(name=\"adminonly\")\r\n    @is_admin_or_owner()\r\n    async def admin_only_command(self, ctx):\r\n        \"\"\"Only admins and bot owner can use this\"\"\"\r\n        await ctx.send(\"✅ You have admin privileges!\")\r\n    \r\n    @commands.hybrid_command(name=\"staffonly\")\r\n    @has_any_role(\"Staff\", \"Moderator\", \"Admin\")\r\n    async def staff_only_command(self, ctx):\r\n        \"\"\"Only staff members can use this\"\"\"\r\n        await ctx.send(\"✅ You are a staff member!\")\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(CustomChecksExtension(bot))\r\n\r\n```\r\n\r\n### Extension with Slash Command Options\r\n```python\r\n\r\nimport discord\r\nfrom discord.ext import commands\r\nfrom discord import app_commands\r\nfrom typing import Literal\r\n\r\nclass SlashOptionsExtension(commands.Cog):\r\n    def __init__(self, bot):\r\n        self.bot = bot\r\n    \r\n    @commands.hybrid_command(name=\"color\")\r\n    @app_commands.describe(\r\n        color=\"Choose a color\",\r\n        intensity=\"Color intensity level\"\r\n    )\r\n    async def color_command(\r\n        self,\r\n        ctx,\r\n        color: Literal[\"red\", \"green\", \"blue\"],\r\n        intensity: int = 5\r\n    ):\r\n        \"\"\"Command with slash options\"\"\"\r\n        \r\n        color_map = {\r\n            \"red\": 0xff0000,\r\n            \"green\": 0x00ff00,\r\n            \"blue\": 0x0000ff\r\n        }\r\n        \r\n        embed = discord.Embed(\r\n            title=f\"{color.capitalize()} Color\",\r\n            description=f\"Intensity: {intensity}/10\",\r\n            color=color_map[color]\r\n        )\r\n        \r\n        await ctx.send(embed=embed)\r\n    \r\n    @commands.hybrid_command(name=\"userinfo\")\r\n    @app_commands.describe(member=\"The member to get info about\")\r\n    async def userinfo_command(\r\n        self,\r\n        ctx,\r\n        member: discord.Member = None\r\n    ):\r\n        \"\"\"Get information about a user\"\"\"\r\n        \r\n        member = member or ctx.author\r\n        \r\n        embed = discord.Embed(\r\n            title=f\"User Info: {member}\",\r\n            color=member.color\r\n        )\r\n        embed.set_thumbnail(url=member.display_avatar.url)\r\n        embed.add_field(name=\"ID\", value=member.id, inline=True)\r\n        embed.add_field(name=\"Joined\", value=member.joined_at.strftime(\"%Y-%m-%d\"), inline=True)\r\n        embed.add_field(name=\"Roles\", value=f\"{len(member.roles)-1}\", inline=True)\r\n        \r\n        await ctx.send(embed=embed)\r\n\r\nasync def setup(bot):\r\n    await bot.add_cog(SlashOptionsExtension(bot))\r\n```\r\n\r\n### ⚙️ Configuration Guide\r\n#### Auto-Generated config.json\r\nOn first run, the bot creates config.json with default settings:\r\n\r\n```python\r\n\r\n{\r\n    \"prefix\": \"!\",\r\n    \"allow_mention_prefix\": true,\r\n    \"owner_ids\": [],\r\n    \"auto_reload\": true,\r\n    \"status\": {\r\n        \"type\": \"watching\",\r\n        \"text\": \"{guilds} servers\"\r\n    },\r\n    \"database\": {\r\n        \"base_path\": \"./data\"\r\n    },\r\n    \"logging\": {\r\n        \"level\": \"INFO\",\r\n        \"max_bytes\": 10485760,\r\n        \"backup_count\": 5\r\n    },\r\n    \"extensions\": {\r\n        \"auto_load\": true,\r\n        \"blacklist\": []\r\n    },\r\n    \"cooldowns\": {\r\n        \"default_rate\": 3,\r\n        \"default_per\": 5.0\r\n    },\r\n    \"command_permissions\": {},\r\n    \"slash_limiter\": {\r\n        \"max_limit\": 100,\r\n        \"warning_threshold\": 90,\r\n        \"safe_limit\": 95\r\n    },\r\n    \"framework\": {\r\n        \"load_cogs\": true,\r\n        \"enable_event_hooks\": true,\r\n        \"enable_plugin_registry\": true,\r\n        \"enable_framework_diagnostics\": true,\r\n        \"enable_slash_command_limiter\": true,\r\n        \"enable_shard_monitor\": true,\r\n        \"enable_shard_manager\": true\r\n    }\r\n}\r\n```\r\n\r\nConfiguration Options\r\nBasic Settings\r\nprefix (string)\r\n\r\nDefault command prefix\r\nDefault: \"!\"\r\nPer-guild overrides supported via !setprefix\r\n\r\nallow_mention_prefix (boolean)\r\n\r\nEnable @mention as command prefix\r\nDefault: true\r\nAllows users to invoke commands with @BotName command\r\nPer-guild overrides supported via !mentionprefix\r\nExample: @BotName help works like !help when enabled\r\n\r\nowner_ids (array)\r\n\r\nAdditional bot owner IDs\r\nDefault: []\r\nPrimary owner from BOT_OWNER_ID env variable\r\n\r\nauto_reload (boolean)\r\n\r\nEnable hot-reload for extensions\r\nDefault: true\r\nChecks every 30 seconds for file changes\r\n\r\nStatus Configuration\r\nstatus.type (string)\r\n\r\nActivity type shown in Discord\r\nOptions: \"playing\", \"watching\", \"listening\", \"competing\"\r\nDefault: \"watching\"\r\n\r\nstatus.text (string)\r\n\r\nStatus message with variables\r\nVariables: {guilds}, {users}, {commands}\r\nDefault: \"{guilds} servers\"\r\nExample: \"with {users} users | {guilds} servers\"\r\n\r\nDatabase Configuration\r\ndatabase.base_path (string)\r\n\r\nBase directory for database files\r\nDefault: \"./data\"\r\nContains main.db and per-guild databases\r\n\r\nLogging Configuration\r\nlogging.level (string)\r\n\r\nLogging level\r\nOptions: \"DEBUG\", \"INFO\", \"WARNING\", \"ERROR\", \"CRITICAL\"\r\nDefault: \"INFO\"\r\n\r\nlogging.max_bytes (integer)\r\n\r\nMax log file size before rotation\r\nDefault: 10485760 (10MB)\r\n\r\nlogging.backup_count (integer)\r\n\r\nNumber of backup log files to keep\r\nDefault: 5\r\n\r\nExtensions Configuration\r\nextensions.auto_load (boolean)\r\n\r\nAutomatically load all extensions on startup\r\nDefault: true\r\n\r\nextensions.blacklist (array)\r\n\r\nExtension names to skip during auto-load\r\nDefault: []\r\nExample: [\"debug_cog\", \"test_extension\"]\r\n\r\nCooldowns Configuration\r\ncooldowns.default_rate (integer)\r\n\r\nDefault number of command uses\r\nDefault: 3\r\n\r\ncooldowns.default_per (float)\r\n\r\nDefault cooldown period in seconds\r\nDefault: 5.0\r\n\r\nSlash Command Limiter\r\nslash_limiter.max_limit (integer)\r\n\r\nDiscord's hard limit for slash commands\r\nDefault: 100\r\nShould not be changed\r\n\r\nslash_limiter.warning_threshold (integer)\r\n\r\nCommand count to trigger warnings\r\nDefault: 90\r\nLogs warning at this count\r\n\r\nslash_limiter.safe_limit (integer)\r\n\r\nCommand count to start prefix-only mode\r\nDefault: 95\r\nNew extensions become prefix-only\r\n\r\nFramework Cogs\r\nframework.load_cogs (boolean)\r\n\r\nLoad framework internal cogs\r\nDefault: true\r\nDisable to use minimal framework\r\n\r\nframework.enable_event_hooks (boolean)\r\n\r\nEnable Event Hooks system\r\nDefault: true\r\n\r\nframework.enable_plugin_registry (boolean)\r\n\r\nEnable Plugin Registry system\r\nDefault: true\r\n\r\nframework.enable_framework_diagnostics (boolean)\r\n\r\nEnable Framework Diagnostics system\r\nDefault: true\r\n\r\nframework.enable_slash_command_limiter (boolean)\r\n\r\nEnable Slash Command Limiter\r\nDefault: true\r\n\r\nframework.enable_shard_monitor (boolean)\r\n\r\nEnable Shard Monitor cog\r\nDefault: true\r\nAlso controlled by `ENABLE_SHARD_MONITOR` env variable (.env takes precedence)\r\n\r\nframework.enable_shard_manager (boolean)\r\n\r\nEnable Shard Manager cog (multi-process IPC)\r\nDefault: true (but .env default is `false` which takes precedence)\r\nAlso controlled by `ENABLE_SHARD_MANAGER` env variable (.env takes precedence)\r\n\r\nCommand Permissions\r\nConfigure role-based command access:\r\n\r\n\r\n```\r\n# Grant @Moderator access to ban command\r\n!config ban @Moderator\r\n\r\n# Add multiple roles\r\n!config kick @Moderator\r\n!config kick @Admin\r\n\r\n# View current permissions\r\n!config\r\n\r\n# Remove restrictions\r\n!config ban none\r\n```\r\n### Configuration Storage:\r\n```\r\n{\r\n    \"command_permissions\": {\r\n        \"ban\": [123456789, 987654321],\r\n        \"kick\": [123456789]\r\n    }\r\n}\r\n```\r\n\r\n\r\n### Custom Prefixes\r\nSet per-guild prefixes:\r\n```\r\n# Set prefix to ?\r\n!setprefix ?\r\n\r\n# Now commands work with ?\r\n?help\r\n?stats\r\n\r\n# Slash commands always work regardless of prefix\r\n/help\r\n/stats\r\n```\r\n### Database Storage:\r\n#### Stored in guild-specific database at ./data/[guild_id]/guild.db\r\n\r\n\r\n### Environment Variables\r\nRequired .env file:\r\n\r\n\r\n\r\n```\r\n# Required\r\nDISCORD_TOKEN=your_bot_token_here\r\nBOT_OWNER_ID=your_discord_user_id\r\n\r\n# Optional: Sharding (for large bots)\r\nSHARD_COUNT=2\r\n\r\n# SHARD_IDS can be commented out\r\nSHARD_IDS=0,1\r\n\r\n# Shard Monitor\r\nENABLE_SHARD_MONITOR=true\r\nSHARD_ALERT_THRESHOLD=3\r\n\r\n# Shard Manager (multi-process/multi-server)\r\nENABLE_SHARD_MANAGER=false\r\nSHARD_IPC_MODE=server\r\nSHARD_IPC_HOST=127.0.0.1\r\nSHARD_IPC_PORT=20000\r\nSHARD_IPC_SECRET=change_me_please\r\nSHARD_CLUSTER_NAME=cluster-0\r\n```\r\n### Sharding Configuration:\r\n\r\n- `SHARD_COUNT`: Total number of shards (Discord requires sharding at 2500+ guilds)\r\n- `SHARD_IDS`: Comma-separated list of shard IDs for this process (leave empty for auto-sharding)\r\n- `ENABLE_SHARD_MONITOR`: Enable/disable real-time shard health monitoring (default: `true`)\r\n- `SHARD_ALERT_THRESHOLD`: Consecutive failures before alert fires (default: `3`)\r\n- `ENABLE_SHARD_MANAGER`: Enable/disable IPC-based multi-process sharding (default: `false`)\r\n- `SHARD_IPC_MODE`: `server` for primary cluster, `client` for secondary clusters\r\n- `SHARD_IPC_HOST`: IPC bind address (`127.0.0.1` for local, `0.0.0.0` for remote)\r\n- `SHARD_IPC_PORT`: IPC server port (default: `20000`)\r\n- `SHARD_IPC_SECRET`: Shared authentication secret (MUST match on all clusters)\r\n- `SHARD_CLUSTER_NAME`: Unique name to identify this cluster in logs and commands\r\n\r\n\r\n### 🗄️ Database System\r\n#### Architecture\r\nThe framework uses a hybrid database approach:\r\n\r\n1. Main Database (./data/main.db)\r\n  - Global bot statistics\r\n  - Command usage tracking\r\n  - Framework-wide data\r\n\r\n2. Per-Guild Databases (./data/[guild_id]/guild.db)\r\n  - Guild-specific settings\r\n  - Custom prefixes\r\n  - Extension data per guild\r\n\r\n#### Database Features\r\n✅ WAL Mode - Write-Ahead Logging for concurrent access\r\n✅ Connection Pooling - Automatic per-guild connection management\r\n✅ Automatic Backups - Created on bot shutdown\r\n✅ Orphan Cleanup - Removes connections for left guilds\r\n✅ Atomic Operations - ACID compliance\r\n\r\n\r\n#### Using the Database\r\n#### Accessing Main Database\r\n\r\n```python\r\n\r\n# Direct access to main database\r\nasync with self.bot.db.conn.execute(\r\n    \"SELECT * FROM global_stats WHERE key = ?\",\r\n    (\"some_key\",)\r\n) as cursor:\r\n    row = await cursor.fetchone()\r\n```\r\n#### Accessing Guild Database\r\n```python\r\n\r\n# Get guild-specific connection\r\nconn = await self.bot.db._get_guild_connection(guild_id)\r\n\r\n# Execute queries\r\nawait conn.execute(\r\n    \"INSERT INTO custom_table (data) VALUES (?)\",\r\n    (data,)\r\n)\r\nawait conn.commit()\r\n```\r\n#### Built-in Database Methods\r\n```python\r\n\r\n# Set guild prefix\r\nawait bot.db.set_guild_prefix(guild_id, \"?\")\r\n\r\n# Get guild prefix\r\nprefix = await bot.db.get_guild_prefix(guild_id)\r\n\r\n# Increment command usage\r\nawait bot.db.increment_command_usage(\"command_name\")\r\n\r\n# Get command statistics\r\nstats = await bot.db.get_command_stats()\r\n# Returns: [(command_name, count), ...]\r\n\r\n# Cleanup guild data\r\nawait bot.db.cleanup_guild(guild_id)\r\n\r\n# Backup databases\r\nawait bot.db.backup()  # All guilds\r\nawait bot.db.backup(guild_id)  # Specific guild\r\n\r\n```\r\n\r\n\r\n\r\n### Database Schema\r\n#### Main Database\r\nglobal_stats\r\n```\r\n\r\nCREATE TABLE global_stats (\r\n    key TEXT PRIMARY KEY,\r\n    value TEXT,\r\n    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\r\n)\r\n```\r\n\r\n#### Guild Database\r\n#### guild_settings\r\n```\r\nCREATE TABLE guild_settings (\r\n    key TEXT PRIMARY KEY,\r\n    value TEXT,\r\n    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\r\n)\r\n```\r\n#### command_stats\r\n\r\n\r\n\r\n\r\n```\r\nCREATE TABLE command_stats (\r\n    command_name TEXT PRIMARY KEY,\r\n    usage_count INTEGER DEFAULT 0,\r\n    last_used TIMESTAMP\r\n)\r\n```\r\n\r\n### Database Maintenance\r\n#### Automatic Maintenance (Every Hour):\r\n\r\n- Cleans up orphaned connections\r\n- Expires prefix cache entries\r\n- Removes pycache directories\r\n- Logs maintenance actions\r\n\r\nManual Cleanup:\r\n```\r\n!cleanup\r\n```\r\nView Database Stats:\r\n```\r\n!dbstats\r\n\r\n```\r\n\r\n\r\n### 📊 Framework Cogs System\r\n#### Overview\r\n**Framework cogs are internal system components that provide core functionality. They're located in ./cogs directory and are automatically loaded on startup (if enabled in config).**\r\n\r\n\r\n#### Event Hooks System\r\nFile: cogs/event_hooks.py\r\n\r\n**What It Does**\r\n- Internal event system for framework lifecycle events\r\n- Priority-based callback execution\r\n- Asynchronous queue processing (1000 event capacity)\r\n- Execution history tracking (100 total, 20 per event)\r\n- Worker task for async event processing\r\n\r\n#### Available Events: \r\n\r\n### Event Description Table\r\n\r\n| Event Name            | Description                       | Parameters                               |\r\n|-----------------------|-----------------------------------|-------------------------------------------|\r\n| bot_ready             | Bot becomes ready                 | —                                         |\r\n| guild_joined          | Bot joins a guild                 | guild                                     |\r\n| guild_left            | Bot leaves a guild                | guild                                     |\r\n| command_executed      | Command is executed               | command_name, author, guild               |\r\n| command_error         | Command error occurs              | command_name, error, author, guild        |\r\n| extension_loaded      | Extension is loaded (custom)      | extension_name                            |\r\n| extension_unloaded    | Extension is unloaded (custom)    | extension_name                            |\r\n\r\n\r\n\r\n\r\n### Atomic File System\r\n\r\nFile: `atomic_file_system.py`\r\n\r\n**What It Does**\r\n- Thread-safe atomic file operations with zero data corruption\r\n- LRU cache system (300s TTL, 1000 entry limit)\r\n- Automatic file lock management with cleanup\r\n- Retry logic for write operations (3 attempts)\r\n- Comprehensive diagnostics and metrics tracking\r\n\r\n**Key Features:**\r\n\r\n**Atomic Write Protection**\r\n- Tempfile-based writes prevent partial updates\r\n- Automatic retry on permission errors\r\n- Windows/Linux compatible file operations\r\n- Cross-platform atomic move operations\r\n\r\n**LRU Cache System**\r\n- Configurable TTL (default: 300 seconds)\r\n- Automatic eviction when full (max 1000 entries)\r\n- Cache hit rate tracking\r\n- Manual invalidation support\r\n- Thread-safe cache access\r\n\r\n**Lock Management**\r\n- Per-file lock acquisition\r\n- Automatic cleanup of inactive locks (threshold: 500)\r\n- Lock age tracking for diagnostics\r\n- Deadlock prevention\r\n\r\n**Performance Metrics**\r\n- Read/write operation counters\r\n- Cache hit rate calculation\r\n- Failure rate monitoring\r\n- Lock cleanup statistics\r\n\r\n**Health Monitoring**\r\n- Real-time failure rate tracking\r\n- Three-tier status: Healthy (\u003c1%), Degraded (1-5%), Critical (\u003e5%)\r\n- Operation history tracking\r\n\r\n\r\n\r\n\r\n### Using Atomic File System\r\n\r\n**View System Statistics:**\r\n```bash\r\n!atomicstats\r\n```\r\nShows:\r\n- Cache size and hit rate\r\n- Active file locks\r\n- Total read/write operations\r\n- Failure rates and health status\r\n- System uptime\r\n\r\n**Run Diagnostic Tests:**\r\n```bash\r\n!atomictest\r\n```\r\nPerforms:\r\n1. Atomic write test\r\n2. Read test without cache\r\n3. Read test with cache (verifies caching)\r\n4. Concurrent write test (10 simultaneous writes)\r\n5. Cache invalidation test\r\n\r\n**Performance Metrics:**\r\n- Cache hit rate \u003e70% is healthy\r\n- Active locks should be \u003c100 normally\r\n- Failure rate should be \u003c1%\r\n- Lock cleanup runs automatically at 500+ locks\r\n\r\n\r\n\r\n\r\n\r\n### Using Event Hooks\r\n\r\n**Register a Hook:**\r\n```python\r\n# Register hook with priority\r\nbot.register_hook(\"bot_ready\", my_callback, priority=10)\r\n\r\n# Hook callback signature\r\nasync def my_callback(bot, **kwargs):\r\n    # bot: Bot instance\r\n    # kwargs: Event-specific parameters\r\n    pass\r\n```\r\n\r\n**Hook ID Format:**\r\n- Format: `event_name:callback_name`\r\n- Example: `bot_ready:on_bot_ready`\r\n- Used for disabling/enabling specific hooks\r\n\r\n**View Registered Hooks:**\r\n```bash\r\n!eh_list\r\n```\r\nShows:\r\n- All registered hooks by event\r\n- Priority levels\r\n- Execution counts and failure counts\r\n- Average execution time\r\n- Status indicators:\r\n  - 🔴 - Hook disabled manually\r\n  - ⚠️ - Circuit breaker open\r\n  - No icon - Working normally\r\n\r\n**View Execution History:**\r\n```bash\r\n# Last 10 executions\r\n!eh_history\r\n\r\n# Last 30 executions\r\n!eh_history 30\r\n```\r\n\r\n**Manage Problematic Hooks:**\r\n```bash\r\n# Disable a hook that's causing issues\r\n!eh_disable bot_ready:on_bot_ready\r\n\r\n# Re-enable when fixed\r\n!eh_enable bot_ready:on_bot_ready\r\n\r\n# Reset circuit breaker (if hook keeps failing)\r\n!eh_reset_circuit command_executed:log_command\r\n```\r\n\r\n**Set Alert Channel:**\r\n```bash\r\n# Set current channel\r\n!eh_alert_channel\r\n\r\n# Set specific channel\r\n!eh_alert_channel #hook-alerts\r\n```\r\n\r\n**Automatic Alerts Sent For:**\r\n- Queue full (dropped eve","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheholyonez%2Fdiscord-bot-framework","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftheholyonez%2Fdiscord-bot-framework","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftheholyonez%2Fdiscord-bot-framework/lists"}