首页 > 解决方案 > 正在寻找我的不和谐机器人的 8ball 命令的修复程序

问题描述

如果我只使用 ?8ball,该命令就可以正常工作。如果我将我的问题添加到命令中,我似乎无法弄清楚如何让机器人回复,例如?8ball 我应该呆在家里吗?或?8ball 是或否?

如果有用户的问题,我如何让我的机器人对 8ball 命令做出反应?我敢打赌这很简单,但不幸的是我对编码知之甚少。

感谢您的帮助。

这是代码。它适用于 ?8ball 但如果我添加问题则无效。

client.on('message', msg => {
  if (msg.content === '?8ball') {
     msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
}

标签: javascriptnode.jsdiscorddiscord.js

解决方案


问题是您的 if 语句正在明确寻找

?8球

如果您希望它响应任何包含“?8ball”的请求,您可以改用:

client.on('message', msg => {
    if( msg.content.includes('?8ball') ) {
        msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
    }
}

需要注意的是,这将无法确定他们所问的问题,只是它包含一个预定义的字符串(更糟糕的是它不检查字符串是在消息的前面还是在中间)。您必须进行额外的解析才能从消息中获取问题,例如String.split()

将 String.split() 和Array.shift()Array.join()一起使用以获取与查询分开的消息内容的示例:

client.on('message', msg => {
    var msgarray = msg.content.split(' ');

    //If the first part of the created array matches your message.
    if( msgarray[0] === '?8ball' ) {

        //Remove first part of array and put it together again.
        msgarray.shift();

        //Put the user query back together without the first part and spaces between the words
        var msgcontent = msgarray.join(' ');

        msg.reply(eightball[Math.floor(Math.random() * eightball.length)]);
    }
});

推荐阅读