简体   繁体   中英

Applying asynchronous functions to facebook chatbot messages in specific order

I'm doing a chatbot for facebook and I have a problem with the order of sending messages

I send in the chat:

-Hi

The bot responds in the console:

-Hello!

-How can I help you?

but in the chat responds like this:

-How can I help you?

-Hello!

I tried to apply async and await, but it didn't work.

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

How can I ensure the correct order?

Well you can simplify this way:

const callSendAPII = (sender_psid, response) => {
return new Promise((resolve, reject) => {
    let request_body = {
        "recipient": {
            "id": sender_psid
        },
        "message": response
    }
    request({
        uri: 'https://graph.facebook.com/v12.0/me/messages',
        qs: {"access_token": MY_IG_PAGE_TOKEN},
        method: 'POST',
        json: request_body,
    }, (error, response, body) => {
        if (error) {
            reject(error);
        } else {
            resolve(response);
        }
    });
})

now just apply await in the calling function:

await callSendAPII(sender_psid, response)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM