Skip to content

Instantly share code, notes, and snippets.

@Binary-Bytes
Last active June 26, 2022 13:50
Show Gist options
  • Save Binary-Bytes/259a3a112a3b7fa3defa176585dd1120 to your computer and use it in GitHub Desktop.
Save Binary-Bytes/259a3a112a3b7fa3defa176585dd1120 to your computer and use it in GitHub Desktop.
Example advanced discord.js command handler with aliases system
// Example advanced discord.js command handler with aliases system
// IDK Why I Commented And Explained Everything :man_shrugging:
// MAIN INDEX FILE
// Import Packages
const Discord = require('discord.js');
const fs = require('fs');
// Create a Discord Client (Not Including)
// Login The Client (Not Including)
// Create Prefix
let prefix = '!'
// Create a New Collection
client.commands = new Discord.Collection();
// Find All Command Files
const cmdFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
// Loop Over Each File
for (const file of cmdFiles) {
// Get That File
const cmd = require(`./commands/${file}`);
// Save The File
client.commands.set(cmd.name, cmd);
// Get Each Alias
for (let alias of cmd.aliases) {
// Save The Alias
client.commands.set(alias.toString(), cmd);
}
}
// EXAMPLE USAGE
client.on("message", async message => {
if (!message.guild || message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/);
let cmd = args.shift().toLowerCase();
if (cmd && cmd.length >= 1) {
try {
client.commands.get(cmd).execute(client, cmd, args, prefix, message);
} catch (error) {
const embed = new Discord.MessageEmbed()
.setDescription('Command not found!')
.setColor('#f5bc42')
message.reply({
embeds: [embed]
});
}
return;
}
});
// EXAMPLE COMMAND FILE
module.exports = {
name: 'test_cmd',
description: 'A testing cmd',
type: 'admin',
args: [],
aliases: ['test', 'tcmd'],
async execute(client, cmd, args, prefix, message) {
message.reply('okk')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment