I made myself a bot that would simply get an argument from Discord and if the argument had matched it would send the message "Successfully Redeemed." That part works BUT what doesnt work is the exact match. I Want it to exactly match in order for that message to come up but suppose a key is 123456
it would also accept an argument as 12
or 123
. I don't want that to happen, it should EXACTLY match. Here is my current code:
if (command === '$redeemkey') {
const fs = require('fs')
fs.readFile('notredeemed.txt', function (err, data) {
if (err) throw err;
if(data.includes(`${args[0]}`)){
console.log("true")
return message.reply({
embeds: [
new MessageEmbed()
.setColor('GREEN')
.setDescription('Redeemed Successfully')
]
})
}
Here is what my notredeemed.txt
looks like:
12345678
1234567
123456
12345
CodePudding user response:
You can split the codes by line break and then test for their equality. The some
method is used, to return early if a match is found.
fs.readFile('notredeemed.txt', function (err, data) {
if (err) throw err;
let value = args[0];
let codes = data.toString().split(/\r?\n/);
codes.some((code) => {
if ( result === value ) return true;
});
});
CodePudding user response:
.contains()
would check for the argument in the entire file content no matter which position it is in.
Solution #1
You could instead use RegExp
in order to .match()
the exact value based on the line content.
^
- Start of string$
- End of stringm
- Multi-line
Replace:
data.includes(`${args[0]}`)
With:
data.toString().match(new RegExp(`^${args[0]}$`, "m"))
Solution #2
You could .split()
the line breaks in the data and then check if the created array contains the argument, similarly to how you tried checking for the value at first.
Replace:
data.includes(`${args[0]}`)
With:
data.toString().split("\n").includes(`${args[0]}`);