how to add aliases to a command handler in discord.js


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 ( 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 ( == 'general') return message.reply('smh no bot commands in general :raised_hand:');

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

try {
    command.execute(message, args, distube);
} catch(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)`);


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.

Answered By – MrMythical

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published