Search code examples
javascriptnode.jsdiscorddiscord.js

how to add space in commands? discord.js


I want my command to include a space, for example

$ sudo faq mod (note the space)

But that doesn't seem to work, and I usually have to just do

faq_mod instead.

This is my code, but spaces don't work.

const { Client, Intents } = require('discord.js');

const Discord = require('discord.js');

const mongoose = require('mongoose')

require('dotenv').config();

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const prefix = '$ sudo ';

const fs = require('fs');
    
client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.commands.set(command.name, command);
}


client.once('ready', async () => {
    console.log(`Logged in as ${client.user.tag}!`);
    client.user.setActivity('$ sudo help | heckbot.ml');
    await mongoose.connect(process.env.MONGO_URI, {
        keepAlive: true,
        
    })
})




client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/)
    const command = args.shift().toLowerCase();

    if (command === 'ping') {
        client.commands.get('ping').execute(message, args);
    } else if (command === 'info') {
        client.commands.get('info').execute(message, args);
    } else if (command === 'website') {
        client.commands.get('website').execute(message, args);;
    } else if (command === 'help') {
        client.commands.get('help').execute(message, args);
    } else if (command === 'youtube') {
        client.commands.get('youtube').execute(message, args);
    } else if (command === 'invite') {
        client.commands.get('invite').execute(message, args);
    } else if (command === 'kick') {
        client.commands.get('kick').execute(message, args);
    } else if (command === 'ban') {
        client.commands.get('ban').execute(message, args);
    } else if (command === 'clear') {
        client.commands.get('clear').execute(message, args);
    } else if (command === 'faq mod') {
        client.commands.get('faq_mod').execute(message, args, Discord);
    }
});

client.login(process.env.TOKEN)

please help me


Solution

  • You can't include spaces when checking for commands because you are "splitting" the string by spaces when you define args.

    The line

    const args = message.content.slice(prefix.length).split(/ +/)
    

    Will remove the prefix and split the resulting string into spaces. (e.g.: "good morning" turns into ["good", "morning"]). To check for two consecutive arguments, you could do

    if(command == "faq" && args[0] == "mod")