首页 > 解决方案 > JavaScript Else if Chatbot 功能问题

问题描述

所以,我正在编写一个 Discord 机器人(使用 discord.js)。这是我的代码的一部分曾经的样子:

// When bot receives a message:
client.on('message', msg => {
  // Where do you live?
  if (IfIncludesAll(msg.content.toLocaleLowerCase(), ["where", ["you"], ["live"]])) {
    var where_i_live = ["I live in (Town Name).", "I live in (Building), in (Town Name)."]
    msg.channel.send(where_i_live[Math.floor(Math.random() * where_i_live.length)])
  }
  // What is your name?
  else if (IfIncludesAll(msg.content.toLocaleLowerCase(), ["what", ["your"], ["name"]])) {
    var my_name = ["I'm (nickname)!", "I'm (nickname).", "My name is (Full name), but you can call me (nickname)!"]
    msg.channel.send(my_name[Math.floor(Math.random() * my_name.length)])
  }
  // Get monkedev chat to take over:
  else {
    if (msg.author.bot) {
        return;
    }
      fetch(`https://api.monkedev.com/fun/chat?msg=${msg.content}&uid=${msg.author.id}`)
  .then(response => response.json())
  .then(data => {
    msg.channel.send(data.response);
 })
    }
});

该代码将尝试检测我添加的问题之一,如果没有,它将让monkedev fun/chat接管。这样做的主要问题是它只能回答一个问题。为了解决这个问题(并使它不需要写太多,添加更多问题),我将它重复的大部分内容放入一个名为includesAllResponse的函数中。这是函数的样子:

function includesAllResponse(message, question, responses) {
  if (IfIncludesAll(message.toLocaleLowerCase(), question)) {
    return (responses[Math.floor(Math.random() * responses.length)])
  }
}

因此,现在消息代码如下所示:

client.on('message', msg => {
  // Where do you live?
  msg.channel.send((includesAllResponse(msg.content.toLocaleLowerCase(), ["where", "you", "live"], ["Greendale.", "I live in Greendale", "Forge Cottage, in Greendale."])));
  // What is your name?
  msg.channel.send((includesAllResponse(msg.content.toLocaleLowerCase(), ["what", "your", "name"], ["I'm Postman Pat!", "I'm Pat.", "My name is Pat Clifton, but you can call me Postman Pat!"])));
});

现在,我不确定将接收来自monkeyev fun/chat输出的代码放在哪里,因为我不再使用if 和else if。有没有办法做到这一点?还是我需要回到类似于旧代码的东西?

标签: javascriptfunctionif-statement

解决方案


推荐阅读