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;
});