So, there is an inside joke in my server where someone said 9 + 2 = 12, so I'm coding my bot so when someone says, "cal 9 + 2", the bot shows an embed which says calculator as title, and a answer of 12, which works well, but any other calculations wont work, here is the code:
const Math = require("mathjs");
module.exports = {
name: "cal",
description: "Calculates something",
async execute (Client, message, args, Discord){
const lol = '12'
const LOL = '9 + 2'
if(!args[0]) return message.channel.send("Please provide a question to solve");
let resp;
try{
resp = Math.evaluate(args.join(" "))
} catch (e) {
return message.channel.send("Please provide a **valid** question to answer")
}
if(args[0] = '9+2' || '9 + 2' || '9+ 2' || '9 +2'){
const embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setTitle("Calculator")
.addField("Question", `\`\`\`css\n${LOL}\`\`\``)
.addField("Answer", `\`\`\`css\n${lol}\`\`\``)
message.channel.send(embed);
}
else{
const embed = new Discord.MessageEmbed()
.setColor("RANDOM")
.setTitle("Calculator")
.addField("Question", `\`\`\`css\n${args.join(" ")}\`\`\``)
.addField("Answer", `\`\`\`css\n${resp}\`\`\``)
message.channel.send(embed);
}
}
}
the script without the if function, the math part works perfectly! but the joke aint there.
Your problem is with this line:
if(args[0] = '9+2' || '9 + 2' || '9+ 2' || '9 +2'){
First of all, =
is used only for assignments, such as const foo = 'bar'
. For comparison, use the triple equals, such as 'foo' === 'foo'
.
Second of all, x === y || z
does not actually do what you think it does. Statements on both sides of the logical OR operator (||
) will always be evaluated completely separately. The above will not mean, "x
equals either y
or z
" but instead, "x
equals y
, or z
is truthy"
// this means that something like this
// will always return truthy.
// if you separate the two statements,
// the second will always be truthy because
// a string, by itself, *is* truthy
if (true === false || 'hello') {
console.log('It passed');
};
Instead of x === y || z
, you'll have to take the more verbose option, which is:
x === y || x === z /* ... */
Or, you could use Array#includes()
, and put all of the valid strings in an array:
// x === y || x === z
[y, z].includes(x);
For your situation, however, I think the best option would be to use RegExp#test()
, with a regex such as: ^9\s*\+\s*2$
:
if (/^9\s*\+\s*2$/.test(message.content)) {
// ...
}