1 Commits

Author SHA1 Message Date
a2cb18634f Merge pull request 'Add CI/CD testing automation & Improve code formatting' (#10) from development into main
All checks were successful
CI/CD Pipeline / Unit Tests (Python 3.10) (push) Successful in 21s
CI/CD Pipeline / Unit Tests (Python 3.11) (push) Successful in 21s
CI/CD Pipeline / Unit Tests (Python 3.9) (push) Successful in 22s
CI/CD Pipeline / Security Scanning (push) Successful in 19s
CI/CD Pipeline / Integration Tests (push) Successful in 16s
CI/CD Pipeline / Code Quality & Linting (push) Successful in 44s
CI/CD Pipeline / Generate Test Report (push) Successful in 5s
CI/CD Pipeline / Build Docker Image (push) Successful in 24s
CI/CD Pipeline / CI/CD Pipeline Status (push) Successful in 2s
Reviewed-on: #10
2025-10-28 15:24:49 +00:00

457
README.md
View File

@@ -6,8 +6,8 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers
## Table of Contents
- [Features](#features)
- [Architecture Overview](#architecture-overview)
- [Installation](#installation)
- [Discord Bot Setup](#discord-bot-setup)
- [Traditional Installation](#traditional-installation)
- [Docker Installation](#docker-installation)
- [Configuration](#configuration)
@@ -20,154 +20,52 @@ A feature-rich Discord bot for monitoring and managing Pterodactyl game servers
- [Permissions](#permissions)
- [Logging System](#logging-system)
- [Troubleshooting](#troubleshooting)
- [Development](#development)
- [Contributing](#contributing)
- [License](#license)
## Features
### 🎮 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
### 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 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
### 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
### 🔄 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
### 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
### 🔒 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
### 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
### 💾 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
## Architecture Overview
### 🛡️ 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
The bot is built with several key components:
### 🎨 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
1. **PterodactylAPI Class**: Handles all communication with the Pterodactyl Panel API
2. **ServerStatusView Class**: Manages the interactive Discord UI with control buttons
3. **PterodactylBot Class**: Main bot class that orchestrates all operations
4. **Background Task**: Regularly checks server status and updates embeds when needed
5. **Configuration System**: Validates and manages all settings from config.ini
### 🔧 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
The system uses aiohttp for asynchronous HTTP requests and discord.py for Discord interactions.
## 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 (from setup above)
- Discord server (guild) ID (from setup above)
- Discord bot token with proper permissions
- Pterodactyl panel with API access
- Pterodactyl Client API key (starts with `ptlc_`)
- Pterodactyl Application API key (starts with `ptla_`)
- Server with both Client and Application API keys
### Traditional Installation
@@ -223,13 +121,13 @@ Before installing the bot software, you need to create a Discord application and
pterodisbot:
build: .
environment:
# Remove brackets and spaces in environment variables
# Remmove brackets and spaces in environment variables
# Ideally, use .env file to assign values to these instead
- 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_}
- 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_`)}
volumes:
- bot_logs:/app/logs
- bot_embed:/app/embed
@@ -250,7 +148,7 @@ Before installing the bot software, you need to create a Discord application and
When using Docker or generating the config automatically, these environment variables are required:
- `DISCORD_TOKEN`: Your Discord bot token (from Discord Developer Portal)
- `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_`)
@@ -280,251 +178,142 @@ python generate_config.py
### First Run Setup
1. Ensure your bot is invited to your Discord server with proper permissions (see [Discord Bot Setup](#discord-bot-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
2. Verify the "Game Server User" role exists in your server
2. Create a "Game Server User" role for users who should control servers
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
3. Use the `/server_status` command to create your first status embed
### Bot Commands
#### `/server_status`
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
Display an interactive context menu containing all available servers which can be selected to create an embed for a given server.
#### `/refresh_embeds` (Admin only)
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
Force a refresh of all server status embeds. This is useful if embeds become out of sync.
#### `/purge_embeds` (Admin only)
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
Delete all embeds from the Discord guild.
### Embed System
Status embeds dynamically display:
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)
**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.
Embed locations are stored in `embed_locations.json` and persist between bot restarts.
## Permissions
The bot implements two levels of access control:
### 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.
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
### 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.
Administrators can use the `/refresh_embeds` and `/purge_embeds` command.
## Logging System
The bot maintains comprehensive logs in two locations:
### 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`
1. **File Logs**: Rotating log files (5MB max, 3 backups) in `pterodactyl_bot.log`
2. **Console Output**: Real-time logging to stdout
### 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
```
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)
## Troubleshooting
### Common Issues
#### Embeds not updating
**Symptoms**: Embeds show outdated information or don't change when server state changes
**Embeds not updating:**
- Verify the bot has proper channel permissions
- Check API keys have correct permissions
- Use `/refresh_embeds` to reset all embeds
**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:
**Buttons not working:**
- Confirm users have the "Game Server User" role
- Ensure the bot has these permissions:
- View Channel
- Send Messages
- Embed Links
- Use Slash Commands
- Ensure the interaction is happening in the correct Discord server (guild)
#### 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://`)
**API errors:**
- Double-check your Pterodactyl panel URL
- Verify API keys are correct and not expired
- 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()"`
- Confirm the server exists in Pterodactyl
### Checking Logs
For real-time log monitoring:
```bash
# Traditional installation
tail -f logs/pterodisbot.log
# Docker installation
docker logs -f pterodisbot
# Docker Compose
docker-compose logs -f pterodisbot
tail -f pterodactyl_bot.log
```
For searching logs:
## Development
### Requirements
- Python 3.8+
- Poetry (recommended) or pip
### Setup
1. Clone the repository
2. Install dependencies:
```bash
poetry install
```
or
```bash
pip install -r requirements.txt -r requirements-dev.txt
```
3. Create a `.env` file with your development environment variables
4. Run in development mode:
```bash
python pterodisbot.py
```
### Testing
The project includes unit tests (to be expanded). Run with:
```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
pytest
```
### Getting Help
## Contributing
If issues persist after trying these solutions:
Contributions are welcome! Please follow these guidelines:
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)
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/your-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin feature/your-feature`)
5. Open a pull request
### Coding Standards
- Follow PEP 8 style guidelines
- Include type hints for all function signatures
- Document public methods with docstrings
- Write tests for new functionality
## License