Zuher Laith
Zuher Laith

Reputation: 27

Reading args with spaces in node.js

In discord.js I'm trying to read args having no space issues, for example:

const { MessageEmbed } = require("discord.js");

module.exports = {

run: async (client, message, args, { GuildDB }) => {
    let roleName = args[0];
    let roleColor = args[1];
},
};

Problem is, "roleName" doesn't allow to me to use spaces and it counts the second word as roleColor when I use spaces in roleName

How do I easy control args? splits? or use spaces between args?

Any help is appreciated.

Upvotes: 1

Views: 938

Answers (2)

Zero
Zero

Reputation: 2286

Best thing you could do here is create a TextChannel#createMessageCollector since you have multiple arguments to get as input easiest way to do it would be like so: ( Example user command !createrole )

let rolename = args.join(" ") 
message.channel.send("Alright now what would be it's color?").then( msg => 
const filter = (m) => { m.author.id === message.author.id }
const collector = msg.channel.createMessageCollector(filter, { time: 15000 })
collector.on('collect', collected => {
message.channel.send(`Alright creating the role ${rolename} with color ${collected.first().content}`); 
message.guild.roles.create({
    name: rolename
    color: collected.first().content;
})
});

Upvotes: 0

Elitezen
Elitezen

Reputation: 6730

You can handle how the array and split and joined.

To make this easier for yourslef I first recommend you switch the places of your arguments. [command] [roleColor] [roleName] instead of [command] [roleName] [roleColor].

This way we can isolate the color and then use the remaining elements to assign and join to roleName

const { MessageEmbed } = require("discord.js");

module.exports = {
    run: async (client, message, args, { GuildDB }) => {
        // Deconstruct from the args array
        let [roleColor, roleName] = [args[0], args.slice(1)];

        // If there are more than 1 element, join them into a string via a space
        roleName = roleName.join(' ');
    },
};

Upvotes: 1

Related Questions