I'm trying to delete a message on Discord from a user when it contains one or more words that are on a list.
const badWords = ["badword1", "badword2", "badword3"];
client.on("guildBanAdd", (guild, user) => {
const messages = guild.messages.cache.filter((m) => m.author.id === user.id);
for (const message of messages.values()) {
for (const badWord of badWords) {
if (message.content.match(badWord)) {
guild.members.ban(user);
break;
}
}
}
});
CodePudding user response:
It tends to be useful to use some library for this as above suggested solutions do not have built in tokenizer. This means that if someone was to write stuff such as veryverynaughty
it would not get catched because most likely veryverynaughty
is not on word list while [very, naughty]
are. Or alternative would be to run regex on that message.
But to your question, you delete messages using message.delete()
beware, that this does not work on messages older than 14 days. I cannot find the resource now, but I think there was a workaround to it.
import Profanity from 'profanity-js'
const isMessageTextProfane = (message) => {
const customBadwords = ["overthrow", "dictator"]
const config = {
language: "en-us"
}
const profanityInstance = new Profanity(message.content, config)
profanityInstance.addWords(...customBadwords);
return profanityInstance.isProfane(message.content)
}
client.on('guildBanAdd', (guild, user) => {
const messages = guild.messages.cache.filter(m => m.author.id === user.id);
for (const message of messages.values()) {
for (const badWord of badWords) {
if (isMessageTextProfane(message)) {
message.delete()
guild.members.ban(user);
break;
}
}
}
});
CodePudding user response:
const badWords = ["badword1", "badword2", "badword3"];
client.on("messageCreate", (message) => {
const words = message.split(" ");
for (const word of words) {
if (badWords.contains(word)) {
message.delete();
}
}
});
I would use the messageCreate Event because this keeps track of new messages. Second I would split up the message content in the words and then loop through and check if one of the words is in the bad word list. At the end I would delete the message.