Home > Blockchain >  how to add aliases to a command handler in discord.js
how to add aliases to a command handler in discord.js

Time:09-24

I have found on other stack overflow questions that to add aliases you just have to add

const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

but this doesn't work. What I don't understand is what cmd is because it is not defined anywhere else in my code although it is passed in through the arrow function anyway. When using this I can still use the commands but when I use the aliases nothing happens, no message or error in the console. Could anyone assist me on this, Thanks for any help. Here is my code for the command handler:

client.on('messageCreate', message => {
if (message.author.bot) return;
if (!message.content.startsWith(process.env.PREFIX)) return;

const args = message.content.slice(process.env.PREFIX.length).trim().split(/  /);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

if (!client.commands.has(commandName)) return;

if (message.channel.name == 'general') return message.reply('smh no bot commands in general :raised_hand:');

if (!message.guild.me.permissions.has('SEND_MESSAGES')) return message.member.send(`I need the 'SEND_MESSAGES' permission to be able to reply to commands in  the server: ${message.guild.name}`);

try {
    command.execute(message, args, distube);
} catch(error) {
    console.error(error);
    message.reply('Uh oh! It looks like you have encountered a glitch up in the system, please try again later! || <@498615291908194324> fix yo dead bot ||')
}

});

And the command file:

name: 'ping',
description: 'Ping Command',
aliases: ['pg'],
execute(message, args) {
    let ping = new Date().getTime() - message.createdTimestamp
    message.reply(`pong (${ping}ms)`);
}

CodePudding user response:

This line is the problem

if (!client.commands.has(commandName)) return;

You map the collection in a <string, Object> format but the string is the command name, not the alias. The better way is replacing the above line of code with this:

if (!command) return;

This will return early if command is falsey (it was not found) but it will work with aliases.

  • Related