Reputation: 11
I'm trying to have my Discord bot handle commands with spaces in the argument. My args
variable is defined in my index.js
file:
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
My command file (perk.js
) looks like this:
const Discord = require('discord.js');
const PerkData = require('./perk.json');
module.exports = {
name: 'perk',
args: true,
execute(message, args) {
for (let i = 0; i < PerkData.perks.length; i++) {
if (PerkData.perks[i].id.toLowerCase() === args[0].toLowerCase()) {
const perkEmbed = new Discord.MessageEmbed()
.setColor('#000000')
.setTitle('__**' + PerkData.perks[i].name + '**__ ')
.setURL(PerkData.perks[i].url)
.setThumbnail(PerkData.perks[i].gif)
.setDescription('A teachable unique [' + PerkData.perks[i].character + '](' + PerkData.perks[i].characterURL + ') Perk <:Perk:833657215743295499>. It can be unlocked for all other characters from Level ' + PerkData.perks[i].lvl + ' onwards:')
.addField('__Description__', PerkData.perks[i].description, false)
message.channel.send(perkEmbed)
}
}
}
}
As of this moment, I have an "id" field in the JSON file that has hyphens -
instead of spaces, which then the perk.js
file reads from it and matches it up with the description.
Example: .perk ace-in-the-hole
How do I make it so that I can use spaces in the argument instead of having to use hyphens?
Do I need to change how args
is defined in index.js
? Or can it be done within the command file, perk.js
?
Long story short, I have: .perk ace-in-the-hole
working.
But I want to be able to do this: .perk ace in the hole
(Sorry if this was poorly written, I'm not an experienced coder...)
Upvotes: 1
Views: 339
Reputation: 86
You can simply join the array of arguments with a space.
execute(message, args) {
// Join the args array
let perkArg = args.join(' ')
for (let i = 0; i < PerkData.perks.length; i++) {
if (PerkData.perks[i].id.toLowerCase() === perkArg.toLowerCase()) {
// ...
}
}
}
Assuming all the perk IDs are unique and you only want to send one message, you could also search through the whole PerkData.perks
array in a single line without a for loop to find a single item.
// Join the args array
let perkArg = args.join(' ')
let perk = PerkData.perks.find(perk => perk.id === perkArg.toLowerCase())
if(perk !== undefined) {
// perk was found
} else {
// perk was not found
}
Upvotes: 1