diff --git a/README.md b/README.md index cdf92bd..477e66a 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers ## Table of Contents - [Features](#features) - [Installation](#installation) + - [Discord Bot Setup](#discord-bot-setup) - [Traditional Installation](#traditional-installation) - [Docker Installation](#docker-installation) - [Configuration](#configuration) @@ -23,34 +24,150 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers ## Features -### Core Functionality -- **Real-time Server Monitoring**: Auto-updating embeds showing server status (online/offline) and detailed resource usage -- **Power Management**: Start, stop, and restart servers directly from Discord with button controls -- **Connection Information**: One-click display of server addresses and ports -- **Multi-channel Support**: Status embeds can be placed in any channel with proper permissions +### 🎮 Server Management +- **Interactive Server Selection**: Choose servers from an intuitive dropdown menu showing all available game servers +- **Real-time Power Controls**: Start, stop, and restart servers with color-coded button controls + - đŸŸĸ Green Start button + - 🔴 Red Stop button + - đŸ”ĩ Blue Restart button +- **Connection Information**: Instantly view server IP addresses and ports with the "Show Address" button +- **Multi-channel Embeds**: Deploy server status displays across any channels where the bot has permissions -### Intelligent Updates -- **State Change Detection**: Embeds update immediately when server power state changes -- **Resource Thresholds**: CPU usage changes >50% trigger updates -- **Optimized API Calls**: Minimizes requests to the Discord API +### 📊 Server Monitoring +- **Live Status Tracking**: Auto-updating embeds display current server state (online/offline/starting) +- **Resource Usage Metrics**: Detailed monitoring of: + - CPU usage with dynamic scaling for multi-core servers + - Memory consumption in real-time + - Disk space utilization + - Network activity (incoming/outgoing traffic) + - Server uptime counter with human-readable formatting +- **Visual Metrics Graphs**: + - Combined CPU and memory usage graphs over the last minute + - 6 data points captured at 10-second intervals + - Discord dark theme-optimized styling + - Automatic graph generation and embedding for running servers + - Dynamic CPU scaling (100% increments) for accurate multi-vCPU visualization + - Trend indicators (increasing/decreasing/stable) for quick status assessment -### Access Control -- **Guild Restriction**: Operates only in specified Discord server -- **Role-based Permissions**: "Game Server User" role required for interactions -- **Admin Commands**: Special commands restricted to server administrators +### 🔄 Intelligent Update System +- **Smart Update Triggers**: Embeds refresh automatically when: + - Server power state changes (offline ↔ starting ↔ running) + - CPU usage shifts by more than 50% + - Server is detected for the first time + - Running servers reach 10-minute intervals (for uptime accuracy) +- **Rate Limit Protection**: Built-in delays prevent Discord API throttling +- **Optimized API Calls**: Minimizes unnecessary requests through change detection +- **Background Task Management**: Asynchronous update loop runs every 10 seconds -### Reliability Features -- **Persistent Storage**: Remembers embed locations between bot restarts -- **Error Handling**: Comprehensive error recovery and logging -- **Rate Limit Protection**: Built-in delays between API calls +### 🔒 Security & Access Control +- **Single-Guild Restriction**: Bot operates exclusively in your designated Discord server +- **Role-based Permissions**: "Game Server User" role required for all server interactions +- **Administrator Commands**: Special management commands restricted to server administrators +- **Interaction Validation**: Every button press and command verified for proper authorization + +### 💾 Data Persistence +- **Embed Location Storage**: Automatically remembers where embeds are posted (survives bot restarts) +- **JSON-based Storage**: Human-readable embed tracking in `embed_locations.json` +- **Metrics History**: Maintains 1 minute of server metrics data (6 data points per server) +- **Automatic Cleanup**: Removes tracking for deleted embeds and inactive servers + +### đŸ›Ąī¸ Reliability Features +- **Comprehensive Error Handling**: Graceful recovery from API failures and network issues +- **Rotating Log Files**: Automatic log rotation (5MB max, 3 backup files) +- **Debug-level Logging**: Detailed operation logs for troubleshooting +- **Graceful Shutdown**: Proper cleanup on SIGINT/SIGTERM signals (Docker-friendly) +- **Configuration Validation**: Startup verification of all required settings +- **API Key Validation**: Checks for correct Pterodactyl API key formats + +### 🎨 User Interface +- **Color-coded Status**: Visual indicators for server states + - đŸ”ĩ Blue for online servers + - 🔴 Red for offline servers +- **Ephemeral Interactions**: Private responses visible only to command users +- **Real-time Feedback**: Instant confirmation messages for all actions +- **Persistent Controls**: Server control buttons remain functional indefinitely +- **Responsive Design**: Clean, Discord-optimized embed layouts + +### 🔧 Administrator Tools +- **Bulk Embed Refresh**: Force-refresh all server status embeds with one command +- **Complete Purge System**: Remove all bot embeds from the server with detailed statistics +- **Progress Tracking**: Real-time progress updates during multi-embed operations +- **Comprehensive Logging**: All administrative actions logged with user attribution ## Installation +### Discord Bot Setup + +Before installing the bot software, you need to create a Discord application and bot account. + +#### 1. Create Discord Application + +1. Navigate to the [Discord Developer Portal](https://discord.com/developers/applications) +2. Click the **"New Application"** button in the top-right corner +3. Enter a name for your application (e.g., "Pterodactyl Bot") +4. Accept the Terms of Service and click **"Create"** + +#### 2. Configure Bot Settings + +1. In the left sidebar, click on **"Bot"** +2. Click **"Add Bot"** and confirm by clicking **"Yes, do it!"** +3. Under the bot's username, you'll see a **Token** section: + - Click **"Reset Token"** and then **"Copy"** to get your bot token + - âš ī¸ **Keep this token secret!** Never share it publicly or commit it to version control +4. Scroll down to **"Privileged Gateway Intents"** and enable: + - ✅ **Message Content Intent** (required for the bot to read message content) +5. Click **"Save Changes"** at the bottom + +#### 3. Set Bot Permissions + +1. In the left sidebar, click on **"OAuth2"** → **"URL Generator"** +2. Under **"Scopes"**, select: + - ✅ `bot` + - ✅ `applications.commands` +3. Under **"Bot Permissions"**, select: + - ✅ **View Channels** (allows bot to see channels) + - ✅ **Send Messages** (allows bot to post embeds) + - ✅ **Embed Links** (required for rich embeds) + - ✅ **Attach Files** (required for metrics graphs) + - ✅ **Read Message History** (allows bot to edit existing messages) + - ✅ **Use Slash Commands** (required for `/server_status` commands) + +#### 4. Invite Bot to Your Server + +1. Copy the **Generated URL** at the bottom of the OAuth2 URL Generator page +2. Paste this URL into your browser and press Enter +3. Select the Discord server where you want to add the bot +4. Click **"Authorize"** and complete the CAPTCHA if prompted +5. The bot should now appear in your server (offline until you start the application) + +#### 5. Get Your Guild ID + +1. In Discord, enable **Developer Mode**: + - Click the âš™ī¸ gear icon (User Settings) + - Navigate to **"Advanced"** under "App Settings" + - Toggle on **"Developer Mode"** +2. Right-click on your server icon in the left sidebar +3. Click **"Copy Server ID"** at the bottom of the menu +4. Save this ID - you'll need it for the bot configuration + +#### 6. Create Server Role + +1. In your Discord server, click the server name at the top to open the dropdown menu +2. Select **"Server Settings"** → **"Roles"** +3. Click **"Create Role"** +4. Name the role exactly: `Game Server User` +5. The role doesn't need any special permissions - it's only used for bot access control +6. Click **"Save Changes"** +7. Assign this role to any users who should be able to control game servers + ### Prerequisites + - Python 3.8 or higher **or** Docker -- Discord bot token with proper permissions +- Discord bot token (from setup above) +- Discord server (guild) ID (from setup above) - Pterodactyl panel with API access -- Server with both Client and Application API keys +- Pterodactyl Client API key (starts with `ptlc_`) +- Pterodactyl Application API key (starts with `ptla_`) ### Traditional Installation @@ -106,13 +223,13 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers pterodisbot: build: . environment: - # Remmove brackets and spaces in environment variables + # Remove brackets and spaces in environment variables # Ideally, use .env file to assign values to these instead - - DISCORD_TOKEN={Your Discord bot token} - - ALLOWED_GUILD_ID={The Discord server ID where the bot should operate} - - PANEL_URL={Your Pterodactyl panel URL (must include http:// or https://)} - - CLIENT_API_KEY={Pterodactyl client API key (starts with `ptlc_`)} - - APPLICATION_API_KEY={Pterodactyl application API key (starts with `ptla_`)} + - DISCORD_TOKEN={Your Discord bot token from Developer Portal} + - ALLOWED_GUILD_ID={Your Discord server ID from step 5 above} + - PANEL_URL={Your Pterodactyl panel URL with https://} + - CLIENT_API_KEY={Pterodactyl client API key starting with ptlc_} + - APPLICATION_API_KEY={Pterodactyl application API key starting with ptla_} volumes: - bot_logs:/app/logs - bot_embed:/app/embed @@ -133,7 +250,7 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers When using Docker or generating the config automatically, these environment variables are required: -- `DISCORD_TOKEN`: Your Discord bot token +- `DISCORD_TOKEN`: Your Discord bot token (from Discord Developer Portal) - `ALLOWED_GUILD_ID`: The Discord server ID where the bot should operate - `PANEL_URL`: Your Pterodactyl panel URL (must include http:// or https://) - `CLIENT_API_KEY`: Pterodactyl client API key (starts with `ptlc_`) @@ -163,97 +280,252 @@ python generate_config.py ### First Run Setup -1. Invite your bot to your Discord server with these permissions: - - View Channels - - Send Messages - - Embed Links - - Manage Messages (for embed updates) - - Use Slash Commands +1. Ensure your bot is invited to your Discord server with proper permissions (see [Discord Bot Setup](#discord-bot-setup)) -2. Create a "Game Server User" role for users who should control servers +2. Verify the "Game Server User" role exists in your server -3. Use the `/server_status` command to create your first status embed +3. Start the bot using your preferred installation method + +4. The bot should appear online in your server + +5. Use the `/server_status` command to create your first status embed ### Bot Commands #### `/server_status` -Display an interactive context menu containing all available servers which can be selected to create an embed for a given server. +Display an interactive dropdown menu containing all available servers from your Pterodactyl panel. Select a server to create a permanent status embed in the current channel with real-time monitoring and control buttons. + +**Features:** +- Shows total server count and online/offline statistics +- Lists all servers with descriptions +- Creates persistent, auto-updating embeds +- Automatically removes old embeds when recreating for the same server #### `/refresh_embeds` (Admin only) -Force a refresh of all server status embeds. This is useful if embeds become out of sync. +Force a complete refresh of all server status embeds. This command: +- Recreates all tracked embeds with fresh data +- Deletes old embed messages to prevent duplication +- Updates embed tracking storage +- Provides statistics on deleted and created embeds + +**Use cases:** +- Embeds appear out of sync with actual server states +- After bot configuration changes +- Following Discord API issues #### `/purge_embeds` (Admin only) -Delete all embeds from the Discord guild. +Permanently delete all server status embeds from the Discord server. This command: +- Removes all tracked embed messages +- Clears the embed tracking file +- Provides real-time progress updates +- Shows detailed statistics (deleted, missing, errors) + +**Use cases:** +- Starting fresh with new embed layout +- Removing bot from server +- Cleaning up after testing ### Embed System -Status embeds include: -- Server name and current state (color-coded) -- Resource usage (when online): - - CPU percentage - - Memory usage - - Disk usage - - Network activity -- Interactive buttons: - - Start (green) - - Stop (red) - - Restart (blue) - - Show Address (grey) +Status embeds dynamically display: -Embed locations are stored in `embed_locations.json` and persist between bot restarts. +**Header Information:** +- Server name with current state (color-coded) +- Server description +- Last updated timestamp + +**Status Fields:** +- 🆔 Server ID (Pterodactyl identifier) +- â„šī¸ Status (Active or Suspended) +- âąī¸ Uptime (for running servers) + +**Resource Usage (when online):** +- CPU percentage with dynamic scaling +- Memory usage (current vs. allocated) +- Disk usage (current vs. allocated) +- Network traffic (incoming/outgoing) + +**Metrics Visualization (when running):** +- Combined CPU and memory graph +- Last 1 minute of data (6 data points) +- Trend indicators +- Data point counter + +**Interactive Buttons:** +- đŸŸĸ **Start** - Powers on the server +- 🔴 **Stop** - Gracefully shuts down the server +- đŸ”ĩ **Restart** - Reboots the server +- âšĒ **Show Address** - Displays connection information (IP:Port) + +**Automatic Updates:** +Embeds refresh when server state changes, including: +- Power state transitions +- Significant resource usage changes +- Periodic updates for uptime accuracy + +Embed locations are stored in `embed/embed_locations.json` and persist between bot restarts. ## Permissions The bot implements two levels of access control: -1. **Guild Restriction**: Only works in the Discord server specified in `AllowedGuildID` -2. **Role Requirement**: Users must have the "Game Server User" role to interact with server controls +### 1. Guild Restriction +The bot only responds to commands and interactions from the Discord server specified in `AllowedGuildID`. This prevents unauthorized use if the bot is accidentally added to other servers. -Administrators can use the `/refresh_embeds` and `/purge_embeds` command. +### 2. Role-Based Access +Users must have the **"Game Server User"** role (exact name match) to: +- Use server control buttons (Start/Stop/Restart) +- View server addresses +- Interact with any bot features + +### 3. Administrator Access +Server administrators (users with Discord's Administrator permission) can additionally: +- Use `/refresh_embeds` command +- Use `/purge_embeds` command +- No special role required - based on Discord permissions + +**Note:** The `/server_status` command can be used by anyone, but only users with the "Game Server User" role can interact with the resulting embeds. ## Logging System The bot maintains comprehensive logs in two locations: -1. **File Logs**: Rotating log files (5MB max, 3 backups) in `pterodactyl_bot.log` -2. **Console Output**: Real-time logging to stdout +### 1. File Logs +- **Location**: `logs/pterodisbot.log` +- **Rotation**: Automatic rotation when file reaches 5MB +- **Backups**: Keeps 3 previous log files (`pterodisbot.log.1`, `.2`, `.3`) +- **Format**: `YYYY-MM-DD HH:MM:SS - LEVEL - MESSAGE` -Log levels: -- **DEBUG**: Detailed operational information (API calls, state changes) -- **INFO**: General operational messages (bot startup, command usage) -- **WARNING**: Potential issues (missing embeds, API warnings) -- **ERROR**: Operational failures (API errors, permission issues) -- **CRITICAL**: Critical failures (configuration errors, startup failures) +### 2. Console Output +- **Real-time**: Logs appear in stdout/stderr +- **Format**: Same as file logs +- **Level**: INFO and above (less verbose than file logs) + +### Log Levels + +- **DEBUG**: Detailed operational information (API calls, state changes, cache operations) +- **INFO**: General operational messages (bot startup, command usage, successful operations) +- **WARNING**: Potential issues (missing embeds, API warnings, permission issues) +- **ERROR**: Operational failures (API errors, Discord API issues, failed operations) +- **CRITICAL**: Critical failures (configuration errors, startup failures, unrecoverable errors) + +### Example Log Entries + +``` +2025-09-29 03:51:13,743 - INFO - Initialized logging system with file and console output +2025-09-29 03:51:16,828 - INFO - Starting full refresh of all server embeds +2025-09-29 03:51:16,829 - INFO - Bot connected as Petrodisbot (ID: 1419694924458360964) +2025-09-29 03:52:10,481 - INFO - Start button pressed for Minecraft Server by username +2025-09-29 03:52:14,406 - DEBUG - Power state changed for Minecraft Server: offline -> starting +``` ## Troubleshooting ### Common Issues -**Embeds not updating:** -- Verify the bot has proper channel permissions -- Check API keys have correct permissions -- Use `/refresh_embeds` to reset all embeds +#### Embeds not updating +**Symptoms**: Embeds show outdated information or don't change when server state changes -**Buttons not working:** -- Confirm users have the "Game Server User" role -- Ensure the bot has these permissions: +**Solutions:** +- Verify the bot has proper channel permissions (View Channel, Send Messages, Embed Links) +- Check that both API keys are valid and have correct permissions +- Review logs for API errors or rate limiting +- Use `/refresh_embeds` to force-recreate all embeds +- Ensure the bot hasn't been rate-limited by Discord (check logs for HTTP 429 errors) + +#### Buttons not working +**Symptoms**: Clicking Start/Stop/Restart buttons shows permission errors + +**Solutions:** +- Confirm users have the "Game Server User" role (exact name match) +- Verify the role is properly assigned to users +- Check bot permissions: - View Channel - Send Messages - Embed Links - Use Slash Commands +- Ensure the interaction is happening in the correct Discord server (guild) -**API errors:** -- Double-check your Pterodactyl panel URL +#### Commands not appearing +**Symptoms**: Slash commands don't show up when typing `/` + +**Solutions:** +- Wait 5-10 minutes after bot startup (command sync takes time) +- Verify bot has "Use Slash Commands" permission +- Check that the bot is in the correct guild (server) +- Review logs for command sync errors +- Try kicking and re-inviting the bot with proper OAuth2 URL + +#### API errors +**Symptoms**: Bot logs show Pterodactyl API failures + +**Solutions:** +- Double-check your Pterodactyl panel URL (must include `https://`) - Verify API keys are correct and not expired -- Confirm the server exists in Pterodactyl +- Confirm the server exists in Pterodactyl panel +- Check API key permissions: + - Client key needs: server resource access, power control + - Application key needs: server list access, server details +- Test API keys directly using Pterodactyl API documentation + +#### Graphs not appearing +**Symptoms**: Embeds show "Usage Trends" section but no graph image + +**Solutions:** +- Wait at least 20 seconds after server starts (needs 2 data points minimum) +- Check that the server is in "running" state +- Verify matplotlib is installed correctly (`pip install matplotlib`) +- Review logs for graph generation errors +- Ensure `/tmp/matplotlib` directory has write permissions (Docker) + +#### Bot crashes on startup +**Symptoms**: Bot exits immediately with configuration errors + +**Solutions:** +- Verify all required fields in `config.ini`: + - No empty values + - Correct format for all URLs (must include protocol) + - API keys have correct prefixes (`ptlc_` and `ptla_`) + - Guild ID is a valid integer +- Check file permissions on `config.ini` +- Review startup logs for specific validation errors +- Test configuration validation: `python -c "from pterodisbot import validate_config; validate_config()"` ### Checking Logs For real-time log monitoring: ```bash -tail -f pterodactyl_bot.log +# Traditional installation +tail -f logs/pterodisbot.log + +# Docker installation +docker logs -f pterodisbot + +# Docker Compose +docker-compose logs -f pterodisbot ``` +For searching logs: +```bash +# Find all ERROR level messages +grep "ERROR" logs/pterodisbot.log + +# Find logs for specific server +grep "Server_Name" logs/pterodisbot.log + +# View last 100 lines +tail -n 100 logs/pterodisbot.log +``` + +### Getting Help + +If issues persist after trying these solutions: + +1. Enable DEBUG logging by reviewing recent log files +2. Check the [Git Issues](https://git.serendipity.systems/k.eaven/pterodactyl-discord-bot/issues) for similar problems +3. Verify your setup matches all requirements in [Prerequisites](#prerequisites) +4. Test each component individually (Discord bot, Pterodactyl API, permissions) + ## License This project is licensed under the GPL-3.0 License - see the [LICENSE](LICENSE) file for details.