Reputation: 18
I am trying to make my Bot I am currently developing able to respond to a message, Which i really did it.
However I want the bot to respond to one of the elements/strings in an Array, so i don't have to repeatedly write (message.includes('example')) || (message.includes('example2'))
.
I tried doing this with an if statement as that is the only way i know how to. :
client.on('message', message =>{
if (message.author.bot) return;
const fixgreet = message.content.slice();
const greetings = fixgreet.toLowerCase();
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
if (greetings.includes(gnraw)) {
client.responds.get('gn').execute(message, fixgreet);
}
Which doesn't return an error at all, but also won't respond.
gnraw
is the Array which contains the elements, and greetings
is the message content sent by the user, the if statement should be true when the message content contains one of the elements in gnraw
and it should send a response.
gn.txt is a TEXT file with strings, which i created it into an array (gnraw
) by using :
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
Here is an example of what would they look.
the TEXT file could be:
gm
good morning
good day
Then gnraw
will be ['gm', 'good morning', 'good day']
which is formatted from the TEXT file.
As an example of what i would like to happen.
User A : "Good morning." *sends a message, which then identified as greetings
User B : "GM" *identified as greetings
aswell.
if one of the elements in gnraw
is included in greetings
then
the Bot should respond with 'Good morning'.
Please tell me how do i make the bot respond to a message that has one of the elements in the array. I am fairly new to JavaScript.
Upvotes: 0
Views: 315
Reputation: 1
The code I suggested in the comments would work (not sure what you're saying doesn't work about it) - but it has a flaw
If greetings
were something "I have a lot of phlegm" - it would match with gm
so lets try another way
function fn(keywords, target) {
const res = keywords.map(s => new RegExp(`\\b${s}\\b`));
return res.some(re => target.match(re));
}
client.on('message', message =>{
if (message.author.bot) return;
const fixgreet = message.content.slice();
const greetings = fixgreet.toLowerCase();
const gnvars = fs.readFileSync('./commands/urls/gn.txt').toString('utf-8');
const gnraw = gnvars.split('\n');
if (fn(gnraw, greetings)) {
client.responds.get('gn').execute(message, fixgreet);
}
so .. fn
returns a boolean, that is true if one of the gnraw
values is found in the greetings
string
Upvotes: 1