Advanced • Modular • Production-Ready
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.
**✨ NEW (v1.9.0.0): AI Assistant dashboard tab + EventHooksCreater overhaul + Plugin Registry upgrade**
Brand-new GeminiServiceHelper cog adds an AES-256-CBC encrypted AI chat tab directly inside the Live Monitor dashboard — no slash commands required. EventHooksCreater fully implemented (leveling, tickets, voice channels, scheduled announcements, dynamic voice) with new `/hooks` slash commands. Plugin Registry now enforces dependencies for real, persists config across restarts, and paginates plugin lists.
**✨ PREVIOUS (v1.8.0.0): Framework Diagnostics & GeminiService overhaul + Backup completeness**
Framework Diagnostics gains persistent alert channel, rolling error-rate, rolling lag average, `/fw_history`, `/fw_errors`. GeminiService gets real rate-limiting, TTL cache, owner-only file security. Backup/Restore now fully restores forum channels, stage channels, emojis, stickers, and server settings with base64 image capture.
**✨ PREVIOUS (v1.7.2.0): Bot Status Rotator**
Fully configurable bot status rotation with multiple statuses, custom intervals, and dynamic variables, all manageable from the web dashboard.
**🎯 PREVIOUS: @Mention Prefix & Per-Guild Configuration (v1.6.1.0)**
Users can now invoke commands using @BotName, and server admins can configure bot behavior per-guild with the new Guild Settings cog!
🌐 Website
🚀 ZORYX DashHost - Host your Zoryx Discord Bot Framework dashboard for FREE
No PHP hosting required • Instant setup • All features included
🔗 Get Started • 📺 Watch Tutorial
Click to expand
- Important Notice / Data Protection
- 🌟 What Makes This Framework Special
- 🎯 Core Features
- 📋 Requirements
- 🐳 Docker Setup
- 🚀 Quick Start
- 📁 Project Structure
- 🎮 Built-in Commands
- 👥 User Commands
- ⚙️ Guild Settings Commands
- 🛒 Marketplace Commands
- Atomic File System Commands
- 🔌 Plugin Registry Commands
- 📊 Framework Diagnostics Commands
- 🪝 Event Hooks Commands
- 📡 Live Monitor Commands
- 🤖 AI Assistant Commands
- 📊 Shard Monitor Commands
- 🌐 Shard Manager Commands
- 💾 Backup & Restore Commands
- 🔧 Owner-Only Commands
- 🛒 Extension Marketplace
- 🔧 Creating Extensions
- ⚙️ Configuration Guide
- 🗄️ Database System
- 📊 Framework Cogs System
- 📊 Shard Monitor System
- 🌐 Shard Manager System
- 💾 Backup & Restore System
- 🛠 Troubleshooting
- 📈 Performance Tips
- 📜 License
- 🤝 Contributing
- 💬 Support
- 📚 Additional Resources
- 🎉 Showcase
- 👤 Author
Atomic File Operations
- Thread-safe file handling with built-in LRU caching (300s TTL, 1000 entry limit)
- Automatic lock management with cleanup threshold (500 locks)
- Zero data corruption through tempfile-based atomic writes
- Cache invalidation and TTL-based expiration
- Cross-platform compatibility (Windows/Linux)
Advanced Database Management
- Per-guild SQLite databases with automatic connection pooling
- WAL (Write-Ahead Logging) mode for concurrent access
- Automatic backup system on shutdown
- Orphaned connection cleanup
- Global and guild-specific data separation
- Command usage analytics and statistics tracking
Safe Log Rotation
- Automatic size-based rotation (10MB default)
- Configurable backup count (5 backups default)
- Age-based cleanup (30-day retention)
- Dual-mode logging: permanent + current session
- Structured logging with timestamps and levels
Hot-Reload System
- File-watching based auto-reload (30s interval)
- Extension modification timestamps tracked
- Zero downtime during development
- Load time tracking per extension
- Graceful error handling during reload
Intelligent Extension Loading
- Automatic whitespace handling (converts spaces to underscores)
- Extension blacklist support
- Load time tracking and diagnostics
- Conflict detection through Plugin Registry
- Dependency resolution system
Hybrid Command System
- Seamless prefix and slash command support
- @Mention prefix support - Users can invoke commands with
@BotName command - Per-guild mention prefix configuration - Admins control @mention availability per server
- Automatic command type indicators in help menu
- Slash command limit protection (100 command cap)
- Graceful degradation to prefix-only mode
- Visual indicators: ⚡ (hybrid), 🔸 (prefix-only), 🔹 (limit reached)
- Help menu adapts to show available invocation methods
Web-Based Monitoring Dashboard
- Real-time bot status via Live Monitor cog (~12,000+ lines)
- 20 dashboard tabs: Dashboard, Commands, Plugins, Hooks, Hook Creator, Files, File Browser, Chat, Guilds, Events, System, Invite, Marketplace, Tickets, Database, Backups, Shards, Roles, Security, Credits
- Remote extension management (load/unload/reload from browser)
- Full file browser with read/write/delete operations
- Chat console to send Discord messages from dashboard
- Role-based access control (Owner/Helper/Visitor)
- One-command dashboard deployment (
/livemonitor quickstart) - 2-second update interval for near real-time data
- Requires PHP hosting (Strato, Hostinger, any cPanel host)
Event Hooks System (cogs/event_hooks.py)
- Internal event system for framework lifecycle events
- Priority-based callback execution
- Asynchronous queue processing:
- 1000 event capacity with backpressure (5s wait before drop)
- Queue delay tracking for performance monitoring
- Worker auto-restart on crash (up to 10 attempts)
- Circuit Breaker Pattern:
- Opens after 5 failures in 5 minutes
- Disables hook for 60 seconds
- Automatic recovery with manual override
- Prevents cascading failures
- Hook timeout protection:
- 10-second timeout per hook execution
- Prevents blocking the entire queue
- Timeout triggers circuit breaker
- Performance monitoring:
- Execution time tracking per hook
- Success/failure counts
- Average execution time calculations
- Queue delay metrics
- Hook management:
- Disable/enable hooks without code changes
- Status indicators (🔴 disabled,
⚠️ circuit open) - Manual circuit breaker reset
- Alert system:
- Queue full notifications
- Circuit breaker triggers
- Worker crash alerts
- Configurable alert channel
- Hook execution history (100 total, 20 per event)
- Built-in events: bot_ready, guild_joined, guild_left, command_executed, command_error
- Custom event emission support
Automation Creator (cogs/EventHooksCreater.py) — v1.9.0.0 (full overhaul, 5.5 → 9.0+)
- User-defined automations built on top of Discord events — create, manage, and monitor from Discord commands or the Live Monitor Hook Creator tab
- Implemented automation templates:
leveling_system— XP per message with per-user cooldown, level-up announcements, role rewards at configurable thresholdsscheduled_announcement— recurring message/embed to a channel at a configurable interval (hours); implemented as a per-hookasyncio.Taskticket_system— private text channel created per user on emoji reaction; support role granted access; reaction removed after ticket creationvoice_activity_tracker— logs join, leave, and mute/unmute events to a log channel; each event type independently togglabledynamic_voice_channels— temporary voice channel created when a user joins a trigger channel; auto-deleted when empty
- Advanced Condition Engine — hooks respect conditions (time_range, day_of_week, role_hierarchy, message_count, user_age, custom_variable) — previously dead code, now evaluated at the top of every handler
- Action pipeline wired in —
_execute_actionsnow called by all handlers (send_message, add_role, remove_role, timeout, send_dm, webhook, create_role, delay, trigger_hook) - Safe math evaluator —
eval()replaced with AST-based parser; only numeric constants and+,-,*,/permitted - No listener accumulation —
_registered_hook_ids: setprevents duplicate listeners on reload - Batch I/O — dirty flag + 60-second
auto_savebackground task instead of writing on every execution - New slash commands:
/hooks list,/hooks info,/hooks delete,/hooks toggle,/hooks create
Plugin Registry (cogs/plugin_registry.py) — v1.9.0.0
- Automatic metadata extraction from extensions with error logging
- Dependency validation and enforcement (v1.9.0.0 — now blocking):
- Version comparison support (
>=,>,==,<=,<) - Missing dependency detection
- Version mismatch detection
register_plugin()refuses to register plugins with unmet dependencies when enforcement is enabled (was advisory-only before)
- Version comparison support (
- Conflict detection and prevention:
- Bidirectional conflict checking
- Automatic conflict alerts
- Circular dependency detection:
- Prevents infinite dependency loops
- Shows full dependency cycle path
- Hook metadata scanning (v1.9.0.0):
__provides_hooks__and__listens_to_hooks__module attributes read during auto-scan
- Command and cog enumeration
- Load time tracking per plugin
- Auto-registration on extension load — falls back to direct
bot.add_listener()if EventHooks is absent - Persistent config (v1.9.0.0): alert channel,
enforce_dependencies, andenforce_conflictspersisted to./data/plugin_registry_config.json— survive restarts - Paginated list (v1.9.0.0):
/pr_listusesPluginListViewwith Prev/Next buttons, 10 plugins per page - Alert system:
- Configurable alert channel
- Validation issue warnings
- Scan error notifications
- Status indicators:
- ✅ Valid plugin
⚠️ Warnings (conflicts, scan errors)- ❌ Missing dependencies
- 🔄 Circular dependencies
- Toggleable enforcement:
- Enable/disable dependency checking
- Enable/disable conflict checking
Framework Diagnostics (cogs/framework_diagnostics.py) — v1.8.0.0
- Real-time system health monitoring with three-tier status (healthy/degraded/critical)
- CPU, memory, threads, open files, and connections tracking
- Rolling 1-hour error rate — computed from a delta of the last 12 × 5-minute snapshots (not lifetime totals); shows
(rolling 1h)or(lifetime)depending on available data - Rolling average loop lag — averages the last 10 readings to eliminate single-tick jitter; annotated as
(avg 10s)in the embed - Configurable loop lag threshold via
FW_LOOP_LAG_THRESHOLD_MSenv var (default: 500 ms) bot.metricsis optional — all accesses usegetattrfallbacks; cog loads and runs even ifbot.metricsis absent- Uptime and latency monitoring; extension load time analysis
- Persistent alert channel — saved to
./data/framework_diagnostics_config.jsonand restored on restart (no longer needs re-setting after every reboot) - Automatic diagnostics run every 5 minutes; alerts sent for critical/degraded health, loop lag, and consecutive write failures
- Health check history — last 48 entries (4 hours) kept in memory and persisted to
./data/framework_health_history.json - Error history — last 20 command errors stored in a deque with timestamp and command name
- New commands (v1.8.0.0):
/fw_history [entries]— shows last N (1–20) health snapshots with timestamp, status, error rate, loop lag/fw_errors— shows the last 20 command errors recorded in the current session
- Comprehensive diagnostics saved to JSON files:
framework_diagnostics.json— Full system reportframework_health.json— Real-time health metricsframework_diagnostics_config.json— Persistent config (alert channel)framework_health_history.json— Persistent health history
Slash Command Limiter (cogs/slash_command_limiter.py)
- Intelligent Discord 100-command limit management with automatic conversion
- Thread-safe singleton pattern - Only one instance allowed per bot
- Configurable thresholds:
- Warning threshold (default: 90/100)
- Safe limit (default: 95/100)
- Hard limit (100/100)
- Multi-layered interception system:
tree.add_command()monkey-patching for dynamic command blockingCog._inject()interception for cog-level slash stripping- Prevents commands from ever reaching Discord's API
- Intelligent command type detection:
- ✅ Skips
HybridCommand- Already have prefix support, no conversion needed - ✅ Skips
commands.Command- Already prefix-only - ✅ Skips
app_commands.Group- Command groups cannot be converted - 🔄 Converts
app_commands.Command- Pure slash commands to prefix equivalents
- ✅ Skips
- Advanced parameter conversion system:
- Automatic type detection from function signatures
- Discord object conversion:
discord.Member/discord.User- Converts @mentions and IDs to Member objectsdiscord.Role- Converts role mentions and IDs to Role objectsdiscord.TextChannel/discord.VoiceChannel- Converts #channel mentions to Channel objects
- Primitive type handling:
int- String to integer conversionfloat- String to float conversionbool- Handles "true", "yes", "1", "y", "on" variations
- Intelligent error messages:
- Missing required parameters with usage examples
- Type conversion failures with helpful hints
- Guild context validation (DM protection)
- Production-ready MockInteraction wrapper:
- Emulates full
discord.Interactionobject for seamless compatibility - Handles
interaction.response.send_message(),interaction.followup.send() - Supports embeds, files, views (buttons/dropdowns), and all Discord features
- Proper attribute forwarding:
guild,user,channel,permissions,command - Modal support with graceful degradation message
- Emulates full
- Comprehensive tracking and logging:
- Blocked commands registry with timestamps and caller info
- Converted commands tracking with conversion type metadata
- Warning threshold system with automatic reset
- Debug logging to
botlogs/debug_slashlimiter.log - Caller tracking shows which file/line triggered blocking
- Self-protection mechanisms:
- Limiter's own commands (
slashlimit) exempted from blocking - Async startup to prevent bot hang during initialization
- Non-blocking background tasks for scanning
- Graceful degradation on conversion failures
- Limiter's own commands (
- User-friendly status display (
/slashlimit):- Visual progress bars showing command usage
- Color-coded status (green=safe, yellow=warning, red=critical)
- Lists blocked and converted commands
- Shows system status and verification state
- Integration with help system:
- Command type indicators: ⚡ (hybrid), 🔸 (prefix-only), 🔹 (converted from slash)
- Automatic updates when commands are converted
- Real-time command count tracking
🤖 AI Assistant — Slash Commands (cogs/GeminiService.py) — v1.8.0.0
- Powered by Google Gemini (model configurable via
GEMINI_MODELenv var, default:gemini-2.5-flash-lite) - Deep Contextual Awareness:
- Dynamically pulls real-time data from
PluginRegistry,FrameworkDiagnostics,SlashCommandLimiter,EventHooks, andEventHooksCreater - File content analysis (owner-only, path-traversal-safe), database schema querying,
README.mdsmart search
- Dynamically pulls real-time data from
- Security (v1.8.0.0):
fileaction is bot owner only;@commands.cooldownreplaced with manual_user_cooldownsdict (was silently ignored for pure slash commands) - Rate Limiting: 15s per-user cooldown, max 3 simultaneous requests, both fire before
interaction.response.defer()for immediate ephemeral feedback - Performance: 60-second TTL cache for
diagnose,plugins,slash,hooks,automations; context capped at 8,000 chars; truncation notice for responses over 4,096 chars - Interactive Help Menu: 12-page paginated button-driven guide (
/ask_zdbf action:help) - Actions:
help,framework,plugins,diagnose,database,file,extension,permission,slash,hooks,automations,readme
🤖 AI Assistant — Dashboard Chat (cogs/GeminiServiceHelper.py) — v1.9.0.0 ✨ NEW
- Encrypted AI chat embedded directly in the Live Monitor dashboard — no slash commands required, accessed from the AI Assistant tab
- AES-256-CBC end-to-end encryption: server-side via Python
cryptographylibrary, client-side via native Web Crypto API (crypto.subtle) — no CDN dependencies, no CSP conflicts - Per-user encrypted sessions persisted to
./data/gemini_dashboard_sessions.json; history survives bot restarts - Context tools auto-injected based on message keywords:
- Framework Info — live stats (version, guild count, cog list)
- Cog/Extension Info — description + commands for any loaded cog (name detected in message)
- File Structure — directory map of root,
cogs/,data/ - README Search — hierarchical breadcrumb parsing, 3,000-char budget, top 4 scored sections
- File Reading — sandboxed to root
*.py,cogs/*.py,data/*;.envand sensitive JSON files always blocked - Capabilities — triggered by "what can you do" style queries
- Attach File button with live-filter autocomplete dropdown: type a filename, autocomplete filters against all allowed files, press Enter to attach as a chip; multiple files supported (up to 3 read per message)
- Smart scroll, optimistic bubbles, typing indicator, lock + Cancel, markdown rendering (fenced code, headers, bold, italic, inline code — XSS-safe, no external deps)
- Capabilities popup — animated glassmorphism modal listing what the AI can and cannot do
- 4 dashboard permission flags:
view_gemini_chat,action_gemini_send,action_gemini_clear_history,action_gemini_config - Requires:
pip install cryptography(added torequirements.txt)
⚙️ Guild Settings (cogs/guild_settings.py)
- Per-Guild Configuration Management:
- Server administrators control bot behavior independently for their server
- Settings stored in per-guild database with automatic persistence
- Graceful fallback to global configuration if no guild-specific setting exists
- @Mention Prefix Configuration:
- Enable/disable @mention prefix (
@BotName command) per server - Check current status with detailed command invocation methods display
- Independent control over user experience preferences
- Enable/disable @mention prefix (
- Comprehensive Settings Dashboard:
- View all server configuration at a glance with
!serversettings - Shows custom prefix, mention prefix status, and server information
- Lists all available command invocation methods for users
- View all server configuration at a glance with
- Administrator-Only Access:
- All configuration commands require Administrator permission
- Guild context validation (cannot be used in DMs)
- Comprehensive error handling with clear feedback
- Extensible Architecture:
- Built on modular design for easy addition of more guild settings
- Clean separation of concerns with dedicated cog
- Full audit logging for all configuration changes
- User-Friendly Interface:
- Rich embed responses with visual indicators
- Clear success/error messages
- Status checking before changes
- Commands:
!mentionprefix enable/disable/status- Control @mention prefix!serversettings- View all server configuration
📊 Shard Monitor (cogs/shard_monitor.py)
- Real-Time Shard Health Monitoring (Bot Owner Only)
- Interactive dashboard with button navigation (Overview, Health, Latency, Events tabs)
- Per-shard metrics: latency, uptime, messages, commands, connects, disconnects
- Automatic health checks every 60 seconds with three-tier status (🟢🟡🔴)
- Configurable alert system with persistent channel configuration
- Comprehensive Health Checks:
- Latency threshold detection (>1s warning, >2s critical)
- Activity monitoring (no events for 5+ minutes triggers warning)
- Consecutive failure tracking with configurable threshold
- Disconnect/reconnect tracking with downtime calculation
- Background Tasks:
- Metrics collection every 30 seconds
- Health check evaluation every 60 seconds
- Persistent metrics saved to disk every 5 minutes
- Event Tracking:
on_shard_connect,on_shard_disconnect,on_shard_resumed,on_shard_ready- Per-shard message and command counters
- Guild join/leave tracking per shard
- .env Toggleable:
ENABLE_SHARD_MONITOR=true/false - Commands:
!shardmonitor- Interactive dashboard with button navigation!sharddetails <id>- Deep-dive into a specific shard!shardhealth- Quick health report for all shards!shardalerts #channel [threshold]- Configure alert system!shardreset [shard_id]- Reset collected metrics
🌐 Shard Manager (cogs/shard_manager.py)
- Multi-Process & Multi-Server Sharding (Bot Owner Only)
- IPC (Inter-Process Communication) system for cross-shard coordination
- Run shards across multiple processes on the same machine or different servers
- TCP-based length-prefixed protocol with authentication
- Automatic reconnection with exponential backoff (5s → 120s max)
- Cluster Architecture:
- One primary cluster (IPC server mode) + one or more secondary clusters (IPC client mode)
- Shared secret authentication prevents unauthorized connections
- Heartbeat system with 30-second intervals for connection health
- Automatic cluster join/leave notifications
- Cross-Shard Communication:
- Stats broadcasting between all clusters every 60 seconds
- Global guild/user/shard count aggregation
- Broadcast messaging to all connected clusters
- Safe preset query system (no arbitrary code execution)
- Security:
- Authentication via shared secret (SHARD_IPC_SECRET)
- 1MB message size limit, nonce-based deduplication
- 10-second auth timeout for unauthenticated connections
- .env Toggleable:
ENABLE_SHARD_MANAGER=true/false(disabled by default) - Commands:
!clusters- Show all connected clusters with stats and health!ipcstatus- IPC connection diagnostics!broadcastmsg <message>- Broadcast to all clusters
💾 Backup & Restore (cogs/backup_restore.py) — v2.2.0 (v1.8.0.0)
- Full Guild Configuration Snapshots (Administrator / Bot Owner)
- Captures roles, channels, categories, permissions, emojis, stickers, server settings, bot settings
- Member role assignments — saves which members have which roles (requires Members Intent)
- Supports text, voice, forum, and stage channels with full permission overwrites
- Images stored as base64 at capture time (v1.8.0.0) — emoji images, sticker images, server icon, and server banner are downloaded and embedded as base64 in the backup JSON; CDN URLs alone are useless after content is deleted
- Atomic file system integration for zero-corruption storage
- Interactive Dashboard (
/backup) with 5 tabs:- 📊 Overview — Storage, latest backup, server stats, cooldown timer
- 📦 Backups — Paginated list with member snapshot counts
- 🔍 Compare — Drift analysis: current state vs latest backup
- 📜 Audit Log — All backup operations tracked
- 📈 Analytics — Trends, frequency, top creators
- 🗑️ Quick Delete — Dropdown selector from dashboard with pin protection
- Selective Restore Engine (v1.8.0.0 — now covers everything backup captures):
- Toggle components: roles, categories, channels, member roles, bot settings, emojis, stickers, server settings
- Forum channels — restored via
guild.create_forum(), skips duplicates by name - Stage channels — restored via
guild.create_stage_channel(), skips duplicates by name - Emojis — restored from embedded base64 via
guild.create_custom_emoji(); managed emojis skipped - Stickers — restored from embedded base64 via
guild.create_sticker(); requires re-backup for entries from before v1.8.0.0 - Server settings — restores name, verification level, default notifications, explicit content filter, AFK channel/timeout, premium progress bar via
guild.edit() - Server icon — restored from embedded base64 via
guild.edit(icon=bytes) - Role Sync toggle (off by default): full rewind adds missing + removes extra roles per member
- Creates only missing items, reapplies member role assignments, recreates permission overwrites
- Real-time progress updates and detailed results
- Auto-Backup Scheduler with per-guild intervals, pinning, notes, integrity verification
- 13 Hybrid Commands:
!backup/!backupcreate/!backuprestore/!backupview/!backupdelete/!backuplist!backuppin/!backupnote/!backupverify/!backupschedule/!backupdiff!backupexport/!backupstats(Bot Owner only)
📡 Live Monitor (cogs/live_monitor.py)
- Web-based dashboard for real-time bot monitoring and remote management
(~12,000+ lines of functionality) - Acts as a bridge between the running Discord bot and an external PHP-powered monitoring interface
⚠️ IMPORTANT: The Credits tab and visual design are © 2025 TheHolyOneZ
These elements are NOT covered by the MIT license and MUST remain visible and unmodified
📺 YouTube Tutorial & Showcase
The full video tutorial is now live 🎉
It provides a complete walkthrough of the Live Monitor dashboard, showcases all features in action, and includes a step-by-step setup guide.👉 Watch here:
https://www.youtube.com/watch?v=ir3AsxZOshw
Server Requirements:
- PHP 7.4+ hosting (shared hosting works fine - e.g., Strato, Hostinger, Bluehost, any cPanel host)
- SQLite3 PHP extension (usually pre-installed)
- HTTPS recommended for security
- No database server required (uses SQLite files)
Dashboard Tabs (21 total):
| Tab | Description |
|---|---|
| Dashboard | Real-time bot stats, latency, uptime, guild/user counts |
| Commands | All prefix/slash/hybrid commands with usage stats |
| Plugins & Extensions | Loaded extensions, dependencies, conflicts, versions |
| Event Hooks | Hook status, circuit breakers, execution metrics |
| Hook Creator | Create custom event hooks from the dashboard |
| File System | Directory statistics, cache hits/misses, file counts |
| File Browser | Full file explorer with read/write/delete/rename/create |
| Chat Console (EXPERIMENTAL) | Send messages to Discord channels from dashboard |
| Guilds / Servers | All servers with member counts, channels, join dates |
| Events | Recent command executions, errors, guild joins/leaves |
| System | CPU, memory, threads, connections, platform info |
| Bot Invite Helper | Generate invite links with permission calculator |
| Marketplace | Browse and install extensions from the marketplace |
| Tickets | Support ticket management and transcripts |
| Database | Browse guild SQLite databases and tables |
| Backup & Restore | Guild snapshot management, scheduled backups, restore operations |
| Shard Manager | Real-time shard monitoring, IPC clusters, health diagnostics |
| Roles & Access | Manage dashboard user roles (Owner/Helper/Visitor) |
| Security & Logs | Audit logs, login history, security events |
| AI Assistant ✨ | AES-256-CBC encrypted Gemini chat — file attach, autocomplete, markdown rendering |
| Credits | Framework attribution (required to remain visible) |
Generated PHP Files (quickstart creates these in ./live_monitor_website/):
| File | Purpose |
|---|---|
index.php |
Main dashboard interface with all tabs |
receive.php |
Receives bot data via HTTP POST |
get_commands.php |
Bot polls this for pending commands |
send_command.php |
Dashboard sends commands to bot |
lm_bootstrap.php |
Core initialization and config |
lm_db.php |
SQLite database helper functions |
lm_auth.php |
Authentication and session management |
setup.php |
First-time claim wizard |
login.php |
Discord OAuth login page |
oauth_callback.php |
OAuth callback handler |
logout.php |
Session logout handler |
owner_audit.php |
Admin audit log viewer |
owner_roles.php |
Role management panel |
owner_db.php |
Database management panel |
backup_dashboard.php |
Bot backup interface |
Slash Command (/livemonitor):
/livemonitor action:<choice> [url:<text>] [interval:<number>]
Actions:
• Quick Start (Setup + Files) - Generate dashboard files and configure
• Status - Show current configuration and connection status
• Enable - Start sending data to dashboard
• Disable - Stop data transmission
• Get Files - Regenerate dashboard files
Prefix Command (!livemonitor):
!livemonitor <action> [url] [interval]
• !livemonitor status
• !livemonitor quickstart https://yoursite.com/monitor
• !livemonitor enable
• !livemonitor disable
• !livemonitor files
Comprehensive data collection:
- Bot metadata (username, ID, guilds, users, latency, uptime, loaded cogs/extensions)
- System resources via
psutil(CPU%, memory MB/%, threads, open files, network connections, platform) - Guild summaries with member counts, text channels (with NSFW status), owner info, join dates
- Command usage statistics with execution counts, last used timestamps, error tracking
- Integration status of framework cogs (EventHooks, SlashLimiter, PluginRegistry, FrameworkDiagnostics)
- Atomic File System cache stats (hits, misses, active locks, read/write counts)
- Health metrics from FrameworkDiagnostics when available
- Detailed plugin information via PluginRegistry integration
- Available extensions scan from
./extensionsdirectory - Framework version info and documentation links
- Event logging system:
- Listens to:
on_command,on_command_error,on_guild_join,on_guild_remove,on_message,on_app_command_completion - Configurable event log capacity (
_max_event_log: 1000 entries) - Hook execution history (
_max_hook_execution_log: 1000 entries) - Message activity aggregation for engagement metrics
- Listens to:
- Remote command execution from web dashboard:
| Command | Permission | Description |
|---|---|---|
reload_extension |
Helper+ | Hot-reload an extension |
load_extension |
Helper+ | Load a new extension |
unload_extension |
Helper+ | Unload an extension |
clear_cache |
Helper+ | Clear bot caches |
write_file |
Helper+ | Write/create files |
read_file |
Helper+ | Read file contents |
list_dir |
Helper+ | List directory contents |
rename_file |
Helper+ | Rename files |
create_dir |
Helper+ | Create directories |
delete_path |
Helper+ | Delete files/directories |
send_chat_message |
Helper+ | Send message to Discord channel |
shutdown_bot |
Owner | Gracefully stop the bot |
leave_guild |
Owner | Leave a Discord server |
backup_bot_directory |
Owner | Create bot backup archive |
fetch_marketplace_extensions |
Permission | Browse marketplace |
download_marketplace_extension |
Permission | Download from marketplace |
- Role-based access control:
- Owner - Full access to all dashboard features including shutdown
- Helper - Extension management, file operations, chat console
- Visitor - Read-only access, view chat history
- Granular permissions:
control_core,control_plugins,control_files,control_chat,control_hooks,control_guilds,control_backup,control_marketplace
- Task loop system (
send_status_loop):- 2-second update interval for near real-time monitoring
- Multi-payload JSON packaging (core, commands, plugins, hooks, filesystem, etc.)
- HTTP POST to configured
receive.phpendpoint - Command polling from
get_commands.phpendpoint aiohttpclient session management with configurable timeouts- Failure tracking (
send_failures) with success state (last_send_success) - Graceful task cancellation on
asyncio.CancelledError - Asset syncing (branding images) to remote server
- Configuration (
data/live_monitor_config.json):enabled- Toggle monitoring on/offwebsite_url- Dashboard URLsecret_token- Bot↔Server authentication tokensetup_token- One-time dashboard claim tokenupdate_interval- Seconds between updates (5-60)
- Thread-safe file operations:
asyncio.Lock(_fileops_lock) prevents race conditionsasyncio.to_threadfor blocking I/O operations- Response tracking via
_fileops_responsedictionary - Concurrent command execution with
asyncio.create_task
- Security features:
- Token-based API authentication (32-byte cryptographic tokens)
- Discord OAuth integration for dashboard login
- One-time setup token prevents unauthorized claiming
- Role-based command restrictions
- Audit logging for all sensitive operations
- HTTPS recommended for production
Direct Extension Installation
- Browse official extensions from within Discord
- Search by keywords, categories, or status
- One-click installation with confirmation
- Automatic file writing to
./extensionsdirectory - Post-install instructions with load commands
ZygnalID System
- Unique 16-character bot identifier
- Automatic generation on first use
- Required for extension downloads
- Enables dedicated support and tracking
- Stored securely in
./data/marketplace/ZygnalID.txt
License Agreement
- Mandatory acceptance before marketplace access
- Per-user tracking of acceptance
- Usage restrictions enforcement
- Extension-specific licensing support
- Terms displayed in interactive embed
Dependency Management
!marketplace fixdepscommand- Automatic log parsing for
ModuleNotFoundError - pip-based dependency installation
- Success/failure reporting per package
- Duplicate installation prevention
Advanced Features
- Extension categories: Working, Beta, Broken
- Custom URL support for extensions
- Version tracking and display
- Author attribution
- Extension status indicators
- Pagination for large lists (5 per page)
- Dropdown menus for selection
- Cache system (300s TTL) for API calls
- Rate limit handling with retry logic
Interactive Help System
- Dropdown-based category navigation
- Pagination for large command lists (5 per page)
- Visual command type indicators
- Automatic cog organization
- User-specific interaction validation
- Credits button with framework info
- Dynamic back navigation
- Real-time command count per category
Rich Embeds Everywhere
- Color-coded responses (success=green, error=red, warning=yellow)
- Consistent styling across all commands
- Timestamp inclusion
- Footer information
- Thumbnail support
- Field-based organization
- Progress bars for visual feedback
Auto-Delete Messages
- Configurable delete timers (5-15s)
- Success message cleanup
- Error message cleanup
- Reduces channel clutter
- User-friendly experience
Multi-Tier Permission System
- Bot Owner: Full access (from BOT_OWNER_ID env variable)
- Guild Owner: Server management commands
- Role-Based: Per-command role requirements
- Discord Permissions: Native permission integration
- Hardcoded Restrictions: Owner-only command list
Interaction Security
- User-specific button/dropdown validation
- Interaction author verification
- Ephemeral error messages
- Timeout-based view expiration (180-300s)
- Session-based state management
Data Protection
- Atomic file operations prevent corruption
- Database WAL mode for ACID compliance
- Automatic backups before shutdown
- Guild configuration snapshots with checksums
- File locking mechanism
- Cache invalidation on writes
- Secure temporary file handling
Metrics Collection
- Real-time command tracking (LRU cache, 100 command limit)
- Message processing statistics
- Error rate monitoring
- Uptime tracking
- Top command analytics
- Per-command usage counts in database
Health Monitoring
- Error rate calculation
- Status determination (healthy/degraded)
- Latency tracking
- Extension load time analysis
- Database connection monitoring
- Cache performance metrics
- Per-shard health checks with three-tier status (🟢🟡🔴)
- Automatic shard health alerts to configurable channels
Diagnostics Dashboard
- System information (Python version, platform, architecture)
- Bot statistics (guilds, users, channels)
- Extension analysis (count, load times)
- Command registration (prefix + slash)
- Performance metrics (CPU, memory, threads)
- Database health status
Atomic File Testing
- Built-in
!atomictestcommand - Write/read/cache performance benchmarking
- Concurrent operation testing (10 simultaneous writes)
- Data integrity verification
- Cache statistics display
Cache Management
!cachestatscommand for monitoring- File cache size tracking
- Lock count monitoring
- Prefix cache statistics
- Metrics cache info
- Database connection counts
Integrity Checks
!integritycheckcommand- File system validation
- Database connection testing
- Cache system verification
- Extension loading checks
- Shard status monitoring
- Memory usage analysis
System Cleanup
!cleanupcommand- pycache directory removal
- Expired prefix cache cleanup
- File lock cleanup
- Orphaned database connection removal
- Statistics reporting
✅ Atomic File Operations - Thread-safe file handling with LRU caching and retry logic
- Zero data corruption through tempfile-based writes
- 300s TTL, 1000 entry LRU cache
- Automatic lock cleanup (500 lock threshold)
- 3-attempt retry with exponential backoff
- Comprehensive metrics and health monitoring
- Diagnostic commands:
!atomicstats,!atomictest - Cache hit rate tracking and optimization
- Cross-platform compatibility (Windows/Linux)
✅ SQLite Database - Optimized with WAL mode and connection pooling
✅ Safe Log Rotation - Automatic management with size and age limits
✅ Hot-Reload System - File-watching based auto-reload (optional)
✅ Metrics Collection - Real-time command tracking and analytics
✅ Framework Cogs - Modular internal components with event system
✅ Auto-Sharding - Built-in support for large-scale deployments
✅ Shard Monitor - Real-time health, latency, and event tracking per shard
✅ Shard Manager - IPC-based multi-process and multi-server shard coordination
✅ Backup & Restore - Full guild snapshots with interactive dashboard and smart restore
✅ Bot Status Rotator - Configurable status rotation with multiple statuses and dynamic variables
✅ Hybrid Commands - Both prefix and slash command support
✅ @Mention Prefix - Invoke commands with @BotName syntax (configurable per-guild)
✅ Permission Framework - Multi-tier role-based access control
✅ AI Assistant - Gemini-powered natural language introspection
✅ Command Autocomplete - Dynamic suggestions for slash commands
✅ Cooldown Management - Built-in rate limiting
✅ Auto-Delete Messages - Automatic cleanup of responses
✅ Slash Limit Protection - Automatic prefix-only fallback
✅ Command Type Indicators - Visual markers in help menu
✅ Integrated Browser - Browse extensions from Discord
✅ Search & Filter - Find extensions by keywords or category
✅ One-Click Install - Direct installation to bot
✅ License Agreement - Mandatory acceptance system
✅ ZygnalID Support - Unique bot identification
✅ Dependency Auto-Fix - Automatic missing package installation
✅ Version Tracking - Extension versioning support
✅ Interactive Help - Dropdown navigation with pagination
✅ Rich Embeds - Modern Discord UI with color coding
✅ User Validation - Security-checked interactions
✅ Progress Bars - Visual feedback for operations
✅ Category Organization - Automatic command grouping
✅ Per-Guild Settings - Custom prefixes, @mention controls, and configurations
✅ Guild Settings Dashboard - View all server settings at a glance
✅ JSON Config System - Centralized configuration
✅ Command Permissions - Granular role requirements
✅ Extension Blacklist - Selective loading control
✅ Framework Cog Control - Enable/disable components
✅ Bot Status Rotator - Configurable status rotation with dynamic variables from the dashboard
✅ Command Usage Stats - Track popular commands
✅ Error Tracking - Comprehensive error logging
✅ Uptime Monitoring - Real-time bot statistics
✅ Performance Metrics - Load times and query tracking
✅ Health Monitoring - System diagnostics and alerts
✅ Hook History - Event system execution tracking
✅ Shard Monitoring - Real-time per-shard health, latency, and event tracking
✅ Multi-Cluster Stats - Cross-shard stat aggregation via IPC
✅ Backup Snapshots - Full guild configuration backup with integrity checksums
Python: 3.8+ (Built and tested with 3.12.7)
discord.py: 2.0+ (Built with 2.6.3)
aiofiles==24.1.0
aiohttp==3.12.14
aiosqlite==0.21.0
discord.py==2.6.3
python-dotenv==1.0.0
psutil==5.9.6
rich==14.0.0
git clone https://github.com/TheHolyOneZ/discord-bot-framework.git
cd discord-bot-framework
docker build -t discord-bot-framework .
docker run -d --name mybot discord-bot-framework
git clone https://github.com/TheHolyOneZ/discord-bot-framework.git
cd discord-bot-frameworkpip install -r requirements.txtCreate .env in the root directory:
DISCORD_TOKEN=Bot_Token
BOT_OWNER_ID=Your_DiscordID
# Sharding Configuration
SHARD_COUNT=1
# Can be commented out depending on your needs. If you want to use auto-sharding, leave (SHARD_IDS) commented out.
# SHARD_IDS=0,1
# Shard Monitor (real-time shard health monitoring)
ENABLE_SHARD_MONITOR=true
SHARD_ALERT_THRESHOLD=3
# Shard Manager (multi-process/multi-server IPC — disabled by default)
ENABLE_SHARD_MANAGER=false
SHARD_IPC_MODE=server
SHARD_IPC_HOST=127.0.0.1
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=change_me_please
SHARD_CLUSTER_NAME=cluster-0
# Backup & Restore (enabled by default)
ENABLE_BACKUP_RESTORE=true
BACKUP_MAX_PER_GUILD=25
BACKUP_COOLDOWN=300
BACKUP_AUTO_INTERVAL=0
BACKUP_RETENTION_DAYS=0Getting Your User ID:
- Enable Developer Mode: User Settings → Advanced → Developer Mode
- Right-click your username → Copy ID
Getting Bot Token:
- Go to Discord Developer Portal
- Create New Application
- Go to Bot section → Reset Token → Copy token
In the Discord Developer Portal:
- Go to your application → Bot section
- Enable these Privileged Gateway Intents:
- ✅ Presence Intent
- ✅ Server Members Intent
- ✅ Message Content Intent
Note: Server Members Intent is required for the Backup & Restore system to capture member role assignments. Without it, backups will still work but member roles will be empty.
python main.pyYou should see a Rich console panel with bot statistics!
Generate invite URL in Developer Portal:
- OAuth2 → URL Generator
- Select Scopes:
bot,applications.commands - Select Permissions: Administrator (or specific permissions)
- Copy generated URL and open in browser
discord-bot-framework/
│
├── main.py # Core bot logic and built-in commands
├── atomic_file_system.py # Atomic operations and data management
│
├── extensions/ # Your extension modules (auto-loaded)
│ ├── Put_Cogs_Extensions_here.txt
│ ├── example_logger.py # Example extension
│ └── marketplace.py # Extension Marketplace cog
│
├── cogs/ # Framework internal cogs
│ ├── event_hooks.py # Internal event system
│ ├── plugin_registry.py # Plugin metadata & dependency tracking
│ ├── framework_diagnostics.py # Health monitoring
│ ├── live_monitor.py # Web dashboard & remote management
│ ├── slash_command_limiter.py # Slash command protection
│ ├── shard_monitor.py # Real-time shard health monitoring
│ ├── shard_manager.py # Multi-process IPC shard management
│ ├── backup_restore.py # Backup & Restore system
│ ├── GeminiService.py # AI assistant — slash commands (/ask_zdbf)
│ ├── GeminiServiceHelper.py # AI assistant — Live Monitor dashboard chat (NEW v1.9.0.0)
│ ├── SHARD_MONITOR_DOCS.md # Shard Monitor documentation
│ └── SHARD_MANAGER_DOCS.md # Shard Manager documentation
│
├── data/ # Auto-generated data directory
│ ├── main.db # Global SQLite database
│ ├── main.db-wal # WAL file for main DB
│ ├── main.db-shm # Shared memory for main DB
│ ├── [guild_id]/ # Per-guild databases
│ │ ├── guild.db
│ │ └── guild_backup_*.db
│ ├── plugin_registry.json # Plugin metadata cache
│ ├── plugin_registry_config.json # Plugin Registry alert channel + enforcement states (NEW)
│ ├── framework_diagnostics.json # System diagnostics
│ ├── framework_diagnostics_config.json # FW Diagnostics alert channel (NEW)
│ ├── framework_health.json # Health monitoring data
│ ├── live_monitor_config.json # Live Monitor settings
│ ├── gemini_dashboard_sessions.json # AI Assistant encrypted session history (NEW)
│ ├── shard_monitor/ # Shard monitor data
│ │ ├── shard_metrics.json # Periodic metrics snapshot
│ │ └── alert_config.json # Alert channel & threshold config
│ ├── shard_manager/ # Shard manager data (reserved)
│ ├── backups/ # Backup snapshots
│ │ └── [guild_id]/ # Per-guild backup data
│ │ ├── index.json # Backup index/metadata
│ │ ├── audit_log.json # Backup audit trail (last 200 entries)
│ │ ├── schedule.json # Auto-backup schedule config
│ │ └── [backup_id].json # Individual snapshots (with member roles)
│ └── marketplace/
│ ├── ZygnalID.txt # Unique bot identifier
│ └── license_accepted.json # License acceptance tracking
│
├── botlogs/ # Log files
│ ├── permanent.log # Persistent log (rotates at 10MB)
│ ├── permanent.log.1-5 # Backup logs
│ └── current_run.log # Current session only
│
├── images/ # Documentation images
│ ├── Terminal-1.png
│ ├── HelpMenu-Example.png
│ └── ... (showcase images)
│
├── assets/ # Live Monitor dashboard assets (optional branding)
│ ├── zoryx-framework.png # Dashboard logo
│ ├── zoryx-framework.ico # Favicon
│ └── banner.png # Banner image
│
├── live_monitor_website/ # Generated dashboard files (upload to PHP server)
│ ├── index.php # Main dashboard interface (~10,000+ lines)
│ ├── receive.php # Bot data reception endpoint
│ ├── get_commands.php # Command polling endpoint
│ ├── send_command.php # Command submission with role checks
│ ├── lm_bootstrap.php # Core initialization and tokens
│ ├── lm_db.php # SQLite database helpers
│ ├── lm_auth.php # Authentication and sessions
│ ├── setup.php # One-time claim wizard
│ ├── login.php # Discord OAuth login
│ ├── oauth_callback.php # OAuth callback handler
│ ├── logout.php # Session logout
│ ├── owner_audit.php # Admin audit log viewer
│ ├── owner_roles.php # Role management panel
│ ├── owner_db.php # Database admin panel
│ ├── backup_dashboard.php # Bot backup interface
│ └── assets/ # Copied branding assets
│
├── config.json # Bot configuration (auto-generated)
├── .env # Environment variables (YOU CREATE THIS)
├── .env.example # Environment variable reference template
├── requirements.txt # Python dependencies
├── README.md # This file
├── LICENSE # MIT License
├── SECURITY.md # Security policy
├── CODE_OF_CONDUCT.md # Code of conduct
└── CONTRIBUTING.md # Contribution guidelines
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!help / /help |
Interactive help menu with dropdown navigation | 10s | ✅ |
!stats / /stats |
Bot statistics, metrics, and framework info | 10s | ✅ |
!extensions / /extensions |
List loaded user extensions and framework cogs | 10s | ✅ |
!discordbotframework |
Framework information and feature list | 10s | ✅ |
!shardinfo / /shardinfo |
Shard information and distribution | 10s | ✅ |
!setprefix <prefix> |
Set custom prefix for your server (Admin only) | - | ✅ |
!config [cmd] [role] |
Configure command permissions (Owner only) | - | ✅ |
| Command | Description | Permission | Hybrid |
|---|---|---|---|
!mentionprefix enable / /mentionprefix enable |
Enable @mention prefix for this server | Administrator | ✅ |
!mentionprefix disable / /mentionprefix disable |
Disable @mention prefix for this server | Administrator | ✅ |
!mentionprefix status / /mentionprefix status |
Check current @mention prefix setting | Administrator | ✅ |
!serversettings / /serversettings |
View all server configuration settings | Administrator | ✅ |
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.
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!marketplace / /marketplace |
Main marketplace menu with quick actions | 5s | ✅ |
!marketplace browse |
Browse all available extensions | 10s | ✅ |
!marketplace search <query> |
Search extensions by keywords | 10s | ✅ |
!marketplace install <id> |
Install extension by ID | 30s | ✅ |
!marketplace info <id> |
View detailed extension information | 5s | ✅ |
!marketplace refresh |
Refresh extension cache | 60s | ✅ |
!marketplace fixdeps |
Auto-install missing dependencies (Owner) | 60s | ✅ |
!marketplace myid |
View your ZygnalID (Owner only) | - | ✅ |
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!atomicstats / /atomicstats |
Display atomic file system statistics (Owner) | - | Yes |
!atomictest / /atomictest |
Run comprehensive atomic operations test suite (Owner) | - | Yes |
| Command | Description | AI Query |
|---|---|---|
!pr_list / /pr_list |
List all registered plugins — paginated, 10 per page with Prev/Next (v1.9.0.0) | /ask_zdbf action:plugins |
!pr_info <name> / /pr_info |
Detailed information about a specific plugin | /ask_zdbf action:plugins query:"tell me about [plugin]" |
!pr_validate <name> |
Validate plugin dependencies and conflicts (Owner) | /ask_zdbf action:plugins query:"does [plugin] have issues?" |
!pr_enforce <mode> |
Toggle dependency/conflict enforcement — now blocking in v1.9.0.0 (Owner) | - |
!pr_alert_channel [channel] |
Set alert channel for registry warnings — persisted across restarts (Owner) | - |
| Command | Description | AI Query |
|---|---|---|
!fw_diagnostics / /fw_diagnostics |
Display framework health and diagnostics (Owner) | /ask_zdbf action:diagnose |
!fw_alert_channel / /fw_alert_channel |
Set alert channel for framework diagnostics (Owner) | - |
!slashlimit / /slashlimit |
Check slash command usage and limits | /ask_zdbf action:slash |
Internal framework event system (cogs/event_hooks.py):
| Command | Description | AI Query |
|---|---|---|
!eh_list / /eh_list |
Display registered hooks with metrics (Owner) | /ask_zdbf action:hooks |
!eh_history [limit] / /eh_history |
Display hook execution history (Owner) | /ask_zdbf action:hooks query:"show hook history" |
!eh_disable <hook_id> |
Disable a problematic hook (Owner) | - |
!eh_enable <hook_id> |
Re-enable a disabled hook (Owner) | - |
!eh_reset_circuit <hook_id> |
Reset circuit breaker for hook (Owner) | - |
!eh_alert_channel [channel] |
Set alert channel for event hooks (Owner) | - |
User-created automations (cogs/EventHooksCreater.py) — v1.9.0.0:
| Command | Description | Access |
|---|---|---|
/hooks list [page] |
Paginated list of all automations in this guild | Owner / Admin |
/hooks info <hook_id> |
Detailed embed: params, conditions, execution stats, last run | Owner / Admin |
/hooks delete <hook_id> |
Delete an automation with confirmation | Owner |
/hooks toggle <hook_id> |
Enable or disable an automation | Owner / Admin |
/hooks create <template_id> |
Create a new automation from a template | Owner / Admin |
Available templates: leveling_system, scheduled_announcement, ticket_system, voice_activity_tracker, dynamic_voice_channels
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
/livemonitor quickstart <url> |
Generate dashboard files and configure monitoring | - | ✅ |
/livemonitor status |
Show current configuration, connection status, failure count | - | ✅ |
/livemonitor enable |
Start sending data to dashboard (2-second intervals) | - | ✅ |
/livemonitor disable |
Stop all data transmission and command polling | - | ✅ |
/livemonitor files |
Regenerate dashboard PHP/HTML/JS files | - | ✅ |
Note: Live Monitor requires a PHP web server (e.g., Strato, Hostinger, any cPanel host). See the Using Live Monitor section for complete setup instructions.
Slash command interface (cogs/GeminiService.py):
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
/ask_zdbf <action> [query] |
Ask the AI assistant about the bot, its code, or data | 15s | ❌ (Slash Only) |
Actions for /ask_zdbf:
help: Shows an interactive help menu for the AI assistant.framework: Ask a general question about the bot's architecture.plugins: Get an AI-powered analysis of installed plugins.diagnose: Receive a health report summary from the AI.database: Ask a question about the database schema in natural language.file: Ask a question about a specific file's content. (Owner only)extension: Inspect an extension file from the/extensionsfolder.slash: Inquire about the slash command auto-conversion system.hooks: Ask about the internal framework (EventHooks) event system.automations: Ask about user-created automations.readme: Ask a question about the bot'sREADME.mdfile.permission: (Owner Only) Manage permissions for the AI assistant.
Dashboard AI chat (cogs/GeminiServiceHelper.py) — v1.9.0.0 ✨ NEW:
The Live Monitor dashboard includes a dedicated AI Assistant tab (tab 21) with a fully encrypted chat interface — no slash commands required.
| Feature | Detail |
|---|---|
| Encryption | AES-256-CBC; client uses Web Crypto API, server uses cryptography library |
| Attach File | Toolbar button with live autocomplete; supports multiple files as chip tags |
| Auto-detect | File names in your message are automatically detected and read |
| Markdown | Fenced code blocks, headers, bold, italic, inline code — no external deps |
| Permissions | view_gemini_chat · action_gemini_send · action_gemini_clear_history · action_gemini_config |
| Config | Owner can change Gemini model and system prompt live from the config drawer |
All commands are Bot Owner Only (
BOT_OWNER_IDfrom.env)
Toggle:ENABLE_SHARD_MONITOR=true/falsein.env
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!shardmonitor / /shardmonitor |
Interactive dashboard with button navigation (Overview, Health, Latency, Events) | 10s | ✅ |
!sharddetails <id> / /sharddetails |
Detailed metrics for a specific shard (guilds, members, latency, reliability, errors) | 10s | ✅ |
!shardhealth / /shardhealth |
Health check report for all shards with critical/warning/healthy breakdown | 30s | ✅ |
!shardalerts [#channel] [threshold] / /shardalerts |
Configure alert channel and failure threshold for automatic health alerts | - | ✅ |
!shardreset [shard_id] / /shardreset |
Reset metrics for a specific shard or all shards (-1 for all) | - | ✅ |
Interactive Dashboard Tabs (/shardmonitor):
| Tab | Button | What It Shows |
|---|---|---|
| Overview | 📊 | Cluster stats, per-shard summary, alert config |
| Health | 🏥 | Health report with healthy/warning/critical breakdown |
| Latency | 📡 | Visual latency bars per shard, cluster latency statistics |
| Events | 📈 | Per-shard event counters (messages, commands, connects, errors) |
| Refresh | 🔄 | Refreshes the currently active tab with latest data |
Health Check Thresholds:
| Condition | Status | Icon |
|---|---|---|
| Average latency > 1000ms | Warning | 🟡 |
| Average latency > 2000ms | Critical | 🔴 |
| No activity for 5+ minutes | Warning | 🟡 |
| 3+ consecutive failures | Warning | 🟡 |
| 5+ consecutive failures | Critical | 🔴 |
| Currently disconnected | Critical | 🔴 |
| Recently disconnected (<60s) | Warning | 🟡 |
All commands are Bot Owner Only (
BOT_OWNER_IDfrom.env)
Toggle:ENABLE_SHARD_MANAGER=true/falsein.env(disabled by default)
Only needed for multi-process or multi-server deployments
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!clusters / /clusters |
Show all connected shard clusters with stats, health, and global totals | 10s | ✅ |
!ipcstatus / /ipcstatus |
IPC system diagnostics (mode, host, port, connected clients, heartbeats) | 10s | ✅ |
!broadcastmsg <message> / /broadcastmsg |
Broadcast a text message to all connected clusters via IPC | - | ✅ |
Administrator permission required (Bot Owner has full access) Toggle:
ENABLE_BACKUP_RESTORE=true/falsein.env(enabled by default) Useful for server migrations, disaster recovery, configuration auditing, and member role recovery
| Command | Description | Cooldown | Hybrid |
|---|---|---|---|
!backup / /backup |
Interactive dashboard with Overview, Backups, Compare, Audit, and Analytics tabs | 10s | ✅ |
!backupcreate [label] / /backupcreate |
Create a full guild snapshot (roles, channels, member roles, permissions, settings) | 5min/guild | ✅ |
!backuprestore <id> / /backuprestore |
Selective restore with component toggles (roles, categories, channels, member roles, bot settings) | - | ✅ |
!backupview <id> / /backupview |
Detailed backup inspection (contents, roles, settings, member count, checksum) | - | ✅ |
!backupdelete <id> / /backupdelete |
Delete a backup with confirmation (respects pin protection) | - | ✅ |
!backuplist / /backuplist |
Paginated list of all backups with metadata | - | ✅ |
!backuppin <id> / /backuppin |
Pin/unpin a backup to protect from deletion and retention cleanup | - | ✅ |
!backupnote <id> <text> / /backupnote |
Add or update a note on a backup (up to 500 chars) | - | ✅ |
!backupverify <id> / /backupverify |
Verify backup integrity via SHA-256 checksum | - | ✅ |
!backupschedule <action> / /backupschedule |
Configure auto-backup schedule (enable/disable/status, 1-168h interval) | - | ✅ |
!backupdiff <a> <b> / /backupdiff |
Compare two backups side by side (roles, channels, members added/removed) | - | ✅ |
!backupexport <id> / /backupexport |
Export backup as downloadable JSON file | - | ✅ (Bot Owner only) |
!backupstats / /backupstats |
Global backup statistics across all guilds | - | ✅ (Bot Owner only) |
Interactive Dashboard Tabs (/backup):
| Tab | Button | What It Shows |
|---|---|---|
| Overview | 📊 | Storage usage bar, latest backup, current guild stats, cooldown timer |
| Backups | 📦 | Paginated list of all backups with ID, label, author, member snapshots, size |
| Compare | 🔍 | Drift analysis: current state vs latest backup with change recommendation |
| Audit Log | 📜 | Chronological log of all backup operations (create, delete, restore, pin, verify) |
| Analytics | 📈 | Trends over time, top creators, backup frequency, member snapshot stats |
| Refresh | 🔄 | Refreshes the currently active tab |
| Delete | 🗑️ | Quick-delete via dropdown selector (ephemeral, respects pin protection) |
| ◀ ▶ | Pagination | Navigate through paginated list and audit pages |
What Gets Backed Up:
| Category | Details |
|---|---|
| Roles | Name, color, hoist, mentionable, permissions value, position |
| Categories | Name, position, NSFW flag, full permission overwrites (target, allow, deny) |
| Text Channels | Name, topic, slowmode, NSFW, category, auto-archive duration, full permission overwrites |
| Voice Channels | Name, bitrate, user limit, RTC region, category, full permission overwrites |
| Forum Channels | Name, topic, NSFW, slowmode, category, permission overwrites |
| Stage Channels | Name, topic, category, permission overwrites |
| Emojis | Name, animated flag, URL, managed status |
| Stickers | Name, description, emoji |
| Server Settings | Verification level, notification level, content filter, AFK timeout/channel, system channel, locale, boost bar |
| Member Roles | Per-member role assignments for all non-bot members (requires Members Intent) |
| Bot Settings | Custom prefix, mention prefix enabled/disabled |
| Command | Description | Access |
|---|---|---|
!sync / /sync |
Force sync slash commands globally | Bot Owner |
!reload <extension> |
Hot-reload specific extension | Bot Owner |
!load <extension> |
Load extension | Bot Owner |
!unload <extension> |
Unload extension | Bot Owner |
!fw_diagnostics |
Display framework diagnostics and health | Bot Owner |
!fw_alert_channel <channel> |
Set alert channel for framework diagnostics | Bot Owner |
!cachestats |
Display cache statistics | Bot Owner |
!dbstats |
Display database connection stats | Bot Owner |
!integritycheck |
Run full system integrity check | Bot Owner |
!cleanup |
Clean up system cache and temp files | Bot Owner |
!shardmonitor |
Interactive shard monitoring dashboard | Bot Owner |
!sharddetails <id> |
Detailed metrics for specific shard | Bot Owner |
!shardhealth |
Health check report for all shards | Bot Owner |
!shardalerts [#ch] [n] |
Configure shard alert channel and threshold | Bot Owner |
!shardreset [id] |
Reset shard metrics (-1 for all) | Bot Owner |
!clusters |
Show all connected shard clusters (requires Shard Manager) | Bot Owner |
!ipcstatus |
IPC system diagnostics (requires Shard Manager) | Bot Owner |
!broadcastmsg <msg> |
Broadcast message to all clusters (requires Shard Manager) | Bot Owner |
!backupexport <id> |
Export backup as JSON file | Bot Owner |
!backupstats |
Global backup statistics across all guilds | Bot Owner |
The integrated Extension Marketplace allows you to browse, search, and install official extensions directly from Discord without manual file downloads.
✅ Browse Extensions - View all available extensions with pagination
✅ Search Functionality - Find extensions by keywords
✅ Category Filtering - Filter by status (Working, Beta, Broken)
✅ One-Click Install - Direct installation to ./extensions directory
✅ License Agreement - Mandatory acceptance before use
✅ ZygnalID System - Unique bot identification for support
✅ Dependency Management - Automatic missing package installation
✅ Version Tracking - View extension versions and update dates
- Run marketplace command:
!marketplace-
Accept License Agreement:
- Read the terms carefully
- Click "✅ Accept License" button
- Acceptance is tracked per-user
-
Browse Extensions:
- Use dropdown menu or buttons
- Search by keywords
- Filter by categories
Method 1: Interactive Menu
!marketplace
# Click "Browse All" button
# Select extension from dropdown
# Click "📦 Install Extension"
# Confirm installationMethod 2: Direct Install
!marketplace install <extension_id>Post-Installation: After successful installation:
# Load the extension immediately
!load extension_name
# Or reload if already loaded
!reload extension_name
# Or restart bot for auto-loadWhat is ZygnalID?
- Unique 16-character identifier for your bot
- Auto-generated on first marketplace use
- Required for extension downloads
- Enables dedicated support and tracking
View Your ID:
!marketplace myid(Owner only, sent via DM for security)
Activation: If your ID is invalid or not activated:
- Join ZygnalBot Discord:
gg/sgZnXca5ts - Verify yourself
- Open ticket for "Zygnal ID Activation"
- Provide your ZygnalID from
!marketplace myid
Automatic Fix: If extensions fail to load due to missing Python packages:
!marketplace fixdepsThis command:
- Scans
botlogs/current_run.logforModuleNotFoundError - Extracts missing package names
- Automatically runs
pip install <package> - Reports success/failure per package
- Provides next steps for loading extensions
Manual Installation:
pip install package_name
!reload extension_nameWorking ✅
- Fully functional extensions
- Tested and verified
- Production-ready
Beta
- Experimental features
- May have minor issues
- Actively developed
Broken ❌
- Known issues
- Not recommended for use
- Awaiting fixes
View detailed information about any extension:
!marketplace info <extension_id>Displays:
- Full description
- Version number
- Status (Working/Beta/Broken)
- File type (PY/TXT)
- Upload date
- Custom URL (if available)
- Installation instructions
By Keyword:
!marketplace search moderationBy Title or Description: The search is case-insensitive and matches:
- Extension titles
- Description text
- Details field
The marketplace caches API responses for 300 seconds (5 minutes).
Force Refresh:
!marketplace refreshUse this when:
- New extensions are added
- Extension details are updated
- Cache shows outdated information
import discord
from discord.ext import commands
from discord import app_commands
class MyExtension(commands.Cog):
"""Description of your extension"""
def __init__(self, bot):
self.bot = bot
print(f"{self.__class__.__name__} initialized")
@commands.hybrid_command(
name="example",
help="An example command that works with both prefix and slash"
)
@commands.cooldown(1, 5, commands.BucketType.user)
async def example_command(self, ctx):
"""Command implementation"""
embed = discord.Embed(
title="✅ Success",
description="This is an example command!",
color=0x00ff00
)
await ctx.send(embed=embed)
@commands.Cog.listener()
async def on_message(self, message):
"""Event listener example"""
if message.author.bot:
return
# Your logic here
def cog_unload(self):
"""Cleanup when extension is unloaded"""
print(f"{self.__class__.__name__} unloaded")
async def setup(bot):
"""Required setup function"""
await bot.add_cog(MyExtension(bot))Basic File Operations:
from atomic_file_system import global_file_handler
class MyExtension(commands.Cog):
async def save_data(self, data: dict):
# Atomic write with cache invalidation
success = await global_file_handler.atomic_write_json(
"./data/my_extension_data.json",
data,
invalidate_cache_after=True
)
return success
async def load_data(self) -> dict:
# Read with caching enabled (300s TTL)
data = await global_file_handler.atomic_read_json(
"./data/my_extension_data.json",
use_cache=True
)
return data or {}Advanced Usage with Manual Cache Control:
class AdvancedExtension(commands.Cog):
async def update_config(self, key: str, value: str):
# Read current config (cached)
config = await global_file_handler.atomic_read_json(
"./data/config.json",
use_cache=True
) or {}
# Update config
config[key] = value
# Write and keep in cache (frequent reads)
await global_file_handler.atomic_write_json(
"./data/config.json",
config,
invalidate_cache_after=False # Keep in cache
)
async def force_reload(self):
# Bypass cache for critical reads
config = await global_file_handler.atomic_read_json(
"./data/config.json",
use_cache=False
)
# Or manually invalidate cache
global_file_handler.invalidate_cache("./data/config.json")Cache Statistics in Extensions:
class MonitoringExtension(commands.Cog):
@commands.command()
async def check_cache(self, ctx):
stats = global_file_handler.get_cache_stats()
await ctx.send(f"""
Cache Performance:
- Size: {stats['cache_size']}/{stats['max_cache_size']}
- Hit Rate: {stats['hit_rate']}%
- Total Ops: {stats['total_reads'] + stats['total_writes']}
- Failures: {stats['write_failures'] + stats['read_failures']}
""")import discord
from discord.ext import commands
# Plugin metadata (recommended for Plugin Registry)
__version__ = "1.0.0"
__author__ = "YourName"
__description__ = "A cool extension that does amazing things"
__dependencies__ = [] # List of required extensions
__conflicts__ = [] # List of incompatible extensions
class MyExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Register with Plugin Registry (if available)
if hasattr(bot, 'register_plugin'):
bot.register_plugin(
name="my_extension",
version=__version__,
author=__author__,
description=__description__,
dependencies=__dependencies__,
conflicts_with=__conflicts__
)
@commands.hybrid_command(name="example")
async def example_command(self, ctx):
await ctx.send("Hello from my extension!")
async def setup(bot):
await bot.add_cog(MyExtension(bot))from discord.ext import commands
import discord
class HookedExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Register hooks if Event Hooks system is available
if hasattr(bot, 'register_hook'):
# Priority: higher executes first (default: 0)
bot.register_hook("extension_loaded", self.on_ext_loaded, priority=5)
bot.register_hook("command_executed", self.on_cmd_used)
bot.register_hook("bot_ready", self.on_bot_ready)
async def on_ext_loaded(self, bot, extension_name: str, **kwargs):
"""Called when any extension is loaded"""
print(f"Extension loaded: {extension_name}")
async def on_cmd_used(self, bot, command_name: str, author, **kwargs):
"""Called when any command is executed"""
print(f"Command {command_name} used by {author}")
async def on_bot_ready(self, bot, bot_user, **kwargs):
"""Called when bot becomes ready"""
print(f"Bot is ready: {bot_user}")
def cog_unload(self):
"""Cleanup: Unregister hooks when cog unloads"""
if hasattr(self.bot, 'unregister_hook'):
self.bot.unregister_hook("extension_loaded", self.on_ext_loaded)
self.bot.unregister_hook("command_executed", self.on_cmd_used)
self.bot.unregister_hook("bot_ready", self.on_bot_ready)
async def setup(bot):
await bot.add_cog(HookedExtension(bot))from discord.ext import commands
import discord
class DatabaseExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="savedata")
async def save_data(self, ctx, key: str, value: str):
"""Save data to guild database"""
# Get guild-specific database connection
conn = await self.bot.db._get_guild_connection(ctx.guild.id)
# Create table if not exists
await conn.execute("""
CREATE TABLE IF NOT EXISTS custom_data (
key TEXT PRIMARY KEY,
value TEXT,
user_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Insert or replace data
await conn.execute(
"INSERT OR REPLACE INTO custom_data (key, value, user_id) VALUES (?, ?, ?)",
(key, value, ctx.author.id)
)
await conn.commit()
await ctx.send(f"✅ Saved: {key} = {value}")
@commands.hybrid_command(name="getdata")
async def get_data(self, ctx, key: str):
"""Retrieve data from guild database"""
conn = await self.bot.db._get_guild_connection(ctx.guild.id)
async with conn.execute(
"SELECT value, user_id FROM custom_data WHERE key = ?",
(key,)
) as cursor:
row = await cursor.fetchone()
if row:
await ctx.send(f"📄 {key} = {row['value']} (saved by <@{row['user_id']}>)")
else:
await ctx.send(f"❌ No data found for key: {key}")
async def setup(bot):
await bot.add_cog(DatabaseExtension(bot))The database system uses the atomic file handler for:
- Configuration persistence -
config.jsonwritten atomically - Plugin registry storage - Registry JSON with ACID compliance
- Framework diagnostics - Diagnostic reports saved safely
- Extension data - Any JSON-based extension storage
Benefits:
- Zero data corruption even during crashes
- Concurrent access safety
- Automatic retry on transient failures
- Cache acceleration for frequently accessed files
- Lock-free reads (when cached)
Performance Optimization:
# High-frequency reads (use cache)
prefix = await bot.config.get("prefix") # Cached
# Critical writes (bypass cache)
await bot.config.file_handler.atomic_write_json(
path,
data,
invalidate_cache_after=True
)
# Batch operations (manual cache management)
for item in items:
await process_item(item)
global_file_handler.clear_all_cache() # Clear after batchfrom discord.ext import commands
import discord
from atomic_file_system import global_file_handler
from datetime import datetime
class FileExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.data_file = "./data/my_extension_data.json"
@commands.hybrid_command(name="saveconfig")
async def save_config(self, ctx, setting: str, value: str):
"""Save configuration atomically"""
# Read existing data (with caching)
existing_data = await global_file_handler.atomic_read_json(
self.data_file,
use_cache=True
) or {}
# Update data
existing_data[setting] = {
"value": value,
"set_by": ctx.author.id,
"timestamp": datetime.now().isoformat()
}
# Atomic write (invalidates cache)
success = await global_file_handler.atomic_write_json(
self.data_file,
existing_data,
invalidate_cache_after=True
)
if success:
await ctx.send(f"✅ Configuration saved: {setting} = {value}")
else:
await ctx.send("❌ Failed to save configuration")
@commands.hybrid_command(name="getconfig")
async def get_config(self, ctx, setting: str = None):
"""Retrieve configuration"""
# Read with caching enabled (300s TTL)
data = await global_file_handler.atomic_read_json(
self.data_file,
use_cache=True
)
if not data:
await ctx.send("❌ No configuration found")
return
if setting:
if setting in data:
config = data[setting]
await ctx.send(
f"📄 {setting} = {config['value']}\n"
f"Set by: <@{config['set_by']}>\n"
f"Time: {config['timestamp']}"
)
else:
await ctx.send(f"❌ Setting not found: {setting}")
else:
# Display all settings
embed = discord.Embed(
title="⚙️ All Configurations",
color=0x5865f2
)
for key, config in data.items():
embed.add_field(
name=key,
value=f"Value: {config['value']}\nSet by: <@{config['set_by']}>",
inline=False
)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(FileExtension(bot))import discord
from discord.ext import commands
from discord import app_commands
class ModerationExtension(commands.Cog, name="Moderation"):
"""Moderation commands for server management"""
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(
name="ban",
help="Ban a user from the server"
)
@commands.has_permissions(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
@commands.guild_only()
async def ban_user(
self,
ctx,
member: discord.Member,
*,
reason: str = "No reason provided"
):
"""Ban a member with reason"""
# Safety check
if member.top_role >= ctx.author.top_role:
await ctx.send("❌ You cannot ban this user (role hierarchy)")
return
# Perform ban
await member.ban(reason=f"{reason} (By: {ctx.author})")
# Log to database
await self.bot.db.increment_command_usage("ban")
# Send confirmation
embed = discord.Embed(
title="🔨 User Banned",
description=f"**User:** {member.mention}\n**Reason:** {reason}",
color=0xff0000,
timestamp=discord.utils.utcnow()
)
embed.set_footer(text=f"Banned by {ctx.author}")
await ctx.send(embed=embed)
# Try to DM the user
try:
dm_embed = discord.Embed(
title="You were banned",
description=f"**Server:** {ctx.guild.name}\n**Reason:** {reason}",
color=0xff0000
)
await member.send(embed=dm_embed)
except:
pass # User has DMs disabled
@commands.hybrid_command(
name="kick",
help="Kick a user from the server"
)
@commands.has_permissions(kick_members=True)
@commands.bot_has_permissions(kick_members=True)
@commands.guild_only()
async def kick_user(
self,
ctx,
member: discord.Member,
*,
reason: str = "No reason provided"
):
"""Kick a member with reason"""
if member.top_role >= ctx.author.top_role:
await ctx.send("❌ You cannot kick this user (role hierarchy)")
return
await member.kick(reason=f"{reason} (By: {ctx.author})")
await self.bot.db.increment_command_usage("kick")
embed = discord.Embed(
title="👢 User Kicked",
description=f"**User:** {member.mention}\n**Reason:** {reason}",
color=0xff9900,
timestamp=discord.utils.utcnow()
)
embed.set_footer(text=f"Kicked by {ctx.author}")
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(ModerationExtension(bot))import discord
from discord.ext import commands, tasks
from datetime import datetime
class TaskExtension(commands.Cog):
"""Extension with background tasks"""
def __init__(self, bot):
self.bot = bot
self.message_count = 0
self.hourly_report.start()
def cog_unload(self):
"""Stop tasks when unloading"""
self.hourly_report.cancel()
@tasks.loop(hours=1)
async def hourly_report(self):
"""Send hourly statistics report"""
channel_id = self.bot.config.get("reports_channel_id")
if not channel_id:
return
channel = self.bot.get_channel(channel_id)
if not channel:
return
embed = discord.Embed(
title="📊 Hourly Report",
description=f"Messages tracked: {self.message_count}",
color=0x5865f2,
timestamp=datetime.utcnow()
)
stats = self.bot.metrics.get_stats()
embed.add_field(
name="Bot Statistics",
value=f"Commands: {stats['commands_processed']}\nErrors: {stats['error_count']}",
inline=False
)
await channel.send(embed=embed)
self.message_count = 0 # Reset counter
@hourly_report.before_loop
async def before_hourly_report(self):
"""Wait until bot is ready"""
await self.bot.wait_until_ready()
@commands.Cog.listener()
async def on_message(self, message):
"""Track messages"""
if not message.author.bot:
self.message_count += 1
async def setup(bot):
await bot.add_cog(TaskExtension(bot))import discord
from discord.ext import commands
def is_admin_or_owner():
"""Custom check for admin or bot owner"""
async def predicate(ctx):
if ctx.author.id == ctx.bot.bot_owner_id:
return True
if ctx.guild and ctx.author.guild_permissions.administrator:
return True
raise commands.CheckFailure("You must be an administrator or bot owner")
return commands.check(predicate)
def has_any_role(*role_names):
"""Custom check for any of the specified roles"""
async def predicate(ctx):
if not ctx.guild:
raise commands.CheckFailure("This command cannot be used in DMs")
member_roles = [role.name for role in ctx.author.roles]
if any(role in member_roles for role in role_names):
return True
raise commands.CheckFailure(f"You need one of these roles: {', '.join(role_names)}")
return commands.check(predicate)
class CustomChecksExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="adminonly")
@is_admin_or_owner()
async def admin_only_command(self, ctx):
"""Only admins and bot owner can use this"""
await ctx.send("✅ You have admin privileges!")
@commands.hybrid_command(name="staffonly")
@has_any_role("Staff", "Moderator", "Admin")
async def staff_only_command(self, ctx):
"""Only staff members can use this"""
await ctx.send("✅ You are a staff member!")
async def setup(bot):
await bot.add_cog(CustomChecksExtension(bot))import discord
from discord.ext import commands
from discord import app_commands
from typing import Literal
class SlashOptionsExtension(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.hybrid_command(name="color")
@app_commands.describe(
color="Choose a color",
intensity="Color intensity level"
)
async def color_command(
self,
ctx,
color: Literal["red", "green", "blue"],
intensity: int = 5
):
"""Command with slash options"""
color_map = {
"red": 0xff0000,
"green": 0x00ff00,
"blue": 0x0000ff
}
embed = discord.Embed(
title=f"{color.capitalize()} Color",
description=f"Intensity: {intensity}/10",
color=color_map[color]
)
await ctx.send(embed=embed)
@commands.hybrid_command(name="userinfo")
@app_commands.describe(member="The member to get info about")
async def userinfo_command(
self,
ctx,
member: discord.Member = None
):
"""Get information about a user"""
member = member or ctx.author
embed = discord.Embed(
title=f"User Info: {member}",
color=member.color
)
embed.set_thumbnail(url=member.display_avatar.url)
embed.add_field(name="ID", value=member.id, inline=True)
embed.add_field(name="Joined", value=member.joined_at.strftime("%Y-%m-%d"), inline=True)
embed.add_field(name="Roles", value=f"{len(member.roles)-1}", inline=True)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(SlashOptionsExtension(bot))On first run, the bot creates config.json with default settings:
{
"prefix": "!",
"allow_mention_prefix": true,
"owner_ids": [],
"auto_reload": true,
"status": {
"type": "watching",
"text": "{guilds} servers"
},
"database": {
"base_path": "./data"
},
"logging": {
"level": "INFO",
"max_bytes": 10485760,
"backup_count": 5
},
"extensions": {
"auto_load": true,
"blacklist": []
},
"cooldowns": {
"default_rate": 3,
"default_per": 5.0
},
"command_permissions": {},
"slash_limiter": {
"max_limit": 100,
"warning_threshold": 90,
"safe_limit": 95
},
"framework": {
"load_cogs": true,
"enable_event_hooks": true,
"enable_plugin_registry": true,
"enable_framework_diagnostics": true,
"enable_slash_command_limiter": true,
"enable_shard_monitor": true,
"enable_shard_manager": true
}
}Configuration Options Basic Settings prefix (string)
Default command prefix Default: "!" Per-guild overrides supported via !setprefix
allow_mention_prefix (boolean)
Enable @mention as command prefix Default: true Allows users to invoke commands with @BotName command Per-guild overrides supported via !mentionprefix Example: @BotName help works like !help when enabled
owner_ids (array)
Additional bot owner IDs Default: [] Primary owner from BOT_OWNER_ID env variable
auto_reload (boolean)
Enable hot-reload for extensions Default: true Checks every 30 seconds for file changes
Status Configuration status.type (string)
Activity type shown in Discord Options: "playing", "watching", "listening", "competing" Default: "watching"
status.text (string)
Status message with variables Variables: {guilds}, {users}, {commands} Default: "{guilds} servers" Example: "with {users} users | {guilds} servers"
Database Configuration database.base_path (string)
Base directory for database files Default: "./data" Contains main.db and per-guild databases
Logging Configuration logging.level (string)
Logging level Options: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" Default: "INFO"
logging.max_bytes (integer)
Max log file size before rotation Default: 10485760 (10MB)
logging.backup_count (integer)
Number of backup log files to keep Default: 5
Extensions Configuration extensions.auto_load (boolean)
Automatically load all extensions on startup Default: true
extensions.blacklist (array)
Extension names to skip during auto-load Default: [] Example: ["debug_cog", "test_extension"]
Cooldowns Configuration cooldowns.default_rate (integer)
Default number of command uses Default: 3
cooldowns.default_per (float)
Default cooldown period in seconds Default: 5.0
Slash Command Limiter slash_limiter.max_limit (integer)
Discord's hard limit for slash commands Default: 100 Should not be changed
slash_limiter.warning_threshold (integer)
Command count to trigger warnings Default: 90 Logs warning at this count
slash_limiter.safe_limit (integer)
Command count to start prefix-only mode Default: 95 New extensions become prefix-only
Framework Cogs framework.load_cogs (boolean)
Load framework internal cogs Default: true Disable to use minimal framework
framework.enable_event_hooks (boolean)
Enable Event Hooks system Default: true
framework.enable_plugin_registry (boolean)
Enable Plugin Registry system Default: true
framework.enable_framework_diagnostics (boolean)
Enable Framework Diagnostics system Default: true
framework.enable_slash_command_limiter (boolean)
Enable Slash Command Limiter Default: true
framework.enable_shard_monitor (boolean)
Enable Shard Monitor cog
Default: true
Also controlled by ENABLE_SHARD_MONITOR env variable (.env takes precedence)
framework.enable_shard_manager (boolean)
Enable Shard Manager cog (multi-process IPC)
Default: true (but .env default is false which takes precedence)
Also controlled by ENABLE_SHARD_MANAGER env variable (.env takes precedence)
Command Permissions Configure role-based command access:
# Grant @Moderator access to ban command
!config ban @Moderator
# Add multiple roles
!config kick @Moderator
!config kick @Admin
# View current permissions
!config
# Remove restrictions
!config ban none
{
"command_permissions": {
"ban": [123456789, 987654321],
"kick": [123456789]
}
}
Set per-guild prefixes:
# Set prefix to ?
!setprefix ?
# Now commands work with ?
?help
?stats
# Slash commands always work regardless of prefix
/help
/stats
Required .env file:
# Required
DISCORD_TOKEN=your_bot_token_here
BOT_OWNER_ID=your_discord_user_id
# Optional: Sharding (for large bots)
SHARD_COUNT=2
# SHARD_IDS can be commented out
SHARD_IDS=0,1
# Shard Monitor
ENABLE_SHARD_MONITOR=true
SHARD_ALERT_THRESHOLD=3
# Shard Manager (multi-process/multi-server)
ENABLE_SHARD_MANAGER=false
SHARD_IPC_MODE=server
SHARD_IPC_HOST=127.0.0.1
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=change_me_please
SHARD_CLUSTER_NAME=cluster-0
SHARD_COUNT: Total number of shards (Discord requires sharding at 2500+ guilds)SHARD_IDS: Comma-separated list of shard IDs for this process (leave empty for auto-sharding)ENABLE_SHARD_MONITOR: Enable/disable real-time shard health monitoring (default:true)SHARD_ALERT_THRESHOLD: Consecutive failures before alert fires (default:3)ENABLE_SHARD_MANAGER: Enable/disable IPC-based multi-process sharding (default:false)SHARD_IPC_MODE:serverfor primary cluster,clientfor secondary clustersSHARD_IPC_HOST: IPC bind address (127.0.0.1for local,0.0.0.0for remote)SHARD_IPC_PORT: IPC server port (default:20000)SHARD_IPC_SECRET: Shared authentication secret (MUST match on all clusters)SHARD_CLUSTER_NAME: Unique name to identify this cluster in logs and commands
The framework uses a hybrid database approach:
- Main Database (./data/main.db)
- Global bot statistics
- Command usage tracking
- Framework-wide data
- Per-Guild Databases (./data/[guild_id]/guild.db)
- Guild-specific settings
- Custom prefixes
- Extension data per guild
✅ WAL Mode - Write-Ahead Logging for concurrent access ✅ Connection Pooling - Automatic per-guild connection management ✅ Automatic Backups - Created on bot shutdown ✅ Orphan Cleanup - Removes connections for left guilds ✅ Atomic Operations - ACID compliance
# Direct access to main database
async with self.bot.db.conn.execute(
"SELECT * FROM global_stats WHERE key = ?",
("some_key",)
) as cursor:
row = await cursor.fetchone()# Get guild-specific connection
conn = await self.bot.db._get_guild_connection(guild_id)
# Execute queries
await conn.execute(
"INSERT INTO custom_table (data) VALUES (?)",
(data,)
)
await conn.commit()# Set guild prefix
await bot.db.set_guild_prefix(guild_id, "?")
# Get guild prefix
prefix = await bot.db.get_guild_prefix(guild_id)
# Increment command usage
await bot.db.increment_command_usage("command_name")
# Get command statistics
stats = await bot.db.get_command_stats()
# Returns: [(command_name, count), ...]
# Cleanup guild data
await bot.db.cleanup_guild(guild_id)
# Backup databases
await bot.db.backup() # All guilds
await bot.db.backup(guild_id) # Specific guildglobal_stats
CREATE TABLE global_stats (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
CREATE TABLE guild_settings (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
CREATE TABLE command_stats (
command_name TEXT PRIMARY KEY,
usage_count INTEGER DEFAULT 0,
last_used TIMESTAMP
)
- Cleans up orphaned connections
- Expires prefix cache entries
- Removes pycache directories
- Logs maintenance actions
Manual Cleanup:
!cleanup
View Database Stats:
!dbstats
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).
File: cogs/event_hooks.py
What It Does
- Internal event system for framework lifecycle events
- Priority-based callback execution
- Asynchronous queue processing (1000 event capacity)
- Execution history tracking (100 total, 20 per event)
- Worker task for async event processing
| Event Name | Description | Parameters |
|---|---|---|
| bot_ready | Bot becomes ready | — |
| guild_joined | Bot joins a guild | guild |
| guild_left | Bot leaves a guild | guild |
| command_executed | Command is executed | command_name, author, guild |
| command_error | Command error occurs | command_name, error, author, guild |
| extension_loaded | Extension is loaded (custom) | extension_name |
| extension_unloaded | Extension is unloaded (custom) | extension_name |
File: atomic_file_system.py
What It Does
- Thread-safe atomic file operations with zero data corruption
- LRU cache system (300s TTL, 1000 entry limit)
- Automatic file lock management with cleanup
- Retry logic for write operations (3 attempts)
- Comprehensive diagnostics and metrics tracking
Key Features:
Atomic Write Protection
- Tempfile-based writes prevent partial updates
- Automatic retry on permission errors
- Windows/Linux compatible file operations
- Cross-platform atomic move operations
LRU Cache System
- Configurable TTL (default: 300 seconds)
- Automatic eviction when full (max 1000 entries)
- Cache hit rate tracking
- Manual invalidation support
- Thread-safe cache access
Lock Management
- Per-file lock acquisition
- Automatic cleanup of inactive locks (threshold: 500)
- Lock age tracking for diagnostics
- Deadlock prevention
Performance Metrics
- Read/write operation counters
- Cache hit rate calculation
- Failure rate monitoring
- Lock cleanup statistics
Health Monitoring
- Real-time failure rate tracking
- Three-tier status: Healthy (<1%), Degraded (1-5%), Critical (>5%)
- Operation history tracking
View System Statistics:
!atomicstatsShows:
- Cache size and hit rate
- Active file locks
- Total read/write operations
- Failure rates and health status
- System uptime
Run Diagnostic Tests:
!atomictestPerforms:
- Atomic write test
- Read test without cache
- Read test with cache (verifies caching)
- Concurrent write test (10 simultaneous writes)
- Cache invalidation test
Performance Metrics:
- Cache hit rate >70% is healthy
- Active locks should be <100 normally
- Failure rate should be <1%
- Lock cleanup runs automatically at 500+ locks
Register a Hook:
# Register hook with priority
bot.register_hook("bot_ready", my_callback, priority=10)
# Hook callback signature
async def my_callback(bot, **kwargs):
# bot: Bot instance
# kwargs: Event-specific parameters
passHook ID Format:
- Format:
event_name:callback_name - Example:
bot_ready:on_bot_ready - Used for disabling/enabling specific hooks
View Registered Hooks:
!eh_listShows:
- All registered hooks by event
- Priority levels
- Execution counts and failure counts
- Average execution time
- Status indicators:
- 🔴 - Hook disabled manually
⚠️ - Circuit breaker open- No icon - Working normally
View Execution History:
# Last 10 executions
!eh_history
# Last 30 executions
!eh_history 30Manage Problematic Hooks:
# Disable a hook that's causing issues
!eh_disable bot_ready:on_bot_ready
# Re-enable when fixed
!eh_enable bot_ready:on_bot_ready
# Reset circuit breaker (if hook keeps failing)
!eh_reset_circuit command_executed:log_commandSet Alert Channel:
# Set current channel
!eh_alert_channel
# Set specific channel
!eh_alert_channel #hook-alertsAutomatic Alerts Sent For:
- Queue full (dropped events)
- Circuit breaker opens (hook disabled due to failures)
- Worker crashes (with restart attempt count)
- Max restart attempts reached
Built-in Events:
bot_ready- Bot becomes ready (kwargs:bot_user)guild_joined- Bot joins guild (kwargs:guild)guild_left- Bot leaves guild (kwargs:guild)command_executed- Command runs (kwargs:command_name,author,guild)command_error- Command error (kwargs:command_name,error,author,guild)
Custom Events:
# Emit custom event from your extension
await bot.emit_hook("custom_event", custom_param="value")Circuit Breaker Behavior:
- Hook fails 5 times within 5 minutes
- Circuit breaker opens (hook disabled)
- Hook disabled for 60 seconds
- Automatically closes after timeout
- Can manually reset with
!eh_reset_circuit
Performance Considerations:
- Each hook has 10-second timeout
- Queue processes sequentially (high-priority first)
- Average execution time tracked per hook
- Slow hooks should be optimized or disabled
Unregister Hooks:
# In cog_unload()
bot.unregister_hook("event_name", my_callback)View Current Health:
!fw_diagnosticsSet Alert Channel:
# Set current channel as alert channel
!fw_alert_channel
# Set specific channel
!fw_alert_channel #alertsWhat Gets Monitored:
-
Health Status:
- ✅ Healthy: Error rate < 5%
⚠️ Degraded: Error rate 5-9.9%- 🚨 Critical: Error rate ≥ 10%
-
System Metrics:
- Memory usage (MB)
- CPU percentage
- Active threads
- Open file handles
- Network connections
- Event loop lag (ms)
-
Bot Statistics:
- Uptime
- Latency
- Commands processed
- Error count
- Extensions loaded
- Servers/users/channels
Automatic Alerts: The system automatically sends alerts to your configured channel for:
- Health status changes (degraded/critical)
- Event loop lag above threshold (500ms)
- Repeated diagnostics write failures (3+ consecutive)
Diagnostics Files:
./data/framework_diagnostics.json- Complete system snapshot (updated every 5 min)./data/framework_health.json- Real-time health metrics (updated every 5 min)
Health Check Frequency:
- Event loop lag: Every 1 second
- Health monitoring: Every 5 minutes
- Diagnostics generation: Every 5 minutes
List All Plugins:
!pr_listShows all registered plugins with status indicators:
- ✅ - All checks passed
⚠️ - Has warnings (conflicts, scan errors)- ❌ - Missing dependencies
- 🔄 - Circular dependency detected
View Plugin Details:
!pr_info extension_nameShows:
- Version, author, description
- Commands and cogs provided
- Dependencies with version requirements
- Conflict status
- Circular dependency paths (if any)
- Scan errors (if any)
Validate Plugin:
!pr_validate extension_nameChecks if a plugin is safe to load by validating:
- All dependencies are met
- No conflicts with loaded plugins
- No circular dependencies
Toggle Enforcement:
# Toggle dependency enforcement
!pr_enforce deps
# Toggle conflict enforcement
!pr_enforce conflictsWhen enforcement is enabled (default):
- Plugins with issues trigger warnings
- Validation errors are logged
When enforcement is disabled:
- Plugins load regardless of issues
- Only informational warnings
Set Alert Channel:
# Set current channel
!pr_alert_channel
# Set specific channel
!pr_alert_channel #plugin-alertsAutomatic Alerts Sent For:
- Plugins loaded with missing dependencies
- Plugins loaded with conflicts
- Extension scan failures
- Circular dependency detection
Version Requirements:
In your extension, specify dependencies with versions:
# Supports: >=, >, ==, <=,
__dependencies__ = {
"other_extension": ">=1.0.0",
"another_ext": "==2.5.1"
}Conflict Declaration:
# List incompatible extensions
__conflicts__ = ["incompatible_ext", "old_version_ext"]Registry File:
- Location:
./data/plugin_registry.json - Auto-saved on changes
- Contains all plugin metadata
- Includes enforcement settings
- Higher priority = executes first
- Default priority: 0
- Range: any integer
- Example: priority=15 runs before priority=10
# View registered hooks (Owner only)
!hooks
# View execution history (Owner only)
!hookhistory [limit]
📺 VIDEO TUTORIAL COMING SOON!
A full YouTube video tutorial is in the works! It will cover:
- 🎬 Complete dashboard showcase and feature walkthrough
- ⚙️ Step-by-step setup guide from start to finish
- 💡 Tips and best practices for production use
- 🔧 Troubleshooting common issues
Keep an eye on the ZygnalBot YouTube channel or the Discord server for the announcement!
Live Monitor requires a PHP web server to host the dashboard. Any standard shared hosting works:
| Provider | Notes |
|---|---|
| Strato | Cheap, reliable German hosting - works great |
| Hostinger | Budget-friendly, good performance |
| Bluehost | Popular cPanel hosting |
| Any cPanel host | Standard PHP hosting works |
| VPS (Nginx/Apache) | Full control option |
Technical Requirements:
- PHP 7.4 or higher
- SQLite3 PHP extension (usually pre-installed)
- HTTPS strongly recommended
- ~50MB storage for dashboard + data files
- No MySQL/PostgreSQL required (uses SQLite)
Step 1: Run Quickstart Command
# Slash command
/livemonitor action:Quick Start (Setup + Files) url:https://yoursite.com/monitor
# Or prefix command
!livemonitor quickstart https://yoursite.com/monitorThis generates files in ./live_monitor_website/ folder.
Step 2: Upload Files to Your Server
Upload the entire contents of ./live_monitor_website/ to your web server:
yoursite.com/monitor/
├── index.php
├── receive.php
├── get_commands.php
├── send_command.php
├── lm_bootstrap.php
├── lm_db.php
├── lm_auth.php
├── setup.php
├── login.php
├── oauth_callback.php
├── logout.php
├── owner_audit.php
├── owner_roles.php
├── owner_db.php
├── backup_dashboard.php
└── assets/
└── (branding images if present)
Step 3: Claim Your Dashboard
- Visit
https://yoursite.com/monitor/setup.php - Enter the Setup Token shown in Discord after quickstart
- This one-time token prevents others from claiming your dashboard
- You become the Owner with full access
Step 4: Enable Monitoring
/livemonitor action:Enable
# or
!livemonitor enableYour dashboard is now live! Data updates every 2 seconds.
| Tab | What You Can Do |
|---|---|
| Dashboard | View bot status, latency graph, uptime, guild/user counts at a glance |
| Commands | See all commands with usage counts, filter by type (hybrid/prefix/slash), view errors |
| Plugins & Extensions | Manage extensions - reload/unload/load, view dependencies and conflicts |
| Event Hooks | Monitor hook execution times, circuit breaker status, disable problematic hooks |
| File System | View directory statistics, cache hit rates, storage usage |
| File Browser | Full file explorer - navigate, read, edit, create, delete files |
| Chat Console | Send messages to Discord channels directly from dashboard (experimental) |
| Guilds / Servers | List all servers with member counts, channels, owner info, leave servers |
| Events | Real-time event log - command executions, errors, guild joins/leaves |
| System | CPU/memory usage, thread count, open files, network connections |
| Bot Invite Helper | Generate invite links with customizable permissions |
| Database | Browse per-guild SQLite databases, view tables and data |
| Roles & Access | Manage dashboard users - assign Owner/Helper/Visitor roles |
| Security & Logs | View audit logs, login history, security events |
| Credits | Framework attribution (MUST remain visible per license) |
| Role | Capabilities |
|---|---|
| Owner | Full access - shutdown bot, leave guilds, manage roles, all file operations |
| Helper | Extension management, file operations, send chat messages, view all data |
| Visitor | Read-only access, view dashboard data, view chat history |
Granular Permissions:
control_core- Shutdown, diagnosticscontrol_plugins- Load/unload/reload extensionscontrol_files- File browser operationscontrol_chat- Send Discord messagescontrol_hooks- Enable/disable hookscontrol_guilds- Leave serverscontrol_backup- Create backupscontrol_marketplace- Download marketplace extensions
Check Status:
/livemonitor action:Status
# or
!livemonitor statusShows: enabled state, dashboard URL, last successful transmission, failure count, update interval.
Enable/Disable:
/livemonitor action:Enable
/livemonitor action:Disable
# or
!livemonitor enable
!livemonitor disableRegenerate Dashboard Files:
/livemonitor action:Get Files
# or
!livemonitor filesCreates fresh dashboard files without changing your tokens.
Change Update Interval:
/livemonitor action:Quick Start url:https://yoursite.com/monitor interval:10Set interval between 5-60 seconds (default: 5).
| Command | Description |
|---|---|
| Extension Management | |
reload_extension |
Hot-reload an extension without restart |
load_extension |
Load a new extension |
unload_extension |
Unload an extension |
| File Operations | |
read_file |
Read file contents |
write_file |
Create or overwrite files |
list_dir |
List directory contents |
rename_file |
Rename files or directories |
create_dir |
Create new directories |
delete_path |
Delete files or directories |
| Bot Control | |
shutdown_bot |
Gracefully stop the bot (Owner only) |
leave_guild |
Leave a Discord server (Owner only) |
backup_bot_directory |
Create backup archive (Owner only) |
clear_cache |
Clear bot caches |
send_chat_message |
Send message to Discord channel |
| Marketplace | |
fetch_marketplace_extensions |
Browse available extensions |
download_marketplace_extension |
Download and install extension |
load_downloaded_extension |
Load newly downloaded extension |
Location: ./data/live_monitor_config.json
{
"enabled": true,
"website_url": "https://yoursite.com/monitor",
"secret_token": "abc123...",
"setup_token": "xyz789...",
"update_interval": 5
}| Setting | Description |
|---|---|
enabled |
Whether monitoring is active |
website_url |
Your dashboard URL |
secret_token |
32-byte token for bot↔server auth |
setup_token |
One-time token for claiming dashboard |
update_interval |
Seconds between data transmissions |
| Category | Data Points |
|---|---|
| Bot Info | Username, ID, guild count, user count, latency, uptime |
| System | CPU%, memory MB/%, threads, open files, connections, platform |
| Guilds | Names, IDs, member counts, owners, channels (with NSFW status), join dates |
| Commands | All commands with type, usage count, last used, error count, aliases |
| Extensions | Loaded cogs, versions, authors, dependencies, conflicts |
| Hooks | Event hooks with execution counts, failure rates, circuit breaker status |
| Atomic FS | Cache size, hit rate, active locks, read/write counts |
| Events | Command executions, errors, guild joins/leaves, message activity |
- Use HTTPS - Tokens are transmitted in URLs
- Keep setup token secret - Only shown once after quickstart
- Monitor audit logs - Check Security tab regularly
- Limit Helper access - Only trusted users
- Regular backups - Use backup feature before major changes
Dashboard not receiving data:
- Check
!livemonitor statusfor failures - Verify URL is correct and accessible
- Check PHP error logs on server
- Ensure
receive.phphas write permissions
Can't claim dashboard:
- Setup token is one-time use
- Run quickstart again for new token
- Check if
lm_bootstrap.phpexists
Commands not executing:
- Check your role has required permissions
- View Security & Logs tab for denied commands
- Verify bot is running and connected
Data Integrity:
- Tempfile-based writes prevent partial updates
- Atomic move operations (all-or-nothing)
- Automatic retry on transient failures
- Lock-based concurrency control
- Cache invalidation on successful writes
Protection Against:
- Race conditions (per-file locks)
- Partial writes (tempfile staging)
- Data corruption (atomic moves)
- Concurrent access (lock management)
- Cache inconsistency (TTL + invalidation)
Monitoring:
- Real-time failure tracking
- Health status calculation
- Comprehensive operation logging
- Test suite for verification
- Full access to all commands
- Defined in
BOT_OWNER_IDenvironment variable - Cannot be overridden
- Access to server management commands
- Can configure command permissions
- Automatically detected via
guild.owner_id
- Per-command role requirements
- Set via
!configcommand - Stored in
config.json
- Uses native Discord permission checks
@commands.has_permissions()@commands.bot_has_permissions()
- No restrictions
- Available to all users
These commands cannot be configured for other users:
BOT_OWNER_ONLY_COMMANDS = [
"reload", "load", "unload", "sync",
"atomictest", "cachestats", "shardinfo",
"dbstats", "integritycheck", "cleanup"
]@commands.command()
@is_bot_owner()
async def owner_command(ctx):
await ctx.send("Owner only!")@commands.command()
@is_bot_owner_or_guild_owner()
async def management_command(ctx):
await ctx.send("Owner or guild owner!")@commands.command()
@has_command_permission()
async def configurable_command(ctx):
await ctx.send("Permission checked!")async def interaction_check(self, interaction):
if interaction.user != self.author:
await interaction.response.send_message(
"❌ Only the command user can use this!",
ephemeral=True
)
return False
return True- Default: 180–300 seconds
- Automatically disables interactions after timeout
- Prevents stale UI elements
Prevents:
- Data corruption during concurrent writes
- Partial file writes
- File locking issues
How it works:
- Write to temporary file
- Verify success
- Atomic move to final location
- Invalidate cache
- Write-Ahead Logging
- Concurrent reads during writes
- ACID compliant
- Crash recovery
- Per-guild isolation
- Automatic cleanup
- Lock-safe operation
- Automatic on shutdown
- Manual via
!dbstats - Timestamped backup files
- Per-file lock acquisition
- Automatic cleanup (500 lock threshold)
- Prevents concurrent write conflicts
- Unique bot identification
- Required for extension downloads
- Activation verification
- Mandatory acceptance
- Per-user tracking
- Enforces usage restrictions
- Extensions stored in isolated directory
- Never auto-executed
- Manual loading required
Default color scheme:
# Success
SUCCESS = 0x00ff00
# Error
ERROR = 0xff0000
# Warning
WARNING = 0xffff00
# Info
INFO = 0x5865f2
# Main Menu
MAIN_MENU = 0x2b2d31
# Credits
CREDITS = 0xffd700embed = discord.Embed(
title="Custom Title",
description="Custom Description",
color=0x9b59b6 # Purple
)Common Unicode emojis:
# Status
"✅" # Success
"❌" # Error
"⚠️" # Warning
"ℹ️" # Info
# Actions
"🔄" # Reload
"📊" # Stats
"⚙️" # Settings
"🔧" # Tools
# Navigation
"◀" # Previous
"▶" # Next
"🏠" # Home
# Categories
"📚" # Help
"📦" # Extensions
"🗄️" # Database
"📊" # StatisticsEdit config.json:
{
"status": {
"type": "watching",
"text": "{guilds} servers | {users} users"
}
}playingwatchinglisteningcompeting
{guilds}– Total server count{users}– Total user count{commands}– Total command count
{
"prefix": "?"
}!setprefix ?@bot.hybrid_command(name="myhelp")
async def custom_help(ctx):
embed = discord.Embed(
title="My Custom Help",
description="Custom help menu",
color=0x5865f2
)
# Add your fields
await ctx.send(embed=embed)Then disable the built-in help in main.py:
Then disable the built-in help in main.py:
bot = BotFrameWork(
command_prefix=lambda b, m: b.get_prefix(m),
intents=intents,
help_command=None, # Disable built-in help
# ... other options
)The Shard Monitor (cogs/shard_monitor.py) provides real-time visibility into your bot's shard health, latency, events, and reliability. It features an interactive dashboard with button navigation, automatic health alerts, persistent metrics, and detailed per-shard diagnostics.
All commands are restricted to the Bot Owner (BOT_OWNER_ID from .env). No regular users or guild owners can access shard monitoring data.
The Shard Monitor uses a dual-toggle system:
.envtoggle (takes precedence):
ENABLE_SHARD_MONITOR=true # Enable the cog
ENABLE_SHARD_MONITOR=false # Disable the cog completelyconfig.jsontoggle (secondary):
"framework": {
"enable_shard_monitor": true
}The cog's setup() function checks the .env variable first. If disabled, the cog never loads:
async def setup(bot):
enabled = os.getenv("ENABLE_SHARD_MONITOR", "true").lower()
if enabled not in ("true", "1", "yes"):
logger.info("ShardMonitor cog is DISABLED via ENABLE_SHARD_MONITOR env var")
return
await bot.add_cog(ShardMonitor(bot))The Shard Monitor runs three background tasks that collect and evaluate data:
┌─────────────────────────────────────────────────────────────┐
│ Shard Monitor Tasks │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ collect_ │ │ health_ │ │ save_metrics │ │
│ │ metrics │ │ check │ │ │ │
│ │ (30s loop) │ │ (60s loop) │ │ (5min loop) │ │
│ │ │ │ │ │ │ │
│ │ Records │ │ Evaluates │ │ Persists to │ │
│ │ latency from │ │ health for │ │ shard_metrics │ │
│ │ each shard │ │ all shards │ │ .json on disk │ │
│ │ │ │ Sends alerts │ │ │ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
│ │
│ Event Listeners: │
│ on_message → per-shard message counter │
│ on_command → per-shard command counter │
│ on_shard_connect → connection tracking + downtime end │
│ on_shard_disconnect → disconnection tracking + downtime │
│ on_shard_resumed → reconnection tracking │
│ on_shard_ready → ready event tracking │
│ on_guild_join → per-shard guild join counter │
│ on_guild_remove → per-shard guild leave counter │
└─────────────────────────────────────────────────────────────┘
Run !shardmonitor or /shardmonitor to get the interactive dashboard:
!shardmonitorThe dashboard displays with navigation buttons at the bottom:
- 📊 Overview — Cluster-wide stats, per-shard summary, alert configuration
- 🏥 Health — Full health report with critical/warning/healthy breakdown
- 📡 Latency — Visual latency bars per shard with min/avg/max statistics
- 📈 Events — Per-shard counters for messages, commands, connects, disconnects, errors
- 🔄 Refresh — Refresh the current tab with latest data
Only the command author can interact with the buttons (validated via interaction_check).
# Inspect shard 0 in detail
!sharddetails 0Shows:
- Basic info: guilds, members, current/avg/min/max latency
- Activity: messages processed, commands executed, guild joins/leaves
- Reliability: uptime %, connect/disconnect/reconnect counts
- Errors: total count, consecutive failures, last error details with timestamp
- Connection history: last connect/disconnect timestamps
# Set alert channel with custom threshold
!shardalerts #shard-alerts 5
# Disable alerts
!shardalertsAlert configuration persists to ./data/shard_monitor/alert_config.json:
{
"alert_channel_id": 1234567890123456789,
"alert_threshold": 5
}When an unhealthy shard is detected during the 60-second health check cycle, an embed is sent to the configured channel showing the affected shards and their issues.
# Reset a specific shard
!shardreset 0
# Reset ALL shards
!shardreset -1Step 1 — Single shard (simplest test):
SHARD_COUNT=1
ENABLE_SHARD_MONITOR=trueStart the bot. Wait 30 seconds, then run !shardmonitor. You should see shard 0 with health status 🟢.
Step 2 — Two shards in one process:
SHARD_COUNT=2
SHARD_IDS=
ENABLE_SHARD_MONITOR=trueNow !shardmonitor shows two shards. Check latency and guild distribution.
The Shard Manager (cogs/shard_manager.py) enables running your bot's shards across multiple processes or even different servers. It provides an IPC (Inter-Process Communication) layer using TCP sockets so separate processes can coordinate, share stats, and communicate.
All commands are Bot Owner Only. The cog is disabled by default — only enable it when you actually need multi-process sharding.
| Scenario | Need Shard Manager? |
|---|---|
| < 2,500 guilds | ❌ No — single process is fine |
| 2,500 - 5,000 guilds | Maybe — if you experience performance issues |
| 5,000+ guilds | ✅ Yes — split across processes |
| Multiple servers/VPS | ✅ Yes — essential for coordination |
| Just want monitoring | ❌ No — use Shard Monitor instead |
Discord requires sharding at 2,500 guilds and recommends it earlier for larger guilds.
┌──────────────────────────────────────────────────┐
│ IPC Network │
│ │
│ ┌─────────────┐ TCP/IP ┌─────────────┐ │
│ │ Cluster 0 │◄──────────►│ Cluster 1 │ │
│ │ (Server) │ │ (Client) │ │
│ │ Shards 0-2 │ │ Shards 3-5 │ │
│ │ 500 guilds │ │ 500 guilds │ │
│ └─────────────┘ └─────────────┘ │
│ ▲ │
│ │ TCP/IP │
│ └──────────────────►┌─────────────┐ │
│ │ Cluster 2 │ │
│ │ (Client) │ │
│ │ Shards 6-8 │ │
│ │ 500 guilds │ │
│ └─────────────┘ │
└──────────────────────────────────────────────────┘
- One cluster runs as
server(IPC server mode) — hosts the TCP server - Additional clusters run as
client— connect to the server - All clusters exchange stats, health data, and can broadcast messages
ENABLE_SHARD_MANAGER=trueAnd in config.json:
"framework": {
"enable_shard_manager": true
}For a bot with 6 shards split across 2 processes on the same machine:
Process 1 (.env):
DISCORD_TOKEN=your_token
BOT_OWNER_ID=123456789
SHARD_COUNT=6
SHARD_IDS=0,1,2
ENABLE_SHARD_MANAGER=true
SHARD_IPC_MODE=server
SHARD_IPC_HOST=127.0.0.1
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=my_super_secret_key_123
SHARD_CLUSTER_NAME=cluster-0Process 2 (.env.cluster1):
DISCORD_TOKEN=your_token
BOT_OWNER_ID=123456789
SHARD_COUNT=6
SHARD_IDS=3,4,5
ENABLE_SHARD_MANAGER=true
SHARD_IPC_MODE=client
SHARD_IPC_HOST=127.0.0.1
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=my_super_secret_key_123
SHARD_CLUSTER_NAME=cluster-1Start Process 1 first (the server), then Process 2. The client will auto-connect.
Same concept, but change the IPC host:
Server A (primary):
SHARD_IPC_MODE=server
SHARD_IPC_HOST=0.0.0.0
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=very_long_random_secret_here
SHARD_CLUSTER_NAME=us-east-1
SHARD_COUNT=9
SHARD_IDS=0,1,2Server B (secondary):
SHARD_IPC_MODE=client
SHARD_IPC_HOST=<Server_A_IP_Address>
SHARD_IPC_PORT=20000
SHARD_IPC_SECRET=very_long_random_secret_here
SHARD_CLUSTER_NAME=us-west-1
SHARD_COUNT=9
SHARD_IDS=3,4,5
⚠️ Important: TheSHARD_IPC_SECRETmust be identical on ALL clusters. The server must bind to0.0.0.0(not127.0.0.1) for remote connections. Ensure the port is open in your firewall.
The IPC system uses a length-prefixed TCP protocol:
┌────────────┬──────────────────────────┐
│ 4 bytes │ N bytes │
│ (uint32 BE)│ (JSON payload) │
│ = N │ │
└────────────┴──────────────────────────┘
Message Types:
| Operation | Direction | Description |
|---|---|---|
auth |
Client → Server | Authentication with secret + cluster info |
auth_response |
Server → Client | Success/failure response |
heartbeat |
Client → Server | Keep-alive (every 30s) with guild count |
heartbeat_ack |
Server → Client | Heartbeat acknowledgement |
stats_broadcast |
Bidirectional | Cluster statistics update (every 60s) |
cluster_join |
Server → Clients | New cluster connected notification |
cluster_leave |
Server → Clients | Cluster disconnected notification |
broadcast_message |
Bidirectional | Text message broadcast from owner |
Security:
- Shared secret authentication on every connection
- 1MB max message size, nonce deduplication
- 10-second auth timeout for unauthenticated connections
- No arbitrary code execution — only safe preset queries
The IPC client has built-in reconnection with exponential backoff:
| Attempt | Delay |
|---|---|
| 1st | 5 seconds |
| 2nd | 10 seconds |
| 3rd | 20 seconds |
| 4th | 40 seconds |
| ... | up to 120 seconds max |
On successful reconnection, the delay resets to 5 seconds.
# View all connected clusters
!clusters
# Check IPC connection diagnostics
!ipcstatus
# Broadcast a message to all clusters
!broadcastmsg Deploying update in 5 minutes/clusters shows:
- Per-cluster stats (guilds, users, shards, latency, uptime)
- Connection health indicators (🟢🟡🔴)
- Global totals across all clusters
- IPC server/client status
Same machine, two processes:
- Set up two copies of your bot directory (or use different
.envfiles) - Configure Process 1 as
serverwithSHARD_IDS=0, Process 2 asclientwithSHARD_IDS=1 - Start Process 1 first, then Process 2
- Run
!clusterson either process — should show both clusters - Run
!ipcstatusto verify the TCP connection - Run
!broadcastmsg Hello from cluster-0to test broadcast
┌──────────────────────────────────────────────────────┐
│ Backup & Restore v2.1.0 │
│ │
│ ┌──────────┐ ┌───────────┐ ┌──────────────┐ │
│ │ Snapshot │───▶│ Atomic │───▶│ Storage │ │
│ │ Capture │ │ File Sys │ │ Index │ │
│ └──────────┘ └───────────┘ └──────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌──────────┐ ┌──────────┐ ┌──────────────────┐ │
│ │ Roles │ │ Channels │ │ Member Roles │ │
│ │ Perms │ │ Overwrites│ │ (per-user) │ │
│ └──────────┘ └──────────┘ └──────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Interactive Dashboard (5 Tabs) │ │
│ │ Overview │ Backups │ Compare │ Audit │ Stats │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Safety & Protection │ │
│ │ Cooldowns │ Pins │ Checksums │ Audit Log │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Automation & Scheduling │ │
│ │ Auto-Backup │ Retention Cleanup │ Scheduling │ │
│ └─────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────┘
- Enable the cog (enabled by default):
ENABLE_BACKUP_RESTORE=true- Create your first backup:
/backupcreate Before server reorganization
- View the dashboard:
/backup
- Restore if needed (with selective component toggles):
/backuprestore abc123def456
- Pin important backups to protect them:
/backuppin abc123def456
- Set up auto-backups:
/backupschedule enable 24
| User Level | Create | Restore | View | Delete | Pin | Schedule | Diff | Export | Stats |
|---|---|---|---|---|---|---|---|---|---|
| Bot Owner | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Administrator | ✅ | ✅ | ✅ | ✅ own + admin | ✅ | ✅ | ✅ | ❌ | ❌ |
| Regular User | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
| Variable | Default | Description |
|---|---|---|
ENABLE_BACKUP_RESTORE |
true |
Enable/disable the Backup & Restore cog |
BACKUP_MAX_PER_GUILD |
25 |
Maximum backup snapshots per guild |
BACKUP_COOLDOWN |
300 |
Seconds between backup creations per guild |
BACKUP_AUTO_INTERVAL |
0 |
Hours between auto-backups (0 = disabled, set > 0 to enable scheduler loop) |
BACKUP_RETENTION_DAYS |
0 |
Days to keep unpinned backups (0 = keep forever) |
"framework": {
"enable_backup_restore": true
}The backup system captures which roles each non-bot member has at backup time. On restore, it reapplies those roles to members who are still in the server.
Requirements:
- Members Gateway Intent must be enabled in your bot's Developer Portal settings
- Without this intent, member roles will be empty in backups (everything else still works)
How it works:
- During backup: chunks the guild to load all members, saves their non-managed, non-default role IDs and names
- During restore (safe mode, default): for each member still in the server, adds back roles they're missing
- During restore (Role Sync ON): adds missing roles AND removes roles the member has now but didn't have at backup time — fully rewinding their roles to the exact backup state
- Rate-limited at ~2 members/sec to respect Discord API limits
Role Sync example:
- Backup state: TheZ1 has
Member, Admin, Helper, HR - Current state: TheZ1 has
Member, HR, Noob - Safe mode (default): adds
Admin, Helperback.Noobstays. - Role Sync ON: adds
Admin, Helperback. RemovesNoob. TheZ1 is exactly as they were.
Abuse Prevention:
- 5-minute cooldown between backup creations (bot owner gets bypass notification instead of silent skip)
- Maximum 25 backups per guild — delete old ones to free space
- Backup label length limited to 100 characters
- Interaction author verification on all buttons — only the command invoker can interact
Pin Protection:
- Pinned backups cannot be deleted manually or by retention cleanup
- Pin/unpin with
/backuppin <id>
Restore Protection:
- Selective component toggles — choose exactly what to restore
- Role Sync mode (off by default) — destructive mode that removes roles not in backup. Protected behind explicit toggle.
- Two-step confirmation dialog with danger-colored button
- Restore only creates missing items — never deletes existing ones
- Per-guild restore lock prevents concurrent restore operations
- Real-time progress updates during restore
- Detailed error reporting if any items fail to create
Data Integrity:
- SHA-256 checksum stored per backup, verifiable with
/backupverify - Atomic file system integration prevents corruption during writes
- Individual snapshot files with UUID-based IDs
Timezone Handling:
- All timestamps stored as UTC-aware ISO 8601 strings
- Discord's
<t:epoch:R>formatting displays correctly in every user's local timezone - Backward-compatible with legacy naive timestamps from older backup versions
The restore engine is non-destructive and selective. It compares the backup snapshot against the current guild state and only creates items that are missing:
| Scenario | Behavior |
|---|---|
| Role exists (by name) | Skipped — existing role kept |
| Role missing | Created with backed-up permissions, color, and settings |
| Channel exists (by name) | Skipped — existing channel kept |
| Channel missing | Created with backed-up topic, slowmode, overwrites, and category |
| Category exists (by name) | Skipped — existing category kept |
| Category missing | Created with backed-up permission overwrites |
| Member still in server | Missing roles from backup are re-applied |
| Member still in server (Role Sync ON) | Roles fully rewound: missing roles added, extra roles removed |
| Member left server | Skipped — cannot apply roles to absent members |
| Bot prefix in backup | Restored to guild database with cache invalidation |
| Mention prefix setting | Restored to guild database |
- Run
/backupto open the dashboard — explore all 5 tabs - Run
/backupcreate Test backupto create a snapshot - Run
/backupview <id>to inspect it — check member role count - Run
/backup→ Compare tab to see drift analysis - Delete a test channel, then run
/backuprestore <id>to restore it - Verify the channel was recreated with correct settings and permissions
- Run
/backuppin <id>to protect important backups - Run
/backupverify <id>to confirm integrity - Run
/backupdiff <id_a> <id_b>to compare two backups
Error: DISCORD_TOKEN not found in .env!
Solution:
- Create
.envfile in root directory - Add:
DISCORD_TOKEN=your_token_here - Ensure no quotes around token
- Ensure file is named
.envnot.env.txt
Error: BOT_OWNER_ID not found in .env!
Solution:
- Add to
.env:BOT_OWNER_ID=your_user_id - Get ID by enabling Developer Mode in Discord
- Right-click your username → Copy ID
Error: discord.ext.commands.errors.ExtensionFailed
Solution:
- Check logs:
cat botlogs/current_run.log - Look for syntax errors in extension
- Ensure all imports are available
- Use
!marketplace fixdepsfor missing packages
High Cache Miss Rate (<50%):
Solution:
- Check if files are being modified externally
- Verify cache TTL isn't too short (default: 300s)
- Run
!atomicstatsto view statistics - Consider increasing
max_cache_sizein code
Many Active Locks (>100):
Solution:
- Check
!atomicstatsfor lock count - Locks cleanup automatically at 500 threshold
- Restart bot if locks are permanently stuck
- Review code for proper async/await usage
Write Failures:
Solution:
- Check file permissions in
./datadirectory - Ensure sufficient disk space
- Verify no external process is locking files
- Check
!atomicstatsfor failure patterns - Review logs for specific error messages
Cache Not Invalidating:
Solution:
# Manual invalidation in code
global_file_handler.invalidate_cache("./data/problematic_file.json")
# Or clear all cache
global_file_handler.clear_all_cache()Performance Degradation:
Solution:
- Check
!atomicstatsfor health status - If failure rate >5%, check disk I/O
- Monitor lock count (should be <50 normally)
- Run
!atomictestto verify system health - Consider restarting bot if critical
Check logs:
# Linux/Mac
cat botlogs/current_run.log | grep -i "extension"
# Windows
findstr /i "extension" botlogs\current_run.logCommon Issues:
- Missing
setupfunction
# Required in every extension
async def setup(bot):
await bot.add_cog(YourCog(bot))-
Syntax errors
- Check Python syntax
- Ensure proper indentation
- Validate imports
-
Extension in blacklist
- Check
config.json→extensions.blacklist - Remove extension name from list
- Check
-
File not in
extensions/directory- Move file to
./extensions/ - Ensure
.pyextension
- Move file to
-
Spaces in filename
- Framework auto-renames to underscores
- Use
!load extension_name(with underscores)
-
Missing dependencies
- Use
!marketplace fixdeps - Or manual:
pip install package_name
- Use
Manual sync:
!syncRate Limiting:
- Discord limits syncs to ~2 per hour
- Bot automatically waits and retries
- Check logs for retry messages
- Wait 1 hour if rate limited
Slash Command Limit Reached:
# Check current usage
!slashlimit
# If at limit (100 commands):
# - New extensions become prefix-only
# - Existing slash commands still work
# - Unload unused extensions to free slotsVerification:
# Check registered commands
!extensions
# View slash command count
!statsError: database is locked
Solution:
- Ensure only one bot instance running
- Wait for WAL checkpoint to complete
- Restart bot if persists
Backup and Reset:
# Backup current database
cp data/main.db data/main.db.backup
cp -r data/[guild_id] data/[guild_id].backup
# Delete database (will regenerate)
rm data/main.db
rm -rf data/[guild_id]
# Restart bot
python main.pyCheck Database Stats:
!dbstats"Missing Permissions" error:
Solution:
- Check bot has required Discord permissions
- Verify role hierarchy (bot role above target roles)
- Enable necessary intents in Developer Portal
- Check bot permissions in channel settings
"You don't have permission" error:
Solution:
- Check command permissions:
!config - Verify your roles match requirements
- Contact bot owner for access
- Check if command is owner-only
High Memory Usage:
Solution:
- Run
!cleanupto clear caches - Check
!cachestatsfor large caches - Reduce cache TTL in
atomic_file_system.py - Restart bot periodically
Slow Command Response:
Solution:
- Check
!statsfor latency - View
!dbstatsfor connection issues - Run
!integritycheckfor system health - Check database file sizes
- Consider sharding for large bots
"Invalid or not activated" ZygnalID:
Solution:
- Get ID:
!marketplace myid(Owner only) - Join ZygnalBot Discord:
gg/sgZnXca5ts - Verify yourself in server
- Open ticket for "Zygnal ID Activation"
- Provide your ZygnalID in ticket
Extension Install Failed:
Solution:
- Check error message for details
- Verify bot has write permissions to
./extensions - Ensure sufficient disk space
- Try
!marketplace refresh - Check logs:
botlogs/current_run.log
Missing Dependencies After Install:
Solution:
# Automatic fix
!marketplace fixdeps
# Manual fix
pip install package_name
!reload extension_nameIssue: File changes not detected
Solution:
- Check
config.json→auto_reload: true - Ensure file in
./extensionsdirectory - Wait 30 seconds for check cycle
- Use manual reload:
!reload extension_name - Check logs for reload errors
Cog doesn't load:
Solution:
- Check
.envhasENABLE_SHARD_MONITOR=true - Check
config.jsonhas"enable_shard_monitor": true - Verify the file exists at
cogs/shard_monitor.py - Check logs:
grep "ShardMonitor" botlogs/current_run.log
No metrics showing / "No activity" warnings:
Solution:
- Wait 30+ seconds after startup for first collection cycle
- The 5-minute inactivity threshold may trigger on low-traffic bots
- Run
!shardreset -1to reset all metrics and start fresh
Alerts not firing:
Solution:
- Verify alert channel is set:
!shardalerts #channel - Check
./data/shard_monitor/alert_config.jsonexists - Ensure bot has Send Messages permission in the alert channel
- Wait for the 60-second health check cycle
Cog doesn't load:
Solution:
- Check
.envhasENABLE_SHARD_MANAGER=true - Note: it's disabled by default (
false)
"Auth failed" when connecting:
Solution:
- Verify
SHARD_IPC_SECRETis identical on all clusters - Check for trailing whitespace in the
.envvalue - Ensure the server cluster is running before starting clients
Can't connect from another machine:
Solution:
- Server must use
SHARD_IPC_HOST=0.0.0.0(not127.0.0.1) - Check firewall allows port
SHARD_IPC_PORT(default: 20000) - Verify the client's
SHARD_IPC_HOSTpoints to the server's IP address - Check logs for connection errors:
grep "IPC" botlogs/current_run.log
"Using default secret" warning:
Solution:
Set a proper secret in .env:
SHARD_IPC_SECRET=my_long_random_secret_string_hereCluster shows 🔴 (disconnected):
Solution:
- Check if the remote process is still running
- Heartbeat timeout is 120 seconds — wait and check again
- Check network connectivity between machines
- Client auto-reconnects with exponential backoff (5s → 120s)
Commands not showing:
Solution:
- Check command has
helpparameter - Ensure command not marked
hidden=True - Verify cog loaded:
!extensions - Check command registered:
!stats
Dropdown not working:
Solution:
- Ensure only command requester can use menu
- Check view hasn't timed out (180s)
- Verify bot has "Use Application Commands" permission
- Try rerunning command
Backup creation fails:
Solution:
- Check
./data/backups/directory has write permissions - Verify you haven't hit the 25-backup limit:
/backup→ Overview tab - Wait for cooldown to expire (5 minutes between backups)
- Check bot logs for
BackupRestore:error messages
Restore not creating items:
Solution:
- Restore only creates missing items — it skips existing roles/channels by name
- Ensure bot has Administrator permission in the server
- Ensure bot's role is above the roles it needs to create in the role hierarchy
- Check the results embed for "Skipped" and "Failed" counts
Permission denied on backup commands:
Solution:
- Backup commands require Administrator permission or Bot Owner status
/backupexportis restricted to Bot Owner only- Non-admin users cannot delete backups they didn't create
- Ensure the command is not disabled in
config.json(enable_backup_restore: false)
Backup data directory not found:
Solution:
- The
./data/backups/directory is auto-created on first use - Check filesystem permissions for the bot process
- Verify the atomic file system is working:
!atomictest
Cache Strategy:
# Frequently read files - USE cache
config = await global_file_handler.atomic_read_json(
"config.json",
use_cache=True # Fast repeated reads
)
# Rarely read files - BYPASS cache
log_data = await global_file_handler.atomic_read_json(
"large_log.json",
use_cache=False # Don't pollute cache
)
# After bulk updates - CLEAR cache
await process_many_files()
global_file_handler.clear_all_cache()Lock Optimization:
# Bad: Multiple separate operations
for file in files:
data = await read_file(file)
await write_file(file, process(data))
# Good: Batch operations
all_data = {}
for file in files:
all_data[file] = await read_file(file)
for file, data in all_data.items():
await write_file(file, process(data))Monitoring Health:
# Regular health checks
!atomicstats # View overall health
# Performance testing
!atomictest # Verify operation speedsBest Practices:
- Use cache for config files (read-heavy)
- Bypass cache for log files (write-heavy)
- Invalidate cache after critical writes
- Monitor failure rate (should be <1%)
- Run cleanup during low-activity periods
Use Transactions for Bulk Operations:
async with bot.db.conn.execute("BEGIN"):
for item in items:
await bot.db.conn.execute(
"INSERT INTO table VALUES (?)",
(item,)
)
await bot.db.conn.commit()Index Frequently Queried Columns:
await conn.execute(
"CREATE INDEX IF NOT EXISTS idx_user_id ON my_table(user_id)"
)Use LIMIT for Large Queries:
async with conn.execute(
"SELECT * FROM large_table LIMIT 100"
) as cursor:
rows = await cursor.fetchall()Use Caching for Read-Heavy Operations:
# Enable caching (300s TTL)
data = await global_file_handler.atomic_read_json(
filepath,
use_cache=True
)Disable Caching for Real-Time Data:
data = await global_file_handler.atomic_read_json(
filepath,
use_cache=False
)Batch File Operations:
# Bad: Multiple writes
for item in items:
await global_file_handler.atomic_write_json(f"data/{item}.json", item_data)
# Good: Single write
combined_data = {item: item_data for item in items}
await global_file_handler.atomic_write_json("data/all_items.json", combined_data)Batch Messages:
# Bad: Individual messages
for user in users:
await channel.send(f"Hello {user}")
# Good: Single message
await channel.send(f"Hello {', '.join(str(u) for u in users)}")Use Embeds for Rich Content:
# Embeds are more efficient than multiple messages
embed = discord.Embed(title="Data")
for key, value in data.items():
embed.add_field(name=key, value=value)
await channel.send(embed=embed)Cache Guild/Member Data:
# Use intents to cache data
intents = discord.Intents.all()
# Access cached data (no API call)
member = guild.get_member(user_id)Blacklist Unused Extensions:
{
"extensions": {
"blacklist": ["debug_cog", "test_extension"]
}
}Profile Extension Load Times:
# View load times
!extensions
# Check diagnostics
!diagnosticsRegular Cleanup:
# Run periodically
!cleanupMonitor Cache Usage:
!cachestatsLimit Background Tasks:
# Increase interval for non-critical tasks
@tasks.loop(hours=6) # Instead of minutes=5
async def background_task(self):
passFor bots in 2000+ guilds:
# Basic sharding (single process, multiple shards)
SHARD_COUNT=2
SHARD_IDS=0,1Enable shard monitoring for visibility:
ENABLE_SHARD_MONITOR=trueFor large bots (5000+ guilds), use multi-process sharding:
# Process 1: shards 0-2
SHARD_COUNT=6
SHARD_IDS=0,1,2
ENABLE_SHARD_MANAGER=true
SHARD_IPC_MODE=server
SHARD_IPC_SECRET=your_secret
SHARD_CLUSTER_NAME=cluster-0
# Process 2: shards 3-5
SHARD_COUNT=6
SHARD_IDS=3,4,5
ENABLE_SHARD_MANAGER=true
SHARD_IPC_MODE=client
SHARD_IPC_SECRET=your_secret
SHARD_CLUSTER_NAME=cluster-1Benefits:
- Distributes load across processes
- Reduces per-process memory
- Improved stability
- Better rate limit handling
- Cross-shard stat aggregation via IPC
- Automatic health monitoring and alerts
Monitoring Commands:
!shardmonitor # Interactive dashboard
!shardhealth # Quick health check
!clusters # View all clusters (requires Shard Manager)MIT License + Additional Terms
Copyright (c) 2025 TheHolyOneZ
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
ADDITIONAL TERMS:
1. The file main.py, and any version or derivative thereof, remains under
the MIT License and can be freely modified, provided that this license
and the original copyright notice remain intact.
2. The CreditsButton class (as originally defined in the Software) must
remain present in all distributed, forked, or modified versions of the Software.
Its functionality and visibility must not be removed or obscured.
Specifically:
- The Credits Button must continue to exist and be displayed in the same
interface location as in the original version.
- The Credits Button must contain visible credit to the original author,
"TheHolyOneZ", and a link or reference to the original repository:
https://github.com/TheHolyOneZ/discord-bot-framework
- The textual credit contents (embed fields such as "Created By", "License",
and related original attribution text) must remain clearly visible and
intact. Additional information may be added, but the original credits must
not be removed, replaced, or hidden.
3. Altering, deleting, or renaming the author's name "TheHolyOneZ" in this
license or within the Credits Button is strictly prohibited.
4. The discordbotframework command (including its aliases framework and
botinfo) as defined in the Software must remain intact. This includes
its function body and the original list of "Framework Features" and "User
Commands" in its generated embed. Functionality or content that provides
credit or information about the original framework must not be removed,
modified, or obscured. Additional fields or information may be added.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| Component | Requirement |
|---|---|
main.py |
Freely modifiable under MIT, keep license & copyright |
| CreditsButton class | Must remain visible and functional in same location |
| "TheHolyOneZ" attribution | Cannot be removed, altered, or renamed anywhere |
| Repository link | Must link to original GitHub repo |
!discordbotframework command |
Must remain with original features and credits |
| Live Monitor Credits tab | © 2025 TheHolyOneZ - NOT covered by MIT, must remain visible |
The Credits tab and visual design of the Live Monitor dashboard (cogs/live_monitor.py) are separately copyrighted and are NOT covered by the MIT license:
- © 2025 TheHolyOneZ
- The Credits section (layout, wording, and SVG crown artwork) MUST remain clearly visible at all times
- This applies to any use, modification, fork, or redistribution of the dashboard
- The Credits tab cannot be hidden, removed, or obscured
Extensions downloaded through the Extension Marketplace have additional licensing terms:
| Requirement | Description |
|---|---|
| Ecosystem Only | Extensions are only usable within the ZygnalBot ecosystem (including Zoryx Bot Framework) |
| Attribution Protected | Cannot remove or alter: ZygnalBot, zygnalbot, TheHolyOneZ, TheZ |
| Individual Licenses | Each extension may have its own additional license terms - respect them |
| No Redistribution | Extensions cannot be redistributed outside authorized ZygnalBot systems |
| ZygnalID Required | Valid, activated ZygnalID required for marketplace access |
- Immediate ZygnalID deactivation
- Permanent service ban
- Potential legal action for severe violations
Contributions are welcome! Here's how to contribute:
- Fork the Repository
git clone https://github.com/yourusername/discord-bot-framework.git
cd discord-bot-framework- Create Feature Branch
git checkout -b feature/amazing-feature-
Test Thoroughly
- Ensure bot starts without errors
- Test all affected commands
- Verify extensions load correctly
- Check for memory leaks
-
Follow Code Style
- Use type hints
- Add docstrings to functions
- Follow PEP 8 guidelines
- Use meaningful variable names
- Comment complex logic
-
Update Documentation
- Update README.md if adding features
- Add docstrings to new functions
- Update CONTRIBUTING.md if needed
-
Commit Changes
git add .
git commit -m "Add amazing feature"- Push to Branch
git push origin feature/amazing-feature- Open Pull Request
- Describe changes clearly
- Reference any related issues
- Include screenshots if UI changes
async def example_function(param: str) -> dict:
"""
Brief description of function.
Args:
param: Description of parameter
Returns:
Description of return value
Raises:
ValueError: When param is invalid
"""
if not param:
raise ValueError("param cannot be empty")
result = {"status": "success", "data": param}
return resultHigh Priority:
- Bug fixes
- Performance improvements
- Documentation improvements
- Extension examples
- Test coverage
Medium Priority:
- New framework features
- Additional framework cogs
- UI/UX improvements
- Logging enhancements
Low Priority:
- Code refactoring
- Style improvements
- Comment additions
Use GitHub Issues with this template:
**Bug Description:**
Clear description of the bug
**Steps to Reproduce:**
1. Step one
2. Step two
3. Error occurs
**Expected Behavior:**
What should happen
**Actual Behavior:**
What actually happens
**Environment:**
- Python version: 3.x.x
- discord.py version: 2.x.x
- OS: Windows/Linux/Mac
**Logs:**Relevant log output
Use GitHub Issues with this template:
**Feature Description:**
Clear description of the feature
**Use Case:**
Why this feature is needed
**Proposed Implementation:**
How it could be implemented
**Alternatives Considered:**
Other approaches consideredNeed help? Have questions?
- GitHub Issues: Report bugs or request features
- GitHub Discussions: Ask questions and discuss
- ZygnalBot Discord:
gg/sgZnXca5ts(For marketplace support)
- discord.py: https://discordpy.readthedocs.io/
- Discord Developer Portal: https://discord.com/developers/applications
- Python asyncio: https://docs.python.org/3/library/asyncio.html
- SQLite: https://www.sqlite.org/docs.html
- aiofiles: https://github.com/Tinche/aiofiles
- aiosqlite: https://aiosqlite.omnilib.dev/
- ZygnalBot Framework: https://zsync.eu/zdbf/
- Extension Marketplace: https://zsync.eu/extension/
Discord Bot Development:
Python Async Programming:
Database Management:
Want to see the framework in action? Check the /images directory for screenshots:
- Terminal-1.png - Bot startup with Rich console
- HelpMenu-Example.png - Interactive help system
- Marketplace-Preview.png - Extension marketplace
- Diagnostics.png - Framework diagnostics dashboard
- And more!
IMPORTANT NOTE: If you are using this framework, please be aware that you are solely responsible for complying with applicable data protection laws in your country or region. The framework records only login events and actions performed in the web dashboard in the audit log database table on your own server. These logs exist on your server, but I do not have access to them and the framework does not transmit or use them in any way. You are responsible for following the data protection guidelines that apply to your location and for ensuring that any data stored on your server, including these logs, is handled appropriately.
TheHolyOneZ
- GitHub: @TheHolyOneZ
- Website: zsync.eu/zdbf/
- Discord: theholyonez
