client.on('message', message => { if (!message.content.startsWith(prefix) || message.author.bot) return; const args = message.content.slice(prefix.length).trim().split(/ +/); const command = args.shift().toLowerCase(); if (command === 'args-info') { if (!args.length) { return message.channel.send(`You didn't provide any arguments, ${message.author}!`); } else if (args[0] === 'foo') { return message.channel.send('bar'); } message.channel.send(`Command name: ${command}nArguments: ${args}`); message.channel.send(`Second argument: ${args[1]}`); message.channel.send(`Arguments: {}`); } } }
This is the part that is relevant to the question.
If you message the bot “Here are my arguments what do you think about that?”, I want it to return:
Command name: args-info Arguments: here,are,my,arguments,what,do,you,think,about,that Second argument: are **Arguments Length: 10**
I need to figure out the command that counts the number of words in a sentence and change this: message.channel.send(`Arguments: ${}`);
I’m not familiar with Discord.js functions and which one can count a character string. I will look some more but I haven’t found anything yet. The reason I ask is this person put it as an example in his code but he never shows the code of how to return the answer and I’m just curious.
https://discordjs.guide/creating-your-bot/commands-with-user-input.html#basic-arguments
Advertisement
Answer
args
is already an array of the words, so you can print the .length
property of that. It will return the number of elements (words in this case) in that array.
message.channel.send(`Arguments length: ${args.length}`);
You can find some comments in the following code to explain it better:
client.on('message', (message) => { if (!message.content.startsWith(prefix) || message.author.bot) return; // args is an array of all the words // including "args-info" const args = message.content // .slice() removes the prefix from the message content .slice(prefix.length) // .trim() removes spaces from both ends .trim() // .split() creates a new array by dividing the string // it splits the string everywhere it finds one or more spaces .split(/ +/); // the shift() method removes the first element // it removes args-info in this case const command = args.shift().toLowerCase(); if (command === 'args-info') { if (!args.length) { return message.channel.send( `You didn't provide any arguments, ${message.author}!`, ); } if (args[0] === 'foo') { return message.channel.send('bar'); } message.channel.send(`Command name: ${command}`); message.channel.send(`Arguments: ${args}`); message.channel.send(`Second argument: ${args[1]}`); // args.length is the number of words message.channel.send(`Arguments length: ${args.length}`); } });
And it seems to be working as expected: