Merge pull request 'feature/eslint' (#2) from feature/eslint into main

Reviewed-on: #2
This commit is contained in:
Louis Gallet 2024-02-27 10:43:22 +00:00
commit 8b803c47f0
13 changed files with 238 additions and 210 deletions

View File

@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

6
.idea/jsLinters/eslint.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EslintConfiguration">
<option name="fix-on-save" value="true" />
</component>
</project>

View File

@ -1,58 +1,64 @@
const { ButtonBuilder, ButtonStyle, SlashCommandBuilder, ActionRow, ActionRowBuilder} = require('discord.js') const { ButtonBuilder, ButtonStyle, SlashCommandBuilder, ActionRowBuilder } = require('discord.js');
const config = require('../../config.json') const config = require('../../config.json');
if (!config.proxmoxUser || !config.proxmoxPass || !config.proxmoxHostname) { if (!config.proxmoxUser || !config.proxmoxPass || !config.proxmoxHostname) {
console.error("Proxmox credentials not found in config.json. Exiting."); console.error('Proxmox credentials not found in config.json. Exiting.');
process.exit(1); process.exit(1);
} }
proxmox = require("proxmox")(config.proxmoxUser, config.proxmoxPass, config.proxmoxHostname); // eslint-disable-next-line no-undef
proxmox = require('proxmox')(config.proxmoxUser, config.proxmoxPass, config.proxmoxHostname);
module.exports = { module.exports = {
cooldowns: 60, cooldowns: 60,
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('start-mc') .setName('start-mc')
.setDescription('Starts the minecraft server machine.'), .setDescription('Starts the minecraft server machine.'),
async execute(interaction) { async execute(interaction) {
const confirm = new ButtonBuilder() const confirm = new ButtonBuilder()
.setCustomId('confirm') .setCustomId('confirm')
.setLabel('Confirm') .setLabel('Confirm')
.setStyle(ButtonStyle.Primary) .setStyle(ButtonStyle.Primary);
const cancel = new ButtonBuilder() const cancel = new ButtonBuilder()
.setCustomId('cancel') .setCustomId('cancel')
.setLabel('Cancel') .setLabel('Cancel')
.setStyle(ButtonStyle.Danger) .setStyle(ButtonStyle.Danger);
const row = new ActionRowBuilder() const row = new ActionRowBuilder()
.addComponents(cancel, confirm) .addComponents(cancel, confirm);
const response = await interaction.reply({ const response = await interaction.reply({
content: 'Are you sure you want to start the Minecraft server?', content: 'Are you sure you want to start the Minecraft server?',
components: [row] components: [row],
}) });
const collectorFilter = i => i.user.id === interaction.user.id; const collectorFilter = i => i.user.id === interaction.user.id;
try { try {
const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, time: 30_000 }); const confirmation = await response.awaitMessageComponent({ filter: collectorFilter, time: 30_000 });
if (confirmation.customId === 'confirm') { if (confirmation.customId === 'confirm') {
proxmox.qemu.start("pve", "102", function(err, res) { // eslint-disable-next-line no-undef
if (err) { proxmox.qemu.start('pve', '102', function(err) {
confirmation.update("Error starting the Minecraft server: " + err); if (err) {
} else { confirmation.update('Error starting the Minecraft server: ' + err);
const linkButton = new ButtonBuilder() }
.setStyle(ButtonStyle.Link) else {
.setLabel('Web Interface') const linkButton = new ButtonBuilder()
.setURL('https://mc.louisgallet.fr') .setStyle(ButtonStyle.Link)
const row = new ActionRowBuilder() .setLabel('Web Interface')
.addComponents(linkButton) .setURL('https://mc.louisgallet.fr');
confirmation.update({content: "Minecraft server started successfully. Please wait a few minutes for it to boot.", components: [row]}); const linkRow = new ActionRowBuilder()
} .addComponents(linkButton);
}) confirmation.update({ content: 'Minecraft server started successfully. Please wait a few minutes for it to boot.', components: [linkRow] });
} else if (confirmation.customId === 'cancel') { }
await confirmation.update({ content: 'Minecraft server start cancelled.', components: [] }); });
} }
} catch (e) { else if (confirmation.customId === 'cancel') {
await confirmation.update({ content: 'You took too long to respond.', components: [] }); await confirmation.update({ content: 'Minecraft server start cancelled.', components: [] });
} }
}
catch (e) {
// eslint-disable-next-line no-undef
await confirmation.update({ content: 'You took too long to respond.', components: [] });
}
} },
} };

View File

@ -1,23 +1,24 @@
const { SlashCommandBuilder } = require('discord.js') const { SlashCommandBuilder } = require('discord.js');
const config = require('../../config.json') const config = require('../../config.json');
if (!config.proxmoxUser || !config.proxmoxPass || !config.proxmoxHostname) { if (!config.proxmoxUser || !config.proxmoxPass || !config.proxmoxHostname) {
console.error("Proxmox credentials not found in config.json. Exiting."); console.error('Proxmox credentials not found in config.json. Exiting.');
process.exit(1); process.exit(1);
} }
proxmox = require("proxmox")(config.proxmoxUser, config.proxmoxPass, config.proxmoxHostname); const proxmox = require('proxmox')(config.proxmoxUser, config.proxmoxPass, config.proxmoxHostname);
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('stop-mc') .setName('stop-mc')
.setDescription('Stops the minecraft server machine.'), .setDescription('Stops the minecraft server machine.'),
async execute(interaction) { async execute(interaction) {
proxmox.qemu.shutdown("pve", "102", function(err, res) { proxmox.qemu.shutdown('pve', '102', function(err) {
if (err) { if (err) {
interaction.reply("Error starting the Minecraft server: " + err); interaction.reply('Error starting the Minecraft server: ' + err);
} else { }
interaction.reply("Minecraft server stopped successfully."); else {
} interaction.reply('Minecraft server stopped successfully.');
}) }
} });
} },
};

View File

@ -1,10 +1,10 @@
const { SlashCommandBuilder } = require('discord.js') const { SlashCommandBuilder } = require('discord.js');
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('ping') .setName('ping')
.setDescription('Replies with Pong'), .setDescription('Replies with Pong'),
async execute(interaction) { async execute(interaction) {
await interaction.reply('Pong') await interaction.reply('Pong');
}, },
} };

View File

@ -1,32 +1,33 @@
const { SlashCommandBuilder } = require('discord.js'); const { SlashCommandBuilder } = require('discord.js');
module.exports = { module.exports = {
category: 'utility', category: 'utility',
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('reload') .setName('reload')
.setDescription('Reloads a command.') .setDescription('Reloads a command.')
.addStringOption(option => .addStringOption(option =>
option.setName('command') option.setName('command')
.setDescription('The command to reload.') .setDescription('The command to reload.')
.setRequired(true)), .setRequired(true)),
async execute(interaction) { async execute(interaction) {
const commandName = interaction.options.getString('command', true).toLowerCase(); const commandName = interaction.options.getString('command', true).toLowerCase();
const command = interaction.client.commands.get(commandName); const command = interaction.client.commands.get(commandName);
if (!command) { if (!command) {
return interaction.reply(`There is no command with name \`${commandName}\`!`); return interaction.reply(`There is no command with name \`${commandName}\`!`);
} }
delete require.cache[require.resolve(`../${command.category}/${command.data.name}.js`)]; delete require.cache[require.resolve(`../${command.category}/${command.data.name}.js`)];
try { try {
await interaction.client.commands.delete(command.data.name); await interaction.client.commands.delete(command.data.name);
const newCommand = require(`../${command.category}/${command.data.name}.js`); const newCommand = require(`../${command.category}/${command.data.name}.js`);
await interaction.client.commands.set(newCommand.data.name, newCommand); await interaction.client.commands.set(newCommand.data.name, newCommand);
await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`); await interaction.reply(`Command \`${newCommand.data.name}\` was reloaded!`);
} catch (error) { }
console.error(error); catch (error) {
await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``); console.error(error);
} await interaction.reply(`There was an error while reloading a command \`${command.data.name}\`:\n\`${error.message}\``);
}, }
},
}; };

View File

@ -1,11 +1,11 @@
const { SlashCommandBuilder } = require('discord.js'); const { SlashCommandBuilder } = require('discord.js');
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('server') .setName('server')
.setDescription('Provides information about the server.'), .setDescription('Provides information about the server.'),
async execute(interaction) { async execute(interaction) {
// interaction.guild is the object representing the Guild in which the command was run // interaction.guild is the object representing the Guild in which the command was run
await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`); await interaction.reply(`This server is ${interaction.guild.name} and has ${interaction.guild.memberCount} members.`);
}, },
}; };

View File

@ -1,12 +1,12 @@
const { SlashCommandBuilder } = require('discord.js'); const { SlashCommandBuilder } = require('discord.js');
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('user') .setName('user')
.setDescription('Provides information about the user.'), .setDescription('Provides information about the user.'),
async execute(interaction) { async execute(interaction) {
// interaction.user is the object representing the User who ran the command // interaction.user is the object representing the User who ran the command
// interaction.member is the GuildMember object, which represents the user in the specific guild // interaction.member is the GuildMember object, which represents the user in the specific guild
await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`); await interaction.reply(`This command was run by ${interaction.user.username}, who joined on ${interaction.member.joinedAt}.`);
}, },
}; };

View File

@ -9,19 +9,20 @@ const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath); const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) { for (const folder of commandFolders) {
// Grab all the command files from the commands directory you created earlier // Grab all the command files from the commands directory you created earlier
const commandsPath = path.join(foldersPath, folder); const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
// Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment
for (const file of commandFiles) { for (const file of commandFiles) {
const filePath = path.join(commandsPath, file); const filePath = path.join(commandsPath, file);
const command = require(filePath); const command = require(filePath);
if ('data' in command && 'execute' in command) { if ('data' in command && 'execute' in command) {
commands.push(command.data.toJSON()); commands.push(command.data.toJSON());
} else { }
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); else {
} console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
} }
}
} }
// Construct and prepare an instance of the REST module // Construct and prepare an instance of the REST module
@ -29,18 +30,19 @@ const rest = new REST().setToken(token);
// and deploy your commands! // and deploy your commands!
(async () => { (async () => {
try { try {
console.log(`Started refreshing ${commands.length} application (/) commands.`); console.log(`Started refreshing ${commands.length} application (/) commands.`);
// The put method is used to fully refresh all commands in the guild with the current set // The put method is used to fully refresh all commands in the guild with the current set
const data = await rest.put( const data = await rest.put(
Routes.applicationGuildCommands(clientId, guildId), Routes.applicationGuildCommands(clientId, guildId),
{ body: commands }, { body: commands },
); );
console.log(`Successfully reloaded ${data.length} application (/) commands.`); console.log(`Successfully reloaded ${data.length} application (/) commands.`);
} catch (error) { }
// And of course, make sure you catch and log any errors! catch (error) {
console.error(error); // And of course, make sure you catch and log any errors!
} console.error(error);
}
})(); })();

View File

@ -1,26 +1,28 @@
const { Events } = require('discord.js'); const { Events } = require('discord.js');
module.exports = { module.exports = {
name: Events.InteractionCreate, name: Events.InteractionCreate,
async execute(interaction) { async execute(interaction) {
if (!interaction.isChatInputCommand()) return; if (!interaction.isChatInputCommand()) return;
const command = interaction.client.commands.get(interaction.commandName); const command = interaction.client.commands.get(interaction.commandName);
if (!command) { if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`); console.error(`No command matching ${interaction.commandName} was found.`);
return; return;
} }
try { try {
await command.execute(interaction); await command.execute(interaction);
} catch (error) { }
console.error(error); catch (error) {
if (interaction.replied || interaction.deferred) { console.error(error);
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true }); if (interaction.replied || interaction.deferred) {
} else { await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); }
} else {
} await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}, }
}
},
}; };

View File

@ -1,9 +1,9 @@
const { Events } = require('discord.js'); const { Events } = require('discord.js');
module.exports = { module.exports = {
name: Events.ClientReady, name: Events.ClientReady,
once: true, once: true,
execute(client) { execute(client) {
console.log(`Ready! Logged in as ${client.user.tag}`); console.log(`Ready! Logged in as ${client.user.tag}`);
}, },
}; };

View File

@ -11,65 +11,68 @@ const foldersPath = path.join(__dirname, 'commands');
const commandFolders = fs.readdirSync(foldersPath); const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) { for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder); const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for (const file of commandFiles) { for (const file of commandFiles) {
const filePath = path.join(commandsPath, file); const filePath = path.join(commandsPath, file);
const command = require(filePath); const command = require(filePath);
if ('data' in command && 'execute' in command) { if ('data' in command && 'execute' in command) {
client.commands.set(command.data.name, command); client.commands.set(command.data.name, command);
} else { }
console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); else {
} console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`);
} }
}
} }
client.once(Events.ClientReady, c => { client.once(Events.ClientReady, c => {
console.log(`Ready! Logged in as ${c.user.tag}`); console.log(`Ready! Logged in as ${c.user.tag}`);
}); });
client.on(Events.InteractionCreate, async interaction => { client.on(Events.InteractionCreate, async interaction => {
if (!interaction.isChatInputCommand()) return; if (!interaction.isChatInputCommand()) return;
const command = client.commands.get(interaction.commandName); const command = client.commands.get(interaction.commandName);
if (!command) { if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`); console.error(`No command matching ${interaction.commandName} was found.`);
return; return;
} }
const { cooldowns } = interaction.client; const { cooldowns } = interaction.client;
if (!cooldowns.has(command.data.name)) { if (!cooldowns.has(command.data.name)) {
cooldowns.set(command.data.name, new Collection()); cooldowns.set(command.data.name, new Collection());
} }
const now = Date.now(); const now = Date.now();
const timestamps = cooldowns.get(command.data.name); const timestamps = cooldowns.get(command.data.name);
const defaultCooldownDuration = 3; const defaultCooldownDuration = 3;
const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1000; const cooldownAmount = (command.cooldown ?? defaultCooldownDuration) * 1000;
if (timestamps.has(interaction.user.id)) { if (timestamps.has(interaction.user.id)) {
const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount; const expirationTime = timestamps.get(interaction.user.id) + cooldownAmount;
if (now < expirationTime) { if (now < expirationTime) {
const expiredTimestamp = Math.round(expirationTime / 1000); const expiredTimestamp = Math.round(expirationTime / 1000);
return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true }); return interaction.reply({ content: `Please wait, you are on a cooldown for \`${command.data.name}\`. You can use it again <t:${expiredTimestamp}:R>.`, ephemeral: true });
} }
} }
timestamps.set(interaction.user.id, now); timestamps.set(interaction.user.id, now);
setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount); setTimeout(() => timestamps.delete(interaction.user.id), cooldownAmount);
try { try {
await command.execute(interaction); await command.execute(interaction);
} catch (error) { }
console.error(error); catch (error) {
if (interaction.replied || interaction.deferred) { console.error(error);
await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true }); if (interaction.replied || interaction.deferred) {
} else { await interaction.followUp({ content: 'There was an error while executing this command!', ephemeral: true });
await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true }); }
} else {
} await interaction.reply({ content: 'There was an error while executing this command!', ephemeral: true });
}
}
}); });
client.login(token); client.login(token);

View File

@ -6,7 +6,8 @@
"scripts": { "scripts": {
"dev": "node deploy-commands.js && nodemon index.js", "dev": "node deploy-commands.js && nodemon index.js",
"start": "node deploy-commands.js && node index.js", "start": "node deploy-commands.js && node index.js",
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint . --fix"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",