首页 > 解决方案 > 检查 Discord 消息中的特定单词

问题描述

我试图弄清楚如何从整条消息中获取特定单词。就像使用亵渎过滤器一样。

    for (let x = 0; x < profanities.length; x++) {
    if (message.content.toUpperCase().includes(profanities[x].toUpperCase())) {
        message.channel.send('Oooooooh you said a bad word!');
        client.channels.get('484375912389935126').send(`Message was deleted due to use of a blocked word:\n\n"${message.content}"`);
        message.delete();
        return;
    }
}

现在这可行,除了如果在另一个词中说出一个词,它也会找到它,因为 .includes 就像如果我要阻止“bum”而有人说“bumble”,它也会删除“bumble”。这对于亵渎过滤器来说很好,但我想为会员做一个有趣的过滤器:

    const words = message.content.toLowerCase();
    if (words.includes('bum')) {
        setTimeout(function() {
          message.channel.send('Are we talking about <@memberID>?!');
        }, 1500);
    }

我使用“memberID”而不是真实 ID。但这会在“bumble”中找到“bum”,但我只希望它在消息中找到“bum”作为单独的词。就像“这个流浪汉很奇怪”之类的。

标签: javascriptdiscorddiscord.js

解决方案


就像其他答案所说,使用正则表达式:

if (/\bbum\b/i.test(message.content)) {
  setTimeout(function() {
    message.channel.send('Are we talking about <@memberID>?!');
  }, 1500)
}

\b检查单词边界并使其i不区分大小写。


推荐阅读