diff --git a/discord/classes/Bot.js b/discord/classes/Bot.js new file mode 100644 index 0000000..e961d5e --- /dev/null +++ b/discord/classes/Bot.js @@ -0,0 +1,132 @@ +const { Client, GatewayIntentBits, ChannelType } = require("discord.js"); +const CommandManager = require('./CommandManager'); +const fs = require('fs'); +const path = require('path'); + +class Bot { + constructor() { + // Initialize client with minimal required intents + this.client = new Client({ + intents: [ + GatewayIntentBits.Guilds, + GatewayIntentBits.DirectMessages, + GatewayIntentBits.MessageContent, + GatewayIntentBits.DirectMessageReactions, + GatewayIntentBits.DirectMessageTyping + ], + partials: ['CHANNEL', 'MESSAGE'] + }); + + // Initialize command manager + this.commandManager = new CommandManager(this.client); + + // Authorized user ID - CHANGE THIS to your Discord user ID + this.authorizedUserId = process.env.AUTHORIZED_USER_ID; + + // Setup temp directory + this.setupTempDirectory(); + + // Setup event handlers + this.setupEventHandlers(); + } + + setupTempDirectory() { + const tempDir = path.join(__dirname, '../../temp'); + if (fs.existsSync(tempDir)) { + console.log("Cleaning up temp directory..."); + const files = fs.readdirSync(tempDir); + for (const file of files) { + fs.unlinkSync(path.join(tempDir, file)); + } + } else { + fs.mkdirSync(tempDir, { recursive: true }); + } + } + + setupEventHandlers() { + // Ready event + this.client.once("ready", async () => { + console.log(`Logged in as ${this.client.user.tag}`); + + // Only register global commands for direct messages + await this.commandManager.registerGlobalCommands(); + + // Send startup notification + await this.sendStartupNotification(); + }); + + // Interaction event + this.client.on("interactionCreate", async (interaction) => { + // Only process commands if: + // 1. It's a DM channel + // 2. The user is authorized + if (interaction.channel?.type !== ChannelType.DM) { + await interaction.reply({ + content: "This bot only works in direct messages for security reasons.", + ephemeral: true + }); + return; + } + + if (interaction.user.id !== this.authorizedUserId) { + console.log(`Unauthorized access attempt by ${interaction.user.tag} (${interaction.user.id})`); + await interaction.reply({ + content: "You are not authorized to use this bot.", + ephemeral: true + }); + return; + } + + console.log(`Authorized command: ${interaction.commandName} from ${interaction.user.tag}`); + + // Handle the interaction + await this.commandManager.handleInteraction(interaction); + }); + + // Error handling + process.on('unhandledRejection', error => { + console.error('Unhandled promise rejection:', error); + }); + } + + async sendStartupNotification() { + // Create startup embed + const startupEmbed = { + title: "VPS Control Bot Status", + description: `Bot started successfully at `, + color: 0x00ff00, + fields: [ + { + name: "Bot Name", + value: this.client.user.tag, + inline: true + }, + { + name: "Relative Time", + value: ``, + inline: true + } + ], + footer: { + text: "VPS Control Bot" + } + }; + + // Only notify the authorized user + try { + const owner = await this.client.users.fetch(this.authorizedUserId); + await owner.send({ embeds: [startupEmbed] }); + console.log(`Sent startup notification to authorized user: ${owner.tag}`); + } catch (error) { + console.error("Failed to send startup notification to authorized user:", error); + } + } + + async start() { + // Login to Discord + await this.client.login(process.env.DISCORD_TOKEN); + return this; + } +} + +module.exports = Bot; diff --git a/discord/classes/CommandManager.js b/discord/classes/CommandManager.js new file mode 100644 index 0000000..8d10b5b --- /dev/null +++ b/discord/classes/CommandManager.js @@ -0,0 +1,107 @@ +const { Collection, REST, Routes } = require('discord.js'); +const fs = require('fs'); +const path = require('path'); + +class CommandManager { + constructor(client) { + this.client = client; + this.commands = new Collection(); + this.commandFolders = ['info', 'system']; // Only include info and system commands + this.rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN); + this.authorizedUserId = process.env.AUTHORIZED_USER_ID; + } + + async loadCommands() { + const commandsPath = path.join(__dirname, '../commands'); + + // Only load commands from allowed folders + for (const folder of this.commandFolders) { + const folderPath = path.join(commandsPath, folder); + + // Skip if folder doesn't exist + if (!fs.existsSync(folderPath)) continue; + + const commandFiles = fs.readdirSync(folderPath).filter(file => file.endsWith('.js')); + + for (const file of commandFiles) { + const filePath = path.join(folderPath, file); + const CommandClass = require(filePath); + const command = new CommandClass(this.client); + + // Add authorization check to command + const originalExecute = command.execute; + command.execute = async function(interaction) { + if (interaction.user.id !== process.env.AUTHORIZED_USER_ID) { + return interaction.reply({ + content: "You are not authorized to use this command.", + ephemeral: true + }); + } + return originalExecute.call(this, interaction); + }; + + this.commands.set(command.name, command); + console.log(`Loaded command: ${command.name}`); + } + } + } + + async registerGlobalCommands() { + try { + await this.loadCommands(); + + if (this.commands.size === 0) { + console.log("No commands to register."); + return; + } + + const commandsData = this.commands.map(command => command.toJSON()); + + console.log(`Started refreshing ${commandsData.length} application (/) commands.`); + + // Register as global commands for DMs + const data = await this.rest.put( + Routes.applicationCommands(this.client.user.id), + { body: commandsData }, + ); + + console.log(`Successfully reloaded ${data.length} application (/) commands.`); + } catch (error) { + console.error(error); + } + } + + async handleInteraction(interaction) { + if (!interaction.isChatInputCommand()) return; + + // Double-check authorization + if (interaction.user.id !== this.authorizedUserId) { + return interaction.reply({ + content: "You are not authorized to use this command.", + ephemeral: true + }); + } + + const command = this.commands.get(interaction.commandName); + if (!command) return; + + try { + await command.execute(interaction); + } catch (error) { + console.error(`Error executing command ${interaction.commandName}:`, error); + + const errorMessage = { + content: "There was an error while executing this command!", + ephemeral: true + }; + + if (interaction.replied || interaction.deferred) { + await interaction.followUp(errorMessage); + } else { + await interaction.reply(errorMessage); + } + } + } +} + +module.exports = CommandManager; diff --git a/discord/classes/SystemCommandBase.js b/discord/classes/SystemCommandBase.js new file mode 100644 index 0000000..8cd5690 --- /dev/null +++ b/discord/classes/SystemCommandBase.js @@ -0,0 +1,48 @@ +const CommandBase = require('./CommandBase'); +const { exec } = require('child_process'); +const util = require('util'); + +const execPromise = util.promisify(exec); + +class SystemCommandBase extends CommandBase { + constructor(client) { + super(client); + + // Add security check for all system commands + const originalExecute = this.execute; + this.execute = async function(interaction) { + if (interaction.user.id !== process.env.AUTHORIZED_USER_ID) { + return interaction.reply({ + content: "You are not authorized to use system commands.", + ephemeral: true + }); + } + + // Additional DM-only check + if (interaction.channel.type !== 'DM') { + return interaction.reply({ + content: "System commands can only be used in Direct Messages for security.", + ephemeral: true + }); + } + + return originalExecute.call(this, interaction); + }; + } + + async execCommand(command, options = {}) { + try { + const { stdout, stderr } = await execPromise(command, options); + return { success: true, stdout, stderr }; + } catch (error) { + return { + success: false, + error: error.message, + stdout: error.stdout, + stderr: error.stderr + }; + } + } +} + +module.exports = SystemCommandBase; diff --git a/discord/commands/info/sysinfo.js b/discord/commands/info/sysinfo.js new file mode 100644 index 0000000..a73627c --- /dev/null +++ b/discord/commands/info/sysinfo.js @@ -0,0 +1,91 @@ +const SystemCommandBase = require('../../classes/SystemCommandBase'); +const os = require('os'); + +class SystemInfo extends SystemCommandBase { + constructor(client) { + super(client); + this.name = 'sysinfo'; + this.description = 'Get system information from the VPS'; + } + + async execute(interaction) { + try { + await interaction.deferReply(); + + // Get basic system info using Node.js + const uptime = Math.floor(os.uptime()); + const days = Math.floor(uptime / 86400); + const hours = Math.floor((uptime % 86400) / 3600); + const minutes = Math.floor((uptime % 3600) / 60); + const seconds = uptime % 60; + const uptimeString = `${days}d ${hours}h ${minutes}m ${seconds}s`; + + const memTotal = Math.round(os.totalmem() / (1024 * 1024 * 1024) * 100) / 100; + const memFree = Math.round(os.freemem() / (1024 * 1024 * 1024) * 100) / 100; + const memUsed = Math.round((memTotal - memFree) * 100) / 100; + const memPercent = Math.round((memUsed / memTotal) * 100); + + // Get more detailed info using system commands + const { stdout: diskInfo } = await this.execCommand('df -h / | tail -n 1'); + const diskParts = diskInfo.trim().split(/\s+/); + const diskTotal = diskParts[1] || 'N/A'; + const diskUsed = diskParts[2] || 'N/A'; + const diskFree = diskParts[3] || 'N/A'; + const diskPercent = diskParts[4] || 'N/A'; + + const { stdout: loadAvg } = await this.execCommand('cat /proc/loadavg'); + const loadParts = loadAvg.trim().split(' '); + const load1m = loadParts[0] || 'N/A'; + const load5m = loadParts[1] || 'N/A'; + const load15m = loadParts[2] || 'N/A'; + + const infoEmbed = { + title: "VPS System Information", + color: 0x3498db, + fields: [ + { + name: "Hostname", + value: os.hostname(), + inline: true + }, + { + name: "Platform", + value: `${os.type()} ${os.release()}`, + inline: true + }, + { + name: "Uptime", + value: uptimeString, + inline: true + }, + { + name: "Memory", + value: `${memUsed}GB / ${memTotal}GB (${memPercent}%)`, + inline: true + }, + { + name: "Disk", + value: `${diskUsed} / ${diskTotal} (${diskPercent})`, + inline: true + }, + { + name: "Load Average", + value: `${load1m} | ${load5m} | ${load15m}`, + inline: true + } + ], + timestamp: new Date(), + footer: { + text: "VPS Control Bot" + } + }; + + await interaction.editReply({ embeds: [infoEmbed] }); + } catch (error) { + console.error(error); + await interaction.editReply("Failed to get system information."); + } + } +} + +module.exports = SystemInfo; diff --git a/index.js b/index.js new file mode 100644 index 0000000..6ab2d20 --- /dev/null +++ b/index.js @@ -0,0 +1,68 @@ +// Main application entry point +const path = require('path'); +require('dotenv').config(); + +// Import the Bot class +const Bot = require('./discord/Bot'); + +// Global variables to hold our services +let apiServer; +let discordBot; + +async function startServices() { + try { + // Start API server + console.log('Starting API server...'); + apiServer = require('./api/server'); + console.log('API server started successfully'); + + // Initialize and start Discord bot + console.log('Starting Discord bot...'); + discordBot = new Bot(); + await discordBot.start(); + console.log('Discord bot started successfully'); + + console.log('All services started - System fully operational'); + } catch (error) { + console.error('Error starting services:', error); + process.exit(1); + } +} + +// Handle graceful shutdown +async function shutdown(signal) { + console.log(`Received ${signal}. Shutting down gracefully...`); + + // Shutdown Discord bot if it exists and has a shutdown method + if (discordBot && typeof discordBot.sendShutdownNotification === 'function') { + try { + await discordBot.sendShutdownNotification(`Manual shutdown triggered by ${signal}`); + console.log('Discord bot shutdown complete'); + } catch (error) { + console.error('Error shutting down Discord bot:', error); + } + } + + // Add any API server shutdown logic here if needed + + console.log('Shutdown complete'); + process.exit(0); +} + +// Register shutdown handlers +process.on('SIGINT', () => shutdown('SIGINT')); +process.on('SIGTERM', () => shutdown('SIGTERM')); + +// Catch uncaught exceptions +process.on('uncaughtException', (error) => { + console.error('Uncaught exception:', error); + if (discordBot && typeof discordBot.sendShutdownNotification === 'function') { + discordBot.sendShutdownNotification('Uncaught exception', error) + .finally(() => process.exit(1)); + } else { + process.exit(1); + } +}); + +// Start all services +startServices();