es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Aplicando funciones asíncronas a los mensajes del chatbot de Facebook en un orden específico.

Estoy haciendo un chatbot para Facebook y tengo un problema con el orden de envío de mensajes.

Envío en el chat:

Ninguno
-Hola

El bot responde en la consola:

-¡Hola!

-¿En qué puedo ayudarte?

Pero en el chat responde así:

Ninguno
-¿En qué puedo ayudarte?

-¡Hola!

He intentado aplicar async y await, pero no funciona.

let postWebhook = (req, res) => {
    // Parse the request body from the POST
    let body = req.body;

    // Check the webhook event is from a Page subscription
    if (body.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        body.entry.forEach(function (entry) {

            // Gets the body of the webhook event
            let webhook_event = entry.messaging[0];

            // Get the sender PSID
            let sender_psid = webhook_event.sender.id;

            // Check if the event is a message or postback and
            // pass the event to the appropriate handler function
            if (webhook_event.message) {
                handleMessage(sender_psid, webhook_event.message);
            }

        });

        // Return a '200 OK' response to all events
        res.status(200).send('EVENT_RECEIVED');

    }
};

let handleMessage = async (sender_psid, received_message) => {
    let response;
    if (received_message.text) {

        addUrl(`url/facebook?mensage=${received_message.text}&usuario=${user}&session=${sender_psid}&origem=${chanel}`)
            .then(res => res.json())
            .then(async json => {
                for (var i = 0; i < json.length; i++) {

                    console.log(json[i].text || json[i].title)
                    response = {json[i].text || json[i] tittle}
                    await callSendAPI(sender_psid, response) //function to verify user and send message
                }
            })
        await callSendAPI(sender_psid, response);
    }
};

¿Cómo puedo asegurar el orden correcto?

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para asegurar el orden correcto de los mensajes enviados por el chatbot, puedes modificar la función handleMessage para construir un array de respuestas y luego utilizar Promise.all() para enviarlos en el orden correcto. Aquí tienes un ejemplo de implementación:

    let handleMessage = async (sender_psid, received_message) => {
      let responses = [];
      if (received_message.text) {
        addUrl(`url/facebook?mensage=${received_message.text}&usuario=${user}&session=${sender_psid}&origem=${chanel}`)
          .then(res => res.json())
          .then(json => {
            for (var i = 0; i < json.length; i++) {
              console.log(json[i].text || json[i].title);
              responses.push({ text: json[i].text || json[i].title });
            }
            return Promise.all(responses.map(response =>
              callSendAPI(sender_psid, response)
            ));
          })
          .catch(error => {
            console.error(error);
          });
      }
    };
    

    En esta implementación, utilizamos un array llamado responses para almacenar cada mensaje que genera el chatbot. Luego, utilizamos Promise.all() para llamar a callSendAPI() en cada respuesta en el orden correcto. Esto asegura que los mensajes se envíen al usuario en el orden en que fueron generados por el chatbot.

Comments are closed.