if(arrayContains(lastMessage, "hello") && arrayContains(lastMessage, "bot")) {
sendMessage(BOT_TEXT + RANDOM_REPLIES.helloGreeting());
}
else if(arrayContains(lastMessage, "goodbye") && arrayContains(lastMessage, "bot")) {
sendMessage(BOT_TEXT + RANDOM_REPLIES.goodbyeGreeting());
}
else if(arrayContains(lastMessage, "sudo") && arrayContains(lastMessage, "bot")) {
sendMessage(BOT_TEXT + RANDOM_REPLIES.sudoCommand());
}
What's the difference between these three lines? The keyword being searched for and the method being called.
Just two values? Seems like the perfect job for a map/object!
I'm assuming that you aren't going to only have these three commands for your chat bot; you're probably going to want to add more in the future.
Let's use a map/object (as I stated above) to store these commands and their keywords and functions:
var commands = {
"hello": function() { [hello greeting] },
"goodbye": function() { [goodbye greeting] },
"sudo": function() { [sudo command] }
};
Now, going back to the main function, all we have to do now is iterate through the map/object and check if the key value with the keyword that you were originally passing into arrayContains.
Here is what that looks like:
var lastMessage = getLastPostedMessage().toLowerCase().replace(/[^a-zA-Z\d\s:]/g, "").split(" ");
if(arrayContains(lastMessage, "bot")) {
for(var command in commands) {
if(arrayContains(lastMessage, command)) {
sendMessage(BOT_TEXT + commands[command]());
}
}
}
Note: I moved the arrayContains outside of the loop because you don't want to unnecessarily check if the message is a command if it isn't even addressing the bot. Credit to 3Doubloons3Doubloons.
I just realized this, but your RANDOM_REPLIES object could be used instead of creating that new commands map/object that I recommended. The only thing you'd have to change in that object would be the keys; you'd have to change those to the keywords.