lundi 7 juin 2021

JavaScript Else if Chatbot Function Problem

So, I am writing a Discord bot (with discord.js). This is what part of my code used to look like:

// 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);
 })
    }
});

The code will try to detect one of the questions that I have added, and if it doesn't, It will get monkedev fun/chat to take over. The main problem with this was that it can only respond to one question. To solve this (and make it so I don't need to write as much, to add more questions), I put most of what it repeats into a function called includesAllResponse. This is what the function looks like:

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

So, now the message code looks like this:

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!"])));
});

Now, I'm not sure where to put the code that receives the output from monkedev fun/chat, as I am no longer using if and else if. Is there a way to do this? Or do I need to go back to something similar to the old code?

Aucun commentaire:

Enregistrer un commentaire