Facebook Messenger Bot ждет ответа после многих запросов и возобновления

Когда я пишу алфавит на своем боте в фейсбуке, мой бот ждет ответа.

Я пишу например: я пишу "а"... бот отвечает "а", я пишу "б"... бот отвечает "б" и т.д...

Но, например, на букву «l» бот ждет ответа и возобновляет работу примерно через несколько минут:

введите здесь описание изображения

примерно через несколько минут бот отвечает:

введите здесь описание изображения

Я использую официальный код с https://developers.facebook.com/docs/messenger-platform/guides/quick-start/

app.js

app.get('/webhook', function(req, res) {
    if (req.query['hub.mode'] === 'subscribe' &&
        req.query['hub.verify_token'] === CONFIGURATION.webhook_token) {
        console.log("Validating webhook");
        res.status(200).send(req.query['hub.challenge']);
    } else {
        console.error("Failed validation. Make sure the validation tokens match.");
        res.sendStatus(403);
    }
});

app.post('/webhook', function (req, res) {
    let data = req.body;

    // Make sure this is a page subscription
    if (data.object === 'page') {

        // Iterate over each entry - there may be multiple if batched
        data.entry.forEach(function(entry) {
            let pageID = entry.id;
            let timeOfEvent = entry.time;

            // Iterate over each messaging event
            entry.messaging.forEach(function(event) {
                if (event.message) {
                    receivedMessage(event);
                } else {
                    console.log("Webhook received unknown event: ", event);
                }
            });
        });

        // Assume all went well.
        //
        // You must send back a 200, within 20 seconds, to let us know
        // you've successfully received the callback. Otherwise, the request
        // will time out and we will keep trying to resend.
        res.sendStatus(200);
    }
});

function receivedMessage(event) {
    let senderID = event.sender.id;
    let recipientID = event.recipient.id;
    let timeOfMessage = event.timestamp;
    let message = event.message;

    console.log("Received message for user %d and page %d at %d with message:",
        senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    let messageId = message.mid;

    let messageText = message.text;
    let messageAttachments = message.attachments;

    if (messageText) {

        // If we receive a text message, check to see if it matches a keyword
        // and send back the example. Otherwise, just echo the text we received.
        switch (messageText) {
            case 'generic':
                sendGenericMessage(senderID);
                break;

            default:
                sendTextMessage(senderID, messageText);
        }
    } else if (messageAttachments) {
        sendTextMessage(senderID, "Message with attachment received");
    }
}

function sendGenericMessage(recipientId) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            attachment: {
                type: "template",
                payload: {
                    template_type: "generic",
                    elements: [{
                        title: "rift",
                        subtitle: "Next-generation virtual reality",
                        item_url: "https://www.oculus.com/en-us/rift/",
                        image_url: "http://messengerdemo.parseapp.com/img/rift.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/rift/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for first bubble",
                        }],
                    }, {
                        title: "touch",
                        subtitle: "Your Hands, Now in VR",
                        item_url: "https://www.oculus.com/en-us/touch/",
                        image_url: "http://messengerdemo.parseapp.com/img/touch.png",
                        buttons: [{
                            type: "web_url",
                            url: "https://www.oculus.com/en-us/touch/",
                            title: "Open Web URL"
                        }, {
                            type: "postback",
                            title: "Call Postback",
                            payload: "Payload for second bubble",
                        }]
                    }]
                }
            }
        }
    };

    callSendAPI(messageData);
}

function sendTextMessage(recipientId, messageText) {
    let messageData = {
        recipient: {
            id: recipientId
        },
        message: {
            text: messageText
        }
    };

    callSendAPI(messageData);
}

function callSendAPI(messageData) {
    request({
        uri: 'https://graph.facebook.com/v2.6/me/messages',
        qs: { access_token: CONFIGURATION.access_token },
        method: 'POST',
        json: messageData

    }, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            let recipientId = body.recipient_id;
            let messageId = body.message_id;

            console.log("Successfully sent generic message with id %s to recipient %s",
                messageId, recipientId);
        } else {
            console.error("Unable to send message.");
            console.error(response);
            console.error(error);
        }
    });
}

let server = app.listen(port, function () {
    InterfaceLogin.process();

    console.log('App listening on port 8080!');
});

server.timeout = 1000;

В моей консоли во время последнего ответа я вижу:

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxxxx

бот не отвечает, и через несколько минут я вижу:

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xxxx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery: 
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }

боты отвечают

Мой последний ответ:

Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"k"}
Successfully sent generic message with id mid.$xxx to recipient xxx
Received message for user xxx and page xxx at xxx with message:
{"mid":"mid.$xxx","seq":xx,"text":"l"}
Successfully sent generic message with id mid.$xxx to recipient xxxx
Webhook received unknown event:  { sender: { id: 'xxx' },
  recipient: { id: 'xxx' },
  timestamp: xxx,
  delivery: 
   { mids: [ 'mid.$xxx' ],
     watermark: xxx,
     seq: 0 } }

person Jérémie Chazelle    schedule 12.09.2017    source источник
comment
Проблема в том, что ваш бот ожидает ответа, или в том, что есть задержка в получении события веб-перехватчика, из-за которой ваш бот отвечает?   -  person amuramoto    schedule 12.09.2017
comment
@amuramoto бот отвечает, но с задержкой после запроса x   -  person Jérémie Chazelle    schedule 12.09.2017
comment
Значит, бот отправляет сообщение, но требуется время, чтобы оно появилось в беседе?   -  person amuramoto    schedule 12.09.2017
comment
@amuramoto Я обновил свой пост, я не знаю, сразу ли бот возвращает сообщение, но нужно время, чтобы в беседе был ответ   -  person Jérémie Chazelle    schedule 12.09.2017
comment
@amuramoto Я обновил свой пост с помощью console.log   -  person Jérémie Chazelle    schedule 12.09.2017
comment
Хорошо, тогда это проблема на стороне API. Я предлагаю вам открыть отчет об ошибке здесь и указать идентификаторы страницы и приложения: developers.facebook.com/ ошибки (Выберите Теги -> Платформа Messenger)   -  person amuramoto    schedule 12.09.2017
comment
@amuramoto Итак, мой бот больше не публикуется, может быть, это нормально в режиме разработки? В рабочем режиме нет этой задержки, этой ошибки?   -  person Jérémie Chazelle    schedule 12.09.2017
comment
AFAIK не должно быть разницы в задержке   -  person amuramoto    schedule 12.09.2017


Ответы (1)


Платформа бот-мессенджера имеет ограничение скорости, если вы превысите его, запросы будут стоять в очереди и выполняться позже.

https://developers.facebook.com/docs/messenger-platform/reference/send-api/

person nacholibre    schedule 14.11.2017