【问题标题】:Discord.js check for multiple words in a one messageDiscord.js 在一条消息中检查多个单词
【发布时间】:2021-10-18 22:22:19
【问题描述】:

我正试图让我的机器人用一个词来回答多种消息变体:

const bomba = new Discord.Client();
    
const a = "bomba" || "bomb" || "bob";
const b = "hey" || "sup" || "hello" || "hi";

bomba.on("message", message => {
    if (message.author == bomba.user) return;
    if (message.content.toLowerCase() === a + b) {
        bomba.channels.cache.get(`${message.channel.id}`).send("Hi!");
    };
});

我该如何进行这项工作?

【问题讨论】:

    标签: javascript discord.js


    【解决方案1】:

    您可以使用正则表达式和.match() 函数来对照几个单词检查消息内容。看看下面的代码,试试看:

    const bomba = new Discord.Client();
        
    const clientNames = ["bomba", "bomb", "bob"].join('|');
    const greetings = ["hey", "sup", "hello", "hi"].join('|');
    
    const regex = new RegExp(`^(${clientNames})\\s(${greetings})$`, 'gi');
    
    bomba.on("message", message => {
        if (message.author == bomba.user) return;
        if (message.content.match(regex)) {
            bomba.channels.cache.get(`${message.channel.id}`).send("Hi!");
        }
    });
    

    有关正则表达式的更多信息,请查看this stackoverflow question/answer

    【讨论】:

    • 它的工作原理和我想要的一样,但是有一个问题:imgur.com/qCf5OAY 看到任何其他符号或单词之间或必要的单词时它不会回复
    【解决方案2】:

    你可以使用Array.includes():

    if (["bomba", "bomb", "bob"].includes(message.content.toLowerCase())) {
        message.channel.send("Hi!");
    };
    

    请注意,最好通过用户的User.id 属性来比较用户,而不是像您在代码中那样检查他们是否引用同一个实例。

    if (message.author.id == bomba.user.id) return;
    

    来自 MDN docs 关于 == 运算符:

    如果操作数都是对象,则仅当两个操作数都引用同一个对象时才返回 true。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-28
      • 2018-07-21
      • 2021-09-26
      • 2021-04-18
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 2021-06-09
      相关资源
      最近更新 更多