Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Alternating messages on chatbot creation

I’m doing a chatbot with Node JS for Instagram using this library available on github(https://github.com/Androz2091/insta.js.git). I’m currently testing the feature through the online replit platform, I’m getting the message from the instagram user and sending it through a url to the reply service

I have a difficulty that would be the bot’s answer. It must follow a message structure, however, this structure is often toggled.

I send in the chat:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

-Hi

The bot responds in the console:

-Hello!

-How can I help you?

but in the chat he responds like this:

-How can I help you?

-Hello!

Below is the code I used to go through the arrays I receive and send the messages

I tried using a switch case to try to solve the problem, but it still remains the same.

node-fetch(`instagram?mensage=${message}&user=${message.author.fullName}&session=${client.user}`)
  .then(res => res.json())
  .then(json => {
    for (var i = 0; i < json.length; i++) {


      message.chat.sendMessage(json[i].text || json[i].title);
      console.log(json[i].text || json[i].title)


      for (var key in json[i]) {

      /* switch case
     switch(json[i][key]){
       case json[i].text:
        message.chat.sendMessage(json[i].text);
        break;
       case json[i].title:
        message.chat.sendMessage(json[i].title);
        break;
      }*/

        if (json[i][key].length == 3) {
          for (var j = 0; j < json[i][key].length; j++) {

            message.chat.sendMessage(json[i][key][j].label);
            console.log(json[i][key][j].label);

          }
        }

Does anyone know why this happens?
I already thank you.

>Solution :

sendMessage returns Promise, but you are using it as a normal function.

You can read about javascript promises here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises.

In your code, it should look something like this

...
.then(async json => {
    for (var i = 0; i < json.length; i++) {
        await message.chat.sendMessage(json[i].text || json[i].title);
        ...
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading