Search code examples
javascriptdiscorddiscord.jsargs

How do I differentiate arguments?


So I want to have my code detect the different sections. The issue is it only thinks there is 1 argument. I tried some if statements and I console logged it and it came out as 1. the code currently is:

module.exports = {
    name: 'report',
    description: "report a naughty person",
    async execute(message, args, Discord, client){ 
    const reason = args.splice(1)
    console.log (args)

if (args.length = 1){ 

    let embed = new Discord.MessageEmbed()
        .setColor('#1ed700')
        .setTitle('Report \n')
        .setDescription(`Person who reported ${message.author} \n`
        + `Channel reported in: ${message.channel}\n`
        + `Person reported: ${args[0]} \n` //The 1st argument
        + `Reason reported: ${reason.join(' ')}`) // The 2nd argument
         

    let messageEmbed = await message.channel.send(embed);
    message.channel.send(`<@&${process.env.DUMMY_ROLE}>`)
    
} else
    message.channel.send('Code is not written properly')
    

}};

How would I be able to change it so that it comes out as 2 different arguments (the first 1 being the mention and the second being the reason). And how would I be able to check if there are these two arguments?


Solution

  • First of all you use an assignment operator to check if args.length is 1. You want a comparison so what you want is the following:

    if (args.length === 1) {
    // Do something
    }
    

    Try setting your args to the following code:

    const args = message.content.split(' ').slice(1); // Only use the last port slice() if you have a prefix like "-" or "+"
    

    I added 2 checks to show you how you can check if a user has been mentioned and one other to check if the user has given a reason. To check if there is a mention you can simply use message.mentions.users.first();. The only thing you forgot to add to the reason was join(' ') otherwise the user can just write one word as reason (I guess that's not what you wanted).

    module.exports = {
        name: 'report',
        description: "report a naughty person",
        async execute(message, args, Discord, client){ 
        const reason = args.splice(1).join(' ')
        const user = message.mentions.users.first();
    
       if (!user) return console.log('No user mentioned');
       if (!reason) return console.log('No reason given') // Checks if there is a reason given
       
       if (user && reason) {
      // Do something
    console.log('User mentioned and reason given')
    }
    }};