Skip to content
Advertisement

Multiple if/else conditions (discord bot)

I’m trying to create a simple discord bot, currently using nodeJS. I’m creating specific commands that only specific users can use and whenever someone who does not have permission to use such command can get a reply “You don’t have permission”. (I hope you get the idea. sorry for the bad wording).

This is my current code:

JavaScript

But what happens is, whenever someone uses a command, the yes or no condition will show 4 times, because there are 4 commands.

So if a user tried to use the !ban command the output would be

JavaScript

I’m pretty sure i messed up something in my if/else conditions but im not sure what it is.. Help is highly appreciated, i’m sorry for the bad wording of things..

Advertisement

Answer

As you have all the conditions separately they will execute one by one. You should use else if after the first clause to tie all the clauses. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if…else

You can also use a switch case statement for the use-case you explained. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

JavaScript

You can also simplify your if clause by checking the message.author.id first and then proceed to check which command is executed like the following.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement