galaxy.linux

NexaBot – Advanced Discord Pterodactyl Server Manager

  1. Project Information
  • Bot Name: NexaBot
  • Type: Discord Server Management Bot
  • Language: Node.js (JavaScript)
  • Discord Library: discord.js v14+
  • API: Pterodactyl Client API
  • Database: SQLite
  • Architecture: Modular, secure and scalable
  1. Main Objective

Create a professional Discord bot named NexaBot that connects to a Pterodactyl Panel through an authorized Client API key.

The bot allows authorized Discord administrators to manage their Minecraft servers directly through Discord slash commands.

  1. Discord Slash Commands

Console Management

"/console command:<command>"

Execute Minecraft server console commands through Pterodactyl.

Examples:

  • "/console command:say Hello everyone"
  • "/console command:time set day"
  • "/console command:weather clear"
  • "/console command:list"

Requirements:

  • Only authorized Discord users can use this command.
  • Send commands through the Pterodactyl Client API.
  • Display confirmation when the command is submitted.
  • Handle API errors.
  • Never expose API credentials.

Server Management

"/server status"

  • Display server status.

"/server start"

  • Start the Minecraft server.

"/server stop"

  • Stop the Minecraft server.

"/server restart"

  • Restart the Minecraft server.

"/server info"

  • Display server information.

Additional Commands

"/nexabot help"

  • Show all commands.

"/nexabot ping"

  • Display bot latency.

"/nexabot panel"

  • Show configured panel information without revealing credentials.

"/nexabot uptime"

  • Show server uptime when available.
  1. Discord Embed Design

Create beautiful, premium Discord embeds.

Use:

  • Modern dark-themed embeds.
  • NexaBot branding.
  • Green success indicators.
  • Red error indicators.
  • Blue information indicators.
  • Server status indicators.
  • Timestamps.
  • Clean formatting.

Example status embed:

NexaBot | Server Status

🟢 Status: Online

🖥️ Server: GalaxySMP

🌐 Panel: panel.example.com

⚡ Management: Pterodactyl API

  1. Pterodactyl Configuration

Create ".env":

DISCORD_TOKEN=YOUR_DISCORD_BOT_TOKEN DISCORD_CLIENT_ID=YOUR_DISCORD_CLIENT_ID DISCORD_GUILD_ID=YOUR_DISCORD_SERVER_ID

PTERODACTYL_URL=https://panel.example.com PTERODACTYL_API_KEY=YOUR_CLIENT_API_KEY PTERODACTYL_SERVER_ID=YOUR_SERVER_IDENTIFIER

Security:

  • Never upload ".env" to GitHub.
  • Include ".env" in ".gitignore".
  • Never display API keys in Discord.
  • Use HTTPS.
  • Never expose credentials through bot commands.
  1. Permission System

Create a configurable Discord user allowlist.

Example:

{ "adminUsers": [ "DISCORD_USER_ID" ], "consoleUsers": [ "DISCORD_USER_ID" ], "powerUsers": [ "DISCORD_USER_ID" ] }

Only authorized Discord users can execute commands.

Also support Discord role-based permissions.

  1. Security System
  • Validate Discord user permissions.
  • Restrict console command execution.
  • Prevent unauthorized power actions.
  • Add command cooldowns.
  • Prevent API spam.
  • Log all remote console commands.
  • Keep API keys private.
  • Never execute operating-system shell commands.
  • Restrict bot management commands to configured administrators.
  1. Advanced Features
  • Multiple Pterodactyl server support.
  • Server status monitoring.
  • Automatic status updates.
  • Console command execution.
  • Start/stop/restart controls.
  • API connection testing.
  • Discord audit logs.
  • Configurable notification channel.
  • Error handling and automatic retry for temporary network failures.
  • SQLite database.
  • Slash command registration.
  • Graceful bot shutdown.
  1. Project Structure

NexaBot/ ├── src/ │ ├── index.js │ ├── config/ │ │ └── config.js │ ├── commands/ │ │ ├── console.js │ │ ├── server.js │ │ └── nexabot.js │ ├── services/ │ │ └── pterodactyl.js │ ├── events/ │ ├── database/ │ ├── utils/ │ └── handlers/ ├── .env ├── .gitignore ├── package.json └── README.md

  1. Final Requirements
  • Use real Pterodactyl API communication.
  • Use Discord slash commands.
  • Use asynchronous API requests.
  • Do not block the Node.js event loop.
  • Support multiple servers.
  • Write clean, maintainable code.
  • Test all commands.
  • Provide complete source code.
  • Provide installation and setup instructions.
  • Do not leave unfinished TODO implementations.

Final Goal: NexaBot should be a professional Discord-based Pterodactyl server management bot capable of controlling Minecraft servers through Discord.

Kodari AI
KodariNov 11 at 5:44 pm 3
NexaBot
NexaBot is a professional Discord bot for managing Pterodactyl game servers through slash commands. It enables authorized users to execute console commands, control server power (start/stop/restart), and view server status and information via premium embeds. Features include role-based permissions, command cooldowns, SQLite logging, multi-server support, automatic retry for network failures, and secure API key handling. Built with discord.js v14 and Node.js, it provides elegant dark-themed embeds with status indicators and comprehensive audit logging for complete server management directly from Discord.
  • Create the NexaBot project, environment template, multi-server configuration, and setup guide.

  • Implement the Pterodactyl API client, asynchronous SQLite audit storage, and status-change monitoring.

  • Add secured slash commands, role/user permissions, cooldowns, and graceful startup/shutdown.

Built NexaBot with /console, /server management commands, and /nexabot help, ping, panel, API-test, and uptime commands. It includes multi-server configuration, user/role permissions, per-user cooldowns, Pterodactyl API error handling, SQLite audit logs, optional status-change notifications, and graceful shutdown.

To run it, add your credentials to .env, configure servers and permissions in config.json, then run npm install and npm start. Live command testing requires valid Discord and Pterodactyl credentials.

Kodari can make mistakes. Review important code before using.
Files
src
.gitignore
config.json
package.json
README.md
Code
16 902
src/index.js
const path = require('node:path');
const { Client, Events, GatewayIntentBits } = require('discord.js');
const { loadConfig } = require('./config/config');
const { Database } = require('./database/database');
const consoleCommand = require('./commands/console');
const serverCommand = require('./commands/server');
const nexabotCommand = require('./commands/nexabot');
const { PterodactylClient } = require('./services/pterodactyl');
const { startStatusMonitor } = require('./services/status-monitor');
const { COLORS, createEmbed } = require('./utils/embeds');
const { serverAutocompleteChoices } = require('./utils/servers');

async function main() {
  const config = await loadConfig();
  const database = new Database(path.join(process.cwd(), 'data', 'nexabot.sqlite'));
  await database.initialize();

  const client = new Client({ intents: [GatewayIntentBits.Guilds] });
  const pterodactyl = new PterodactylClient(config.panelUrl, config.apiKey);
  const commands = [consoleCommand, serverCommand, nexabotCommand];
  const commandMap = new Map(commands.map((command) => [command.data.name, command]));
  const cooldowns = new Map();
  let stopMonitor = () => {};
  let shuttingDown = false;

  client.once(Events.ClientReady, async (readyClient) => {
    try {
      if (readyClient.application.id !== config.discordClientId) {
        throw new Error('DISCORD_CLIENT_ID does not match the application for DISCORD_TOKEN.');
      }
      const definitions = commands.map((command) => command.data.toJSON());
      if (config.discordGuildId) {
        await readyClient.application.commands.set(definitions, config.discordGuildId);
      } else {
        await readyClient.application.commands.set(definitions);
      }
      console.log(`Registered ${definitions.length} slash commands.`);
    } catch (error) {
      console.error('Slash command registration failed:', error.message);
    }

    console.log(`Bot is ready! Logged in as ${readyClient.user.tag}`);
    console.log('KODARI_READY');
    stopMonitor = startStatusMonitor({ client, config, database, pterodactyl });
  });

  client.on(Events.InteractionCreate, async (interaction) => {
    try {
      if (interaction.isAutocomplete()) {
        const focused = interaction.options.getFocused();
        await interaction.respond(serverAutocompleteChoices(config, focused));
        return;
      }
      if (!interaction.isChatInputCommand()) return;

      const command = commandMap.get(interaction.commandName);
      if (!command) return;

      const usesRemoteApi = interaction.commandName === 'console'
        || interaction.commandName === 'server'
        || (interaction.commandName === 'nexabot' && ['test', 'uptime'].includes(interaction.options.getSubcommand()));
      if (usesRemoteApi) {
        const key = interaction.user.id;
        const now = Date.now();
        const availableAt = cooldowns.get(key) || 0;
        if (availableAt > now) {
          const seconds = Math.ceil((availableAt - now) / 1000);
          await interaction.reply({
            embeds: [createEmbed('Cooldown', `Please wait **${seconds}s** before another server request.`, COLORS.warning)],
            ephemeral: true
          });
          return;
        }
        cooldowns.set(key, now + 3000);
      }

      await command.execute(interaction, { client, config, database, pterodactyl });
    } catch (error) {
      console.error('Interaction failed:', error);
      const response = {
        embeds: [createEmbed('Request Failed', 'The command could not be completed. Please try again.', COLORS.error)]
      };
      if (interaction.deferred || interaction.replied) await interaction.followUp({ ...response, ephemeral: true }).catch(() => {});
      else if (interaction.isRepliable()) await interaction.reply({ ...response, ephemeral: true }).catch(() => {});
    }
  });

  client.on(Events.Error, (error) => console.error('Discord client error:', error));
  process.on('unhandledRejection', (error) => console.error('Unhandled promise rejection:', error));

  async function shutdown(signal) {
    if (shuttingDown) return;
    shuttingDown = true;
    console.log(`Received ${signal}; shutting down.`);
    stopMonitor();
    client.destroy();
    try {
      await database.close();
    } catch (error) {
      console.error('Could not close the database cleanly:', error.message);
    }
    process.exit(0);
  }

  process.once('SIGINT', () => void shutdown('SIGINT'));
  process.once('SIGTERM', () => void shutdown('SIGTERM'));

  try {
    await client.login(config.discordToken);
  } catch (error) {
    console.error('Discord login failed:', error.message);
    await database.close();
    process.exitCode = 1;
  }
}

main().catch((error) => {
  console.error('NexaBot startup failed:', error.message);
  process.exitCode = 1;
});