Discord.JS bot - how can I include spaces in my command names?

Viewed 547

When I include spaces in my command names, those commands won't run. I'm using a command handler and in my index.js file, we have:

client.on('message', msg => {
    if (!msg.content.startsWith(prefix) || msg.author.bot) return;
    const args = msg.content.slice(prefix.length).trim().split(/ +/g);
    const commandName = args.shift().toLowerCase();
    const command = client.commands.get(commandName)
    || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
    if (!command) return;
    try {
    command.execute(msg, args);
    } catch (error) {
    console.error(error);
    msg.reply("I'm encountering an error trying to execute that command. Please try again.");
    }
    });

and in my command.js file, we have:

module.exports = {
    name: 'command name',
    execute(msg, args) {
    msg.channel.send("command");
    },
};

When I change command name to command-name or to commandname it works! But when it's command name, my bot doesn't output any response... not even an error message. Where am I going wrong? Is there some simple solution or workaround that I'm overlooking? Thanks in advance.

1 Answers

This is because you shift() your arguments in the line

const commandName = args.shift().toLowerCase();

This takes the first argument and returns it, any following arguments will not be included. To take the first 2 argument use

const commandName = args.splice(0, 2);

Change command to the following to account for any other arguments.

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