简体   繁体   中英

Making a bot with discord.js, how to make my bot detect a certain phrase?

I'm making a bot that will ping me if a certain phrase gets said in my discord. Currently I am using

if(message.content.toLowerCase() === 'word')

How can I make it so it will detect "word" in any sentence? New to coding so I just followed a guide and after a few hours I couldn't figure it out. I only got it to ping me if only "word" was said and nothing else.

A simplistic solution is:

 function contains(content, word) { return (content.toLowerCase().indexOf('word') >= 0); } console.log(contains("This is the word!")); //true console.log(contains("This is WordPress")); //true console.log(contains("Something")); //false

As you can see, the second example is incorrect, because WordPress semantically differs from word . So, if it's not enough to find the word, but we want to isolate it as well, then we can do something like this:

 function contains(content, word) { let pattern = new RegExp("[^az]" + word + "[^az]"); return (pattern.test(content.toLowerCase())); } console.log(contains("This is the word!", "word")); //true console.log(contains("This is WordPress", "word")); //true console.log(contains("Something", "word")); //false

In this second example, I prepend and append [^az] , which means "not a letter"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM