Home > OS >  uanble to get certain words form text file
uanble to get certain words form text file

Time:10-01

Hi I'm wanting to get certain words from a text file rather than all the words in the file. Basically this text file has certain words I want to delete if they are used in a message.

Then I want to send these words in a new message:

How this is not working for me it's just sending all the words ${word} in the text file.

Heres what I'm working with

const badwords = fs.readFileSync("./badwords.txt","utf8").toLowerCase().split("\r\n");
const blocked = badwords.filter(word => message.content.toLowerCase().includes(word)); 

//filter through badwords


blocked.filter(word => {
    if(message.content.includes(word)){
        message.delete()
        log_channel.send(`Message deleted because it contained the words ${word}`) 
    }
})

Return values from badword.txt test1 and test2

CodePudding user response:

Your mistake comes from how you detect if badwords were found in message.content. blocked is already an array of found badwords (hence why they all return when you re-filter them with the same condition) , all you need to do is check if it has a length greater than 0. To send a list of the found badwords take the array and join it into a string

const badwords = fs.readFileSync("./badwords.txt","utf8").toLowerCase().split("\r\n");
const blocked = badwords.filter(word => message.content.toLowerCase().includes(word)); 

if (blocked.length) {
   message.delete()
   log_channel.send(`Message deleted because it contained the words ${blocked.join(' ')}`)
}

CodePudding user response:

Assuming you have next badwords.txt structure

...
bad1
bad2
bad3
...

You need to split them by new line

const badwords = fs.readFileSync("./badwords.txt","utf8").toLowerCase().split("\n");

Then you need to find all words in message and convert to array

const message = "String with-one bad1 word, bad2, bad1".match(/\b[\w\-] \b/gi);

And then just filter message and return new message

const filteredMessage = message.filter(word => {
  if(badwords.includes(word)) {
    log_channel.send(`Message deleted because it contained the words ${word}`)
    return false;
  }
  return true;
}).join(' ');
  • Related