Reputation:
I want the bot to respond to my message if it contains a specific word, at the end of a sentence or in a message alone, ignoring the punctuation, and will ignore the message if the word sticks another word. Example : the word is "yes"
"I said yes !" -> true
"Yes" -> true
"Eyes" -> false
For the moment, I made this :
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log(`Online`);
});
const responseObject = {
"yes": "ok !",
"no": "potato !"
};
client.on('message', message => {
var regex = /[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g;
var regexx = /[ \t]+$/g;
message.content = message.content.toLowerCase();
message.content = message.content.replace(regex, '')
message.content = message.content.replace(regexx, '')
if(responseObject[message.content]) {
message.channel.send(responseObject[message.content]);
}
});
And also, is there a way to optimize more this code ? Thanks in advance.
Upvotes: 0
Views: 356
Reputation: 35540
Here is a function to get the last word in a string:
function getLastWord(str) {
return (str.toLowerCase().match(/(\w+)\W*$/) || [])[1];
}
getLastWord("I said yes !"); // "yes"
getLastWord("Yes"); // "yes"
getLastWord("Eyes"); // "eyes"
Here's the regex explained:
(\w+)
- match any word
\W*
- match any non-alphanumeric characters
$
- the end of the string
Basically, requiring every character between the word and the end of the string to be non-alphanumeric forces the word to be the last word in the sentence. the (statement || [])
ensures that the function returns undefined
when there are no words instead of erroring out. The [1]
is to get the first capturing group, since match
returns an array.
Upvotes: 3