1

我正在使用AWS Lambda和無服務器框架創建一個facebook messenger bot。現在我只想讓它重複發送給用戶的任何信息。下面是代碼:AWS Lambda函數執行多次(無服務器)

'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中沒有「消息」鍵,所以多次執行會有不同的結果。我相信這跟我把信息發回給用戶有關,因爲當我註釋掉axios.post時,問題就會停止。任何想法爲什麼發生這種情況?

+0

一般情況下,如果Lambda函數拋出異常,Lambda會在一定的時間間隔內重試函數,當重試發生時,您確定函數沒有失敗嗎? – kosa

+0

嗯,我沒有看到日誌中的錯誤... – Brandon

+0

當您訂閱facebook messenger webhooks時,您可以訂閱幾個事件。如果您訂閱了郵件傳遞事件,您的Lambda可以在成功傳遞後觸發。你可以從https://developers.facebook.com/docs/messenger-platform/webhook-reference#setup – Asanka

回答

2

@Asanka在評論中發現了它。基本上,Facebook發送了多個事件,我沒有在我的代碼中進行說明。 「消息傳遞」和「消息閱讀」等東西也是我不知道的事件。我只需在開發者控制檯中取消訂閱。