我在我的机器人中运行以下代码,作为删除脏话的命令。然而,它似乎让机器人删除了无论如何发送的任何消息!帮助!
bot.on('message', message => {
if (message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4') {
message.delete(1);
message.channel.send("That word's not appropriate!");
}
});
最佳答案
问题是message.content.includes == 'bannedWord1' ||'bannedWord2' || 'bannedWord3' || 'bannedWord4'
实际上意味着 (message.content.includes == 'bannedWord1') ||'bannedWord2' || 'bannedWord3' || 'bannedWord4'
。非空字符串是真的,所以这始终是真的。
此外,我假设 message.content
是一个字符串。因此,您需要处理诸如“假设”之类的内容,其中包含 ass
但并不是一个坏词。
演示解决方案:
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
var contents = [
'This is a test.',
'bannedWord1 tester.',
'bannedWord2!',
'OkaywordthatcontainsbannedWord1.'
];
var allowed = contents.filter(content => {
var words = content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
return !words.find(word => {
return badWords.includes(word);
});
});
console.log(allowed);
在您的情况下使用:
var badWords = [
'bannedWord1',
'bannedWord2',
'bannedWord3',
'bannedWord4'
];
bot.on('message', message => {
var words = message.content.toLowerCase().trim().match(/\w+|\s+|[^\s\w]+/g);
var containsBadWord = words.some(word => {
return badWords.includes(word);
});
if (containsBadWord) {
message.delete(1);
message.channel.send("That word's not appropriate!");
}
});
来自 regex101.com 的正则表达式解释
- 第一种选择
\w+
\w+
匹配任何单词字符(等于[a-zA-Z0-9_]
)+
量词 - 一次和无限次之间的匹配,尽可能多的次数,根据需要回馈(贪婪)
- 第二个替代方案
\S+
\S+
匹配任何空白字符(等于[\r\n\t\f\v ]
)+
量词 - 一次和无限次之间的匹配,尽可能多的次数,根据需要回馈(贪婪)
- 第三种选择
[^\s\w]+
- 匹配下面列表中不存在的单个字符
[^\s\w]+
+
量词 — 匹配一次和无限次,尽可能多的次数,根据需要返回(贪婪)\s 匹配任何空白字符(等于[\r\n\t\f\v]
)
- 匹配下面列表中不存在的单个字符
关于javascript - Discord.js 机器人正在删除所有消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47315999/