在Facebook Messenger Bots中在单个回发上发送多条回复消息

时间:2017-11-25 06:17:45

标签: json node.js facebook facebook-messenger-bot facebook-chatbot

我想在Messenger上针对单个用户触发的回发发送多个回复。我一直在关注Messenger的developer documentation,但却无法真正找到如何做到这一点。

我的代码结构与他们在网站上提供的教程非常相似,我有一个' handlePostback '函数,用于标识收到的回发并将其与一组预定义的有效负载进行比较'响应'JSON对象。此响应被赋予“ callSendAPI ”,它将此JSON对象置于将消息发送回Messenger API的基本格式。

function handlePostback(sender_psid,receivedPostback)
{ if(payload== 'defined_payload') {
  response = {
  text: 'Some text'
  };
callSendAPI(sender_psid,response);
}

function callSendAPI(sender_psid,response) {
let body = {
recipient: {
id= sender_psid
},
message: response
};
// Followed by code for POST request to the webhook
}

这是基本结构,现在我想发送多条消息作为对一个回发的回复。我做了一些挖掘,我发现解决方案可能是创建一个message []数组。但是我该怎么做?因为我的'响应'是通过该函数生成的,并且消息结构应该看起来像这样(我认为):

let body = {
 recipient: {
 id=sender_psid
 },
 messages: [ {
  response1
  },
  {
  response2
  }
 ]
};

我希望我能解释一下我的问题,如果我能提供更多细节,请告诉我!

4 个答案:

答案 0 :(得分:5)

好问题。如果您不熟悉Node.js,那么这样做的方式并不太明显,而且在Facebook的Send API文档中没有很好地记录。

首先,您使用数组发送多条消息的方法可能无法正常工作。 Facebook有一个解决方案,可以通过一个请求发送多达100个API调用,但在我看来,在您的情况下不需要这样做。如果您想了解更多信息,请查看Batched Request Documentation,您会发现实施情况与您的不同。

一个可行的解决方案是多次调用callSendAPI函数。 但是这个解决方案有一个主要缺点:您将无法控制发送的消息的实际顺序。例如,如果您要发送两条单独的邮件,则无法保证哪些邮件会先发送给用户

要解决此问题,您需要将callSendAPI函数链接起来,以确保只有在第一条消息发送后才会发生下一个callSendAPI调用。您可以通过使用回调或承诺在NodeJS中执行此操作。如果您不熟悉其中任何一个,则可以阅读this进行回调,this进行承诺。

您需要修改callSendAPI功能,尤其是将POST请求发送到Facebook的部分。我将使用 promises 和模块node-fetch来解决您的问题。

const fetch = require('node-fetch');

function handlePostback(sender_psid,receivedPostback){ 
  if (payload == 'defined_payload') {
    response = {
      text: 'Some text'
    };
    response2 = //... Another response
    response3 = //... Another response
  callSendAPI(sender_psid,response).then(() => {
    return callSendAPI(sender_psid, response2).then(() => {
      return callSendAPI(sender_psid, response3); // You can add as many calls as you want
      });
   });
  }
}

function callSendAPI(sender_psid,response) {
  let body = {
    recipient: {
      id= sender_psid
    },
    message: response
  };
  const qs = 'access_token=' + encodeURIComponent(FB_PAGE_TOKEN); // Here you'll need to add your PAGE TOKEN from Facebook
  return fetch('https://graph.facebook.com/me/messages?' + qs, {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(body),
  });
}

答案 1 :(得分:0)

我发现以下链接有助于理清在单个帖子后面实现多个响应的方式。

https://codingislove.com/build-facebook-chat-bot-javascript/

就像你说的那样,数组应该可行。创建一个包含多个响应消息的数组变量

var multipleResponse = {
   messages: [{
      response1
   },
   {
      response2
   }]
};

将数组变量推送到函数

function callSendAPI(sender_psid,response) {

    let body = {
         recipient: {
            id= sender_psid
         },
         message: []
    };
    // Followed by code for POST request to the webhook
}

最后将数组推送到函数数组

body.message.push(multipleResponse.messages);

答案 2 :(得分:0)

@Christos Panagiotakopoulos。我没有得到当时使用的mainMenuResponse链接。相反,我得到了三次响应。 handlePostback函数=>

// Handles messaging_postbacks events
function handlePostback(sender_psid, received_postback) {
  let response;

  // Get the payload for the postback
  let payload = received_postback.payload;

  // Set the response based on the postback payload
  if (payload === 'fashionTip') {
    response = { "text": getFashionTip() } // calls a function which gives a fashion-tip

  // Send the message to acknowledge the postback
  callSendAPI(sender_psid, response).then(() => {
    return callSendAPI(sender_psid, mainMenuResponse)
  });

callSendAPI函数=>

// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
  // construct the message body
  let request_body = {
    "recipient": {
      "id": sender_psid
    },
    "message": response
  }

  // Send the HTTP request to the messenger platform
  request({
    "uri": "https://graph.facebook.com/v2.6/me/messages",
    "qs": {"access_token": PAGE_ACCESS_TOKEN},
    "method": "POST",
    "json": request_body
  }, (err, res, body) => {
    if (!err) {
      console.log("Message sent!");
    } else {
      console.error("Unable to send mesage:" + err);
    }
  });
}

答案 3 :(得分:-2)

不要修改# This assumes brackets are properly balanced def parse1(L): newL = [] i = 0 while i<len(L): x = L[i] if x == '}': # Return the parsed list & the unparsed portion of the original list print(newL, L[i:]) return newL, L[i+1:] elif x == '{': # Split rest of L into parsed & unparsed portions parsed, unparsed = parse1(L[i+1:]) # Insert parsed portion into current list newL.append(parsed) # Reset i & L for unparsed portion i, L = 0, unparsed else: # Convert x to an integer if possible try: x = int(x) except: pass newL.append(x) i += 1 return newL 功能。在callSendAPI函数调用中handlePostback多次。

callSendAPI