git sucks ass
This commit is contained in:
parent
e0efd97621
commit
5a474c5592
19 changed files with 0 additions and 6271 deletions
|
|
@ -1,219 +0,0 @@
|
|||
const { Client, GatewayIntentBits, ChannelType } = require("discord.js");
|
||||
const CommandManager = require('./CommandManager');
|
||||
const NotificationService = require('./NotificationService');
|
||||
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']
|
||||
});
|
||||
|
||||
// Add reference to this bot instance on the client for access from commands
|
||||
this.client.bot = this;
|
||||
|
||||
// THIS IS IMPORTANT: Make sure CommandManager is initialized AFTER the client
|
||||
this.commandManager = new CommandManager(this.client);
|
||||
|
||||
// Authorized users for commands - Parse comma-separated list from env variable
|
||||
this.authorizedUserIds = process.env.AUTHORIZED_USER_IDS
|
||||
? process.env.AUTHORIZED_USER_IDS.split(',').map(id => id.trim())
|
||||
: [];
|
||||
|
||||
// For backward compatibility, add the old env var if it exists
|
||||
if (process.env.AUTHORIZED_USER_ID && !this.authorizedUserIds.includes(process.env.AUTHORIZED_USER_ID)) {
|
||||
this.authorizedUserIds.push(process.env.AUTHORIZED_USER_ID);
|
||||
}
|
||||
|
||||
// Parse notification recipient IDs (separate from command authorization)
|
||||
this.notificationRecipientIds = process.env.NOTIFICATION_USER_IDS ?
|
||||
process.env.NOTIFICATION_USER_IDS.split(',').map(id => id.trim()) :
|
||||
this.authorizedUserIds; // Default to authorized users if not specified
|
||||
|
||||
console.log(`Authorized users configured: ${this.authorizedUserIds.length}`);
|
||||
console.log(`Notification recipients configured: ${this.notificationRecipientIds.length}`);
|
||||
|
||||
// Setup temp directory
|
||||
this.setupTempDirectory();
|
||||
|
||||
// Setup event handlers
|
||||
this.setupEventHandlers();
|
||||
|
||||
// Initialize notification service
|
||||
this.notificationService = null;
|
||||
}
|
||||
|
||||
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 the user is authorized
|
||||
if (!this.authorizedUserIds.includes(interaction.user.id)) {
|
||||
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: "blahaj.tr bot status update",
|
||||
description: `Bot started successfully at <t:${Math.floor(Date.now() / 1000)}:F>`,
|
||||
color: 0x00ff00,
|
||||
fields: [
|
||||
{
|
||||
name: "Bot Name",
|
||||
value: this.client.user.tag,
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: "Relative Time",
|
||||
value: `<t:${Math.floor(Date.now() / 1000)}:R>`,
|
||||
inline: true
|
||||
}
|
||||
],
|
||||
footer: {
|
||||
text: "blahaj.tr"
|
||||
}
|
||||
};
|
||||
|
||||
// Notify all recipients
|
||||
for (const userId of this.notificationRecipientIds) {
|
||||
try {
|
||||
const user = await this.client.users.fetch(userId);
|
||||
await user.send({ embeds: [startupEmbed] });
|
||||
console.log(`Sent startup notification to recipient: ${user.tag}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to send startup notification to user ${userId}:`, error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async sendShutdownNotification(reason = "Manual shutdown", error = null) {
|
||||
// Create shutdown embed
|
||||
const shutdownEmbed = {
|
||||
title: "blahaj.tr bot status update",
|
||||
description: `Bot is shutting down at <t:${Math.floor(Date.now() / 1000)}:F>`,
|
||||
color: 0xFF0000,
|
||||
fields: [
|
||||
{
|
||||
name: "Bot Name",
|
||||
value: this.client.user.tag,
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: "Shutdown Reason",
|
||||
value: reason || "Unknown",
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: "Relative Time",
|
||||
value: `<t:${Math.floor(Date.now() / 1000)}:R>`,
|
||||
inline: true
|
||||
}
|
||||
],
|
||||
footer: {
|
||||
text: "blahaj.tr"
|
||||
}
|
||||
};
|
||||
|
||||
if (error) {
|
||||
shutdownEmbed.fields.push({
|
||||
name: "Error Details",
|
||||
value: `\`\`\`\n${error.message || String(error).substring(0, 1000)}\n\`\`\``,
|
||||
inline: false
|
||||
});
|
||||
}
|
||||
|
||||
// Stop notification service if running
|
||||
if (this.notificationService?.isRunning) {
|
||||
this.notificationService.stop();
|
||||
}
|
||||
|
||||
// Notify authorized user
|
||||
try {
|
||||
const owner = await this.client.users.fetch(this.authorizedUserId);
|
||||
await owner.send({ embeds: [shutdownEmbed] });
|
||||
console.log(`Sent shutdown notification to authorized user: ${owner.tag}`);
|
||||
} catch (error) {
|
||||
console.error("Failed to send shutdown notification to authorized user:", error.message);
|
||||
}
|
||||
|
||||
// Also notify in status channel if available
|
||||
if (this.notificationService?.statusChannel) {
|
||||
try {
|
||||
await this.notificationService.statusChannel.send({ embeds: [shutdownEmbed] });
|
||||
console.log(`Sent shutdown notification to status channel: ${this.notificationService.statusChannel.name}`);
|
||||
} catch (error) {
|
||||
console.error("Failed to send shutdown notification to status channel:", error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async start() {
|
||||
// Login to Discord
|
||||
await this.client.login(process.env.DISCORD_TOKEN);
|
||||
return this;
|
||||
}
|
||||
|
||||
async stop() {
|
||||
// Stop notification service
|
||||
if (this.notificationService) {
|
||||
this.notificationService.stop();
|
||||
}
|
||||
|
||||
// Destroy the client
|
||||
if (this.client) {
|
||||
this.client.destroy();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = Bot;
|
||||
|
|
@ -1,82 +0,0 @@
|
|||
const { SlashCommandBuilder } = require('discord.js');
|
||||
|
||||
class CommandBase {
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
this.name = '';
|
||||
this.description = '';
|
||||
this.options = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the command
|
||||
* @param {Interaction} interaction - The interaction object
|
||||
*/
|
||||
async execute(interaction) {
|
||||
throw new Error('Method not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* Defer the reply to the interaction
|
||||
* @param {Interaction} interaction - The interaction object
|
||||
* @param {boolean} ephemeral - Whether the reply should be ephemeral
|
||||
*/
|
||||
async deferReply(interaction, ephemeral = false) {
|
||||
if (!interaction.deferred && !interaction.replied) {
|
||||
await interaction.deferReply({ ephemeral });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a response to the interaction
|
||||
* @param {Interaction} interaction - The interaction object
|
||||
* @param {Object} options - The response options
|
||||
* @param {boolean} ephemeral - Whether the response should be ephemeral
|
||||
*/
|
||||
async sendResponse(interaction, options, ephemeral = false) {
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.editReply(options);
|
||||
} else {
|
||||
options.ephemeral = ephemeral;
|
||||
await interaction.reply(options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an error response to the interaction
|
||||
* @param {Interaction} interaction - The interaction object
|
||||
* @param {string} message - The error message
|
||||
*/
|
||||
async sendErrorResponse(interaction, message) {
|
||||
const errorEmbed = {
|
||||
title: "Error",
|
||||
description: message,
|
||||
color: 0xFF0000,
|
||||
timestamp: new Date()
|
||||
};
|
||||
|
||||
if (interaction.deferred || interaction.replied) {
|
||||
await interaction.editReply({ embeds: [errorEmbed] });
|
||||
} else {
|
||||
await interaction.reply({ embeds: [errorEmbed], ephemeral: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the command to JSON for registration
|
||||
*/
|
||||
toJSON() {
|
||||
const builder = new SlashCommandBuilder()
|
||||
.setName(this.name)
|
||||
.setDescription(this.description);
|
||||
|
||||
// Add options if defined in the child class
|
||||
if (typeof this.addOptions === 'function') {
|
||||
this.addOptions(builder);
|
||||
}
|
||||
|
||||
return builder.toJSON();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CommandBase;
|
||||
|
|
@ -1,130 +0,0 @@
|
|||
const { Collection, REST, Routes, SlashCommandBuilder } = 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;
|
||||
|
||||
// Add this line to load commands when the CommandManager is created
|
||||
this.loadCommands();
|
||||
}
|
||||
|
||||
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 {
|
||||
console.log("Registering global commands...");
|
||||
|
||||
const commandsData = this.commands.map(command => {
|
||||
const data = {
|
||||
name: command.name,
|
||||
description: command.description,
|
||||
options: command.options || [],
|
||||
// Add these lines for global availability in all contexts
|
||||
integration_types: [1], // Add integration type for global availability
|
||||
contexts: [0, 1, 2], // Available in all contexts (DM, GROUP_DM, GUILD)
|
||||
};
|
||||
|
||||
// If the command has an addOptions method, call it
|
||||
if (typeof command.addOptions === 'function') {
|
||||
data.options = command.addOptions(new SlashCommandBuilder()).options;
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
|
||||
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN);
|
||||
await rest.put(
|
||||
Routes.applicationCommands(this.client.user.id),
|
||||
{ body: commandsData },
|
||||
);
|
||||
|
||||
console.log(`Successfully registered ${commandsData.length} global commands`);
|
||||
} catch (error) {
|
||||
console.error('Error registering global commands:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async handleInteraction(interaction) {
|
||||
if (!interaction.isChatInputCommand()) return;
|
||||
|
||||
// We don't need to double-check authorization here since Bot.js already checks
|
||||
// This avoids potential inconsistencies in the authorization check
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleAutocomplete(interaction) {
|
||||
const command = this.commands.get(interaction.commandName);
|
||||
|
||||
if (!command || typeof command.handleAutocomplete !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await command.handleAutocomplete(interaction);
|
||||
} catch (error) {
|
||||
console.error(`Error handling autocomplete for ${interaction.commandName}:`, error);
|
||||
// Respond with empty array as fallback
|
||||
await interaction.respond([]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CommandManager;
|
||||
|
|
@ -1,300 +0,0 @@
|
|||
const axios = require('axios');
|
||||
|
||||
class NotificationService {
|
||||
constructor(client, options = {}) {
|
||||
this.client = client;
|
||||
|
||||
// Parse notification recipient IDs (separate from command authorization)
|
||||
this.notificationRecipientIds = process.env.NOTIFICATION_USER_IDS ?
|
||||
process.env.NOTIFICATION_USER_IDS.split(',').map(id => id.trim()) :
|
||||
[];
|
||||
|
||||
// For backward compatibility - if no notification IDs specified, use authorized IDs
|
||||
if (this.notificationRecipientIds.length === 0) {
|
||||
// Use the bot's authorizedUserIds as fallback
|
||||
this.notificationRecipientIds = client.bot.authorizedUserIds ||
|
||||
(process.env.AUTHORIZED_USER_IDS ?
|
||||
process.env.AUTHORIZED_USER_IDS.split(',').map(id => id.trim()) :
|
||||
[]);
|
||||
|
||||
// Add legacy single user ID for backward compatibility
|
||||
if (process.env.AUTHORIZED_USER_ID && !this.notificationRecipientIds.includes(process.env.AUTHORIZED_USER_ID)) {
|
||||
this.notificationRecipientIds.push(process.env.AUTHORIZED_USER_ID);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Notification recipients configured: ${this.notificationRecipientIds.length}`);
|
||||
|
||||
this.statusChannel = null;
|
||||
this.checkInterval = options.checkInterval || 10000; // Changed to 10 seconds default
|
||||
this.statusEndpoint = options.statusEndpoint || 'https://blahaj.tr:2589/status';
|
||||
this.notificationChannelId = process.env.STATUS_NOTIFICATION_CHANNEL;
|
||||
|
||||
// Store the previous status to compare for changes
|
||||
this.previousStatus = {
|
||||
servers: {},
|
||||
pm2Services: {} // Changed from services to pm2Services to match API response
|
||||
};
|
||||
|
||||
// Track if this is the first check (to avoid notifications on startup)
|
||||
this.isFirstCheck = true;
|
||||
|
||||
// Indicate if the service is running
|
||||
this.isRunning = false;
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
// Fetch the channel if a channel ID is provided
|
||||
if (this.notificationChannelId) {
|
||||
try {
|
||||
this.statusChannel = await this.client.channels.fetch(this.notificationChannelId);
|
||||
console.log(`Status notification channel set to: ${this.statusChannel.name}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to fetch status notification channel: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Do an initial check to populate the previous status
|
||||
try {
|
||||
const initialStatus = await this.fetchStatus();
|
||||
this.previousStatus = initialStatus;
|
||||
console.log('Initial status check complete');
|
||||
} catch (error) {
|
||||
console.error(`Initial status check failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.isRunning) return;
|
||||
|
||||
console.log(`Starting status notification service (checking every ${this.checkInterval/1000} seconds)`);
|
||||
this.isRunning = true;
|
||||
this.checkTimer = setInterval(() => this.checkStatus(), this.checkInterval);
|
||||
|
||||
// Run the first check
|
||||
this.checkStatus();
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (!this.isRunning) return;
|
||||
|
||||
console.log('Stopping status notification service');
|
||||
clearInterval(this.checkTimer);
|
||||
this.isRunning = false;
|
||||
}
|
||||
|
||||
async fetchStatus() {
|
||||
try {
|
||||
const response = await axios.get(this.statusEndpoint);
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching status: ${error.message}`);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async checkStatus() {
|
||||
try {
|
||||
const currentStatus = await this.fetchStatus();
|
||||
const changes = this.detectChanges(this.previousStatus, currentStatus);
|
||||
|
||||
// If changes detected and not the first check, send notifications
|
||||
if (changes.length > 0 && !this.isFirstCheck) {
|
||||
await this.sendNotifications(changes, currentStatus);
|
||||
}
|
||||
|
||||
// Update previous status and set first check to false
|
||||
this.previousStatus = currentStatus;
|
||||
this.isFirstCheck = false;
|
||||
} catch (error) {
|
||||
console.error(`Status check failed: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
detectChanges(previousStatus, currentStatus) {
|
||||
const changes = [];
|
||||
|
||||
// Check for server status changes
|
||||
if (previousStatus.servers && currentStatus.servers) {
|
||||
for (const server in currentStatus.servers) {
|
||||
// New server or status changed
|
||||
if (!previousStatus.servers[server] ||
|
||||
previousStatus.servers[server].online !== currentStatus.servers[server].online) {
|
||||
changes.push({
|
||||
type: 'server',
|
||||
name: server,
|
||||
status: currentStatus.servers[server].online ? 'online' : 'offline',
|
||||
previous: previousStatus.servers[server]?.online ? 'online' : 'offline',
|
||||
isNew: !previousStatus.servers[server],
|
||||
responseTime: currentStatus.servers[server].responseTime
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check for removed servers
|
||||
for (const server in previousStatus.servers) {
|
||||
if (!currentStatus.servers[server]) {
|
||||
changes.push({
|
||||
type: 'server',
|
||||
name: server,
|
||||
status: 'removed',
|
||||
previous: previousStatus.servers[server].online ? 'online' : 'offline'
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for PM2 service status changes - updated to use pm2Services
|
||||
if (previousStatus.pm2Services && currentStatus.pm2Services) {
|
||||
for (const service in currentStatus.pm2Services) {
|
||||
if (!previousStatus.pm2Services[service] ||
|
||||
previousStatus.pm2Services[service].status !== currentStatus.pm2Services[service].status) {
|
||||
changes.push({
|
||||
type: 'service',
|
||||
name: service,
|
||||
status: currentStatus.pm2Services[service].status,
|
||||
previous: previousStatus.pm2Services[service]?.status || 'unknown',
|
||||
isNew: !previousStatus.pm2Services[service],
|
||||
details: currentStatus.pm2Services[service]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check for removed services
|
||||
for (const service in previousStatus.pm2Services) {
|
||||
if (!currentStatus.pm2Services[service]) {
|
||||
changes.push({
|
||||
type: 'service',
|
||||
name: service,
|
||||
status: 'removed',
|
||||
previous: previousStatus.pm2Services[service].status
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return changes;
|
||||
}
|
||||
|
||||
async sendNotifications(changes, currentStatus) {
|
||||
if (changes.length === 0) return;
|
||||
|
||||
// Create an embed for the notification
|
||||
const embed = {
|
||||
title: 'Status Change Detected',
|
||||
color: 0xFFAA00, // Amber color for notifications
|
||||
timestamp: new Date(),
|
||||
fields: [],
|
||||
footer: {
|
||||
text: 'blahaj.tr Status Monitor'
|
||||
}
|
||||
};
|
||||
|
||||
// Add fields for each change
|
||||
changes.forEach(change => {
|
||||
let fieldContent = '';
|
||||
|
||||
if (change.type === 'server') {
|
||||
const statusEmoji = change.status === 'online' ? '🟢' : (change.status === 'offline' ? '🔴' : '⚪');
|
||||
const previousEmoji = change.previous === 'online' ? '🟢' : (change.previous === 'offline' ? '🔴' : '⚪');
|
||||
|
||||
if (change.isNew) {
|
||||
fieldContent = `${statusEmoji} New server detected: **${change.status}**`;
|
||||
} else if (change.status === 'removed') {
|
||||
fieldContent = `⚪ Server removed (was ${previousEmoji} **${change.previous}**)`;
|
||||
} else {
|
||||
fieldContent = `${previousEmoji} **${change.previous}** → ${statusEmoji} **${change.status}**`;
|
||||
if (change.responseTime !== 'unknown') {
|
||||
fieldContent += `\nResponse time: ${change.responseTime}ms`;
|
||||
}
|
||||
}
|
||||
} else if (change.type === 'service') {
|
||||
let statusEmoji = '⚪';
|
||||
switch (change.status) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
let previousEmoji = '⚪';
|
||||
switch (change.previous) {
|
||||
case 'online': previousEmoji = '🟢'; break;
|
||||
case 'stopping': previousEmoji = '🟠'; break;
|
||||
case 'stopped': previousEmoji = '🔴'; break;
|
||||
case 'errored': previousEmoji = '❌'; break;
|
||||
case 'launching': previousEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
if (change.isNew) {
|
||||
fieldContent = `${statusEmoji} New service detected: **${change.status}**`;
|
||||
} else if (change.status === 'removed') {
|
||||
fieldContent = `⚪ Service removed (was ${previousEmoji} **${change.previous}**)`;
|
||||
} else {
|
||||
fieldContent = `${previousEmoji} **${change.previous}** → ${statusEmoji} **${change.status}**`;
|
||||
|
||||
// Add resource usage if available
|
||||
if (change.details) {
|
||||
const memory = change.details.memory ? Math.round(change.details.memory / (1024 * 1024) * 10) / 10 : 0;
|
||||
fieldContent += `\nCPU: ${change.details.cpu}% | Memory: ${memory}MB`;
|
||||
fieldContent += `\nUptime: ${Math.floor(change.details.uptime / 1000)}s | Restarts: ${change.details.restarts}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
embed.fields.push({
|
||||
name: `${change.type === 'server' ? 'Server' : 'Service'}: ${change.name}`,
|
||||
value: fieldContent,
|
||||
inline: false
|
||||
});
|
||||
});
|
||||
|
||||
// Add a detailed status field if there are many services
|
||||
if (Object.keys(currentStatus.pm2Services || {}).length > 0) {
|
||||
let servicesStatus = '';
|
||||
for (const [name, info] of Object.entries(currentStatus.pm2Services)) {
|
||||
let statusEmoji = '⚪';
|
||||
switch (info.status) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
servicesStatus += `${statusEmoji} **${name}**: ${info.status}\n`;
|
||||
}
|
||||
|
||||
if (servicesStatus) {
|
||||
embed.fields.push({
|
||||
name: 'Current Services Status',
|
||||
value: servicesStatus,
|
||||
inline: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Send to channel if available
|
||||
if (this.statusChannel) {
|
||||
try {
|
||||
await this.statusChannel.send({ embeds: [embed] });
|
||||
console.log('Status change notification sent to channel');
|
||||
} catch (error) {
|
||||
console.error(`Failed to send status notification to channel: ${error.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Send to all notification recipients
|
||||
for (const userId of this.notificationRecipientIds) {
|
||||
try {
|
||||
const user = await this.client.users.fetch(userId);
|
||||
await user.send({ embeds: [embed] });
|
||||
console.log(`Status change notification sent to recipient: ${user.tag}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to send status notification to user ${userId}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = NotificationService;
|
||||
|
|
@ -1,44 +0,0 @@
|
|||
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) {
|
||||
// Get authorized users from the bot instance
|
||||
const authorizedUserIds = client.bot?.authorizedUserIds || [];
|
||||
|
||||
// Check if user ID is in the authorized users array
|
||||
if (!authorizedUserIds.includes(interaction.user.id)) {
|
||||
return interaction.reply({
|
||||
content: "You are not authorized to use system commands.",
|
||||
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;
|
||||
|
|
@ -1,91 +0,0 @@
|
|||
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;
|
||||
|
|
@ -1,539 +0,0 @@
|
|||
const SystemCommandBase = require('../../classes/SystemCommandBase');
|
||||
const { SlashCommandBuilder } = require('discord.js');
|
||||
|
||||
class PM2Control extends SystemCommandBase {
|
||||
constructor(client) {
|
||||
super(client);
|
||||
this.name = 'pm2';
|
||||
this.description = 'Control PM2 processes';
|
||||
}
|
||||
|
||||
addOptions(builder) {
|
||||
return builder
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('list')
|
||||
.setDescription('List all PM2 processes')
|
||||
)
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('info')
|
||||
.setDescription('Get detailed information about a PM2 process')
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName('process')
|
||||
.setDescription('Process name or ID')
|
||||
.setRequired(true)
|
||||
.setAutocomplete(true)
|
||||
)
|
||||
)
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('start')
|
||||
.setDescription('Start a PM2 process')
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName('process')
|
||||
.setDescription('Process name or ID')
|
||||
.setRequired(true)
|
||||
.setAutocomplete(true)
|
||||
)
|
||||
)
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('stop')
|
||||
.setDescription('Stop a PM2 process')
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName('process')
|
||||
.setDescription('Process name or ID')
|
||||
.setRequired(true)
|
||||
.setAutocomplete(true)
|
||||
)
|
||||
)
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('restart')
|
||||
.setDescription('Restart a PM2 process')
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName('process')
|
||||
.setDescription('Process name or ID')
|
||||
.setRequired(true)
|
||||
.setAutocomplete(true)
|
||||
)
|
||||
)
|
||||
.addSubcommand(subcommand =>
|
||||
subcommand
|
||||
.setName('logs')
|
||||
.setDescription('Show recent logs for a PM2 process')
|
||||
.addStringOption(option =>
|
||||
option
|
||||
.setName('process')
|
||||
.setDescription('Process name or ID')
|
||||
.setRequired(true)
|
||||
.setAutocomplete(true)
|
||||
)
|
||||
.addIntegerOption(option =>
|
||||
option
|
||||
.setName('lines')
|
||||
.setDescription('Number of log lines to show')
|
||||
.setRequired(false)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
async execute(interaction) {
|
||||
await interaction.deferReply();
|
||||
|
||||
const subcommand = interaction.options.getSubcommand();
|
||||
|
||||
try {
|
||||
switch (subcommand) {
|
||||
case 'list':
|
||||
await this.handleListCommand(interaction);
|
||||
break;
|
||||
|
||||
case 'info':
|
||||
await this.handleInfoCommand(interaction);
|
||||
break;
|
||||
|
||||
case 'start':
|
||||
await this.handleStartCommand(interaction);
|
||||
break;
|
||||
|
||||
case 'stop':
|
||||
await this.handleStopCommand(interaction);
|
||||
break;
|
||||
|
||||
case 'restart':
|
||||
await this.handleRestartCommand(interaction);
|
||||
break;
|
||||
|
||||
case 'logs':
|
||||
await this.handleLogsCommand(interaction);
|
||||
break;
|
||||
|
||||
default:
|
||||
await interaction.editReply(`Unknown subcommand: ${subcommand}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error executing PM2 command:`, error);
|
||||
await interaction.editReply({
|
||||
content: `Error executing command: ${error.message}`
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleListCommand(interaction) {
|
||||
const { stdout } = await this.execCommand('pm2 jlist');
|
||||
|
||||
try {
|
||||
const processes = JSON.parse(stdout);
|
||||
|
||||
if (processes.length === 0) {
|
||||
await interaction.editReply('No PM2 processes found.');
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = {
|
||||
title: 'PM2 Process List',
|
||||
color: 0x3498db,
|
||||
fields: [],
|
||||
timestamp: new Date(),
|
||||
footer: { text: 'PM2 Process Manager' }
|
||||
};
|
||||
|
||||
processes.forEach(proc => {
|
||||
// Format memory to MB
|
||||
const memory = Math.round(proc.monit.memory / (1024 * 1024) * 10) / 10;
|
||||
|
||||
// Get appropriate status emoji
|
||||
let statusEmoji = '⚪';
|
||||
switch (proc.pm2_env.status) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
// Calculate uptime
|
||||
const uptime = proc.pm2_env.status === 'online' ?
|
||||
this.formatUptime(Date.now() - proc.pm2_env.pm_uptime) :
|
||||
'Not running';
|
||||
|
||||
embed.fields.push({
|
||||
name: `${statusEmoji} ${proc.name} (ID: ${proc.pm_id})`,
|
||||
value: [
|
||||
`**Status:** ${proc.pm2_env.status}`,
|
||||
`**CPU:** ${proc.monit.cpu}%`,
|
||||
`**Memory:** ${memory} MB`,
|
||||
`**Uptime:** ${uptime}`,
|
||||
`**Restarts:** ${proc.pm2_env.restart_time}`
|
||||
].join('\n'),
|
||||
inline: true
|
||||
});
|
||||
});
|
||||
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list:', error);
|
||||
await interaction.editReply({
|
||||
content: `Failed to parse PM2 process list: ${error.message}`,
|
||||
files: stdout.length > 0 ? [{
|
||||
attachment: Buffer.from(stdout),
|
||||
name: 'pm2-list.json'
|
||||
}] : []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleInfoCommand(interaction) {
|
||||
const processName = interaction.options.getString('process');
|
||||
|
||||
// Get detailed info about the process
|
||||
const { success, stdout, stderr } = await this.execCommand(`pm2 show ${processName} --format json`);
|
||||
|
||||
if (!success) {
|
||||
await interaction.editReply(`Failed to get info for PM2 process "${processName}":\n\`\`\`${stderr}\`\`\``);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Parse the JSON output
|
||||
const procInfo = JSON.parse(stdout);
|
||||
|
||||
// Get status emoji
|
||||
let statusEmoji = '⚪';
|
||||
switch (procInfo.status) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
// Format memory
|
||||
const memory = procInfo.memory ?
|
||||
Math.round(procInfo.memory / (1024 * 1024) * 10) / 10 :
|
||||
0;
|
||||
|
||||
// Create embed
|
||||
const embed = {
|
||||
title: `${statusEmoji} PM2 Process: ${procInfo.name}`,
|
||||
color: procInfo.status === 'online' ? 0x00FF00 : 0xFF0000,
|
||||
fields: [
|
||||
{
|
||||
name: 'General',
|
||||
value: [
|
||||
`**ID:** ${procInfo.pm_id}`,
|
||||
`**Status:** ${procInfo.status}`,
|
||||
`**Version:** ${procInfo.version || 'N/A'}`,
|
||||
`**Instances:** ${procInfo.exec_instances || 1}`,
|
||||
`**Exec Mode:** ${procInfo.exec_mode || 'N/A'}`
|
||||
].join('\n'),
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: 'Resources',
|
||||
value: [
|
||||
`**CPU:** ${procInfo.cpu || 0}%`,
|
||||
`**Memory:** ${memory} MB`,
|
||||
`**Uptime:** ${this.formatUptime(procInfo.pm_uptime) || 'Not running'}`,
|
||||
`**Restarts:** ${procInfo.restart_time || 0}`,
|
||||
`**Unstable Restarts:** ${procInfo.unstable_restarts || 0}`
|
||||
].join('\n'),
|
||||
inline: true
|
||||
},
|
||||
{
|
||||
name: 'Paths',
|
||||
value: [
|
||||
`**Path:** ${procInfo.path || 'N/A'}`,
|
||||
`**Current Path:** ${procInfo.cwd || 'N/A'}`,
|
||||
`**Script:** ${procInfo.script || 'N/A'}`
|
||||
].join('\n'),
|
||||
inline: false
|
||||
}
|
||||
],
|
||||
timestamp: new Date(),
|
||||
footer: { text: 'PM2 Process Manager' }
|
||||
};
|
||||
|
||||
// Add logs section if available
|
||||
if (procInfo.out_log_path || procInfo.error_log_path) {
|
||||
embed.fields.push({
|
||||
name: 'Logs',
|
||||
value: [
|
||||
`**Output:** ${procInfo.out_log_path || 'N/A'}`,
|
||||
`**Error:** ${procInfo.error_log_path || 'N/A'}`
|
||||
].join('\n'),
|
||||
inline: false
|
||||
});
|
||||
}
|
||||
|
||||
await interaction.editReply({ embeds: [embed] });
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process info:', error);
|
||||
await interaction.editReply(`Failed to parse info for PM2 process "${processName}":\n\`\`\`${error.message}\`\`\``);
|
||||
}
|
||||
}
|
||||
|
||||
async handleStartCommand(interaction) {
|
||||
const processName = interaction.options.getString('process');
|
||||
|
||||
// First get current status
|
||||
const { success: infoSuccess, stdout: infoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let beforeStatus = 'unknown';
|
||||
|
||||
if (infoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(infoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
beforeStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list before start:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Start the process
|
||||
await interaction.editReply(`Starting PM2 process \`${processName}\`...`);
|
||||
const { success, stdout, stderr } = await this.execCommand(`pm2 start ${processName}`);
|
||||
|
||||
if (!success) {
|
||||
await interaction.editReply(`Failed to start PM2 process "${processName}":\n\`\`\`${stderr}\`\`\``);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get new status
|
||||
const { success: newInfoSuccess, stdout: newInfoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let afterStatus = 'unknown';
|
||||
|
||||
if (newInfoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(newInfoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
afterStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list after start:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Create status emoji
|
||||
let statusEmoji = '⚪';
|
||||
switch (afterStatus) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
await interaction.editReply(`PM2 process \`${processName}\` started.\n\nStatus: ${statusEmoji} ${afterStatus}\nPrevious status: ${beforeStatus}`);
|
||||
}
|
||||
|
||||
async handleStopCommand(interaction) {
|
||||
const processName = interaction.options.getString('process');
|
||||
|
||||
// First get current status
|
||||
const { success: infoSuccess, stdout: infoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let beforeStatus = 'unknown';
|
||||
|
||||
if (infoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(infoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
beforeStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list before stop:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Stop the process
|
||||
await interaction.editReply(`Stopping PM2 process \`${processName}\`...`);
|
||||
const { success, stdout, stderr } = await this.execCommand(`pm2 stop ${processName}`);
|
||||
|
||||
if (!success) {
|
||||
await interaction.editReply(`Failed to stop PM2 process "${processName}":\n\`\`\`${stderr}\`\`\``);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get new status
|
||||
const { success: newInfoSuccess, stdout: newInfoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let afterStatus = 'unknown';
|
||||
|
||||
if (newInfoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(newInfoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
afterStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list after stop:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Create status emoji
|
||||
let statusEmoji = '⚪';
|
||||
switch (afterStatus) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
await interaction.editReply(`PM2 process \`${processName}\` stopped.\n\nStatus: ${statusEmoji} ${afterStatus}\nPrevious status: ${beforeStatus}`);
|
||||
}
|
||||
|
||||
async handleRestartCommand(interaction) {
|
||||
const processName = interaction.options.getString('process');
|
||||
|
||||
// First get current status
|
||||
const { success: infoSuccess, stdout: infoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let beforeStatus = 'unknown';
|
||||
|
||||
if (infoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(infoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
beforeStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list before restart:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Restart the process
|
||||
await interaction.editReply(`Restarting PM2 process \`${processName}\`...`);
|
||||
const { success, stdout, stderr } = await this.execCommand(`pm2 restart ${processName}`);
|
||||
|
||||
if (!success) {
|
||||
await interaction.editReply(`Failed to restart PM2 process "${processName}":\n\`\`\`${stderr}\`\`\``);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get new status
|
||||
const { success: newInfoSuccess, stdout: newInfoStdout } = await this.execCommand(`pm2 jlist`);
|
||||
let afterStatus = 'unknown';
|
||||
|
||||
if (newInfoSuccess) {
|
||||
try {
|
||||
const processes = JSON.parse(newInfoStdout);
|
||||
const proc = processes.find(p => p.name === processName || p.pm_id.toString() === processName);
|
||||
if (proc) {
|
||||
afterStatus = proc.pm2_env.status;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing PM2 process list after restart:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Create status emoji
|
||||
let statusEmoji = '⚪';
|
||||
switch (afterStatus) {
|
||||
case 'online': statusEmoji = '🟢'; break;
|
||||
case 'stopping': statusEmoji = '🟠'; break;
|
||||
case 'stopped': statusEmoji = '🔴'; break;
|
||||
case 'errored': statusEmoji = '❌'; break;
|
||||
case 'launching': statusEmoji = '🟡'; break;
|
||||
}
|
||||
|
||||
await interaction.editReply(`PM2 process \`${processName}\` restarted.\n\nStatus: ${statusEmoji} ${afterStatus}\nPrevious status: ${beforeStatus}`);
|
||||
}
|
||||
|
||||
async handleLogsCommand(interaction) {
|
||||
const processName = interaction.options.getString('process');
|
||||
const lines = interaction.options.getInteger('lines') || 20;
|
||||
|
||||
// Get logs for the process
|
||||
await interaction.editReply(`Fetching logs for PM2 process \`${processName}\`...`);
|
||||
const { success, stdout, stderr } = await this.execCommand(`pm2 logs ${processName} --lines ${lines} --nostream --raw`);
|
||||
|
||||
if (!success) {
|
||||
await interaction.editReply(`Failed to get logs for PM2 process "${processName}":\n\`\`\`${stderr}\`\`\``);
|
||||
return;
|
||||
}
|
||||
|
||||
// Format the logs
|
||||
const logs = stdout.trim();
|
||||
|
||||
if (!logs) {
|
||||
await interaction.editReply(`No logs found for PM2 process \`${processName}\`.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// If logs are too long, split into files
|
||||
if (logs.length > 1950) {
|
||||
await interaction.editReply({
|
||||
content: `Logs for PM2 process \`${processName}\` (last ${lines} lines):`,
|
||||
files: [{
|
||||
attachment: Buffer.from(logs),
|
||||
name: `${processName}-logs.txt`
|
||||
}]
|
||||
});
|
||||
} else {
|
||||
await interaction.editReply(`Logs for PM2 process \`${processName}\` (last ${lines} lines):\n\`\`\`\n${logs}\n\`\`\``);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper method to autocomplete process names
|
||||
async handleAutocomplete(interaction) {
|
||||
try {
|
||||
const focusedValue = interaction.options.getFocused();
|
||||
const { success, stdout } = await this.execCommand('pm2 jlist');
|
||||
|
||||
if (!success) {
|
||||
return interaction.respond([]);
|
||||
}
|
||||
|
||||
const processes = JSON.parse(stdout);
|
||||
const choices = processes.map(proc => ({
|
||||
name: `${proc.name} (${proc.pm2_env.status})`,
|
||||
value: proc.name
|
||||
}));
|
||||
|
||||
// Filter choices based on user input
|
||||
const filtered = choices.filter(choice =>
|
||||
choice.name.toLowerCase().includes(focusedValue.toLowerCase())
|
||||
);
|
||||
|
||||
await interaction.respond(filtered.slice(0, 25));
|
||||
} catch (error) {
|
||||
console.error('Error in PM2 autocomplete:', error);
|
||||
await interaction.respond([]);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to format uptime
|
||||
formatUptime(ms) {
|
||||
if (!ms || ms <= 0) return 'Not running';
|
||||
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
return `${days}d ${hours % 24}h ${minutes % 60}m`;
|
||||
} else if (hours > 0) {
|
||||
return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes}m ${seconds % 60}s`;
|
||||
} else {
|
||||
return `${seconds}s`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PM2Control;
|
||||
Loading…
Add table
Add a link
Reference in a new issue