多次执行 AWS Lambda 函数(无服务器)

AWS Lambda Function Executing Multiple Times (Serverless)

我正在使用 AWS Lambda 和无服务器框架创建一个 Facebook Messenger 机器人。现在我只希望它重复发送回用户的任何内容。这是代码:

'use strict';
var https = require('https');
const axios = require('axios');


var VERIFY_TOKEN = "VERIFY";
var PAGE_ACCESS_TOKEN = "TOKEN";

module.exports.hello = (event, context, callback) => {
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            message: 'Go Serverless v1.0! Your function executed successfully!',
            input: event,
        }),
    };

    callback(null, response);

    // Use this code if you don't use the http event with the LAMBDA-PROXY integration
    // callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

// Receive user messages
module.exports.botReply = (event, context, callback) => {

    var data = JSON.parse(event.body);
    console.log("BOT REPLY")

    // 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) {
            var pageID = entry.id;
            var timeOfEvent = entry.time;
            // Iterate over each messaging event
            entry.messaging.forEach(function(msg) {
                if (msg.message) {
                    console.log("received message");
                    const payload = {
                    recipient: {
                      id: msg.sender.id
                    },
                    message: {
                      text: "test"
                    }
                  };
                    const url = "https://graph.facebook.com/v2.6/me/messages?access_token=" + PAGE_ACCESS_TOKEN;
                    axios.post(url, payload).then((response) => callback(null, response));

                } else {
                    console.log("Webhook received unknown event: ", event);
                    var response = {
                        'body': "ok",
                        'statusCode': 200
                    };

                    callback(null, response);
                }
            });
        });
    }

}

所以机器人确实成功回显了消息,但在我的日志中我可以看到它被执行了多次。有时由于某种原因,消息在 JSON 中没有 "message" 键,因此多次执行会有不同的结果。我相信这与我将消息发回给用户有关,因为当我注释掉 axios.post 时,问题就停止了。知道为什么会这样吗?

@Asanka 在评论中弄明白了。基本上,facebook 正在发送多个我没有在我的代码中考虑的事件。 "message delivered" 和 "message read" 之类的东西也是我不知道的事件。我只需要在开发者控制台中取消订阅即可。