json - 在 Facebook Messenger Bots 中的单个回发中发送多条回复消息

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

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

我的代码结构与他们在网站上提供的教程非常相似,我有一个“handlePostback”函数,用于识别收到的回发并将其与一组预定义的有效负载进行比较以查找'response' 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
  }
 ]
};

我希望我能解释我的问题,如果我能提供更多详细信息,请告诉我!

最佳答案

好问题。如果您不熟悉 Node.js,那么实现它的方法不是很明显,并且 Facebook 的 Send API 文档中没有很好地记录这一点。

首先,您可能已经观察到,使用数组发送多条消息的方法行不通。 Facebook 有一个解决方案,可以通过一个请求发送多达 100 个 API 调用,但我认为这在您的情况下是不需要的。如果您想了解更多信息,请查看 Batched Request Documentation ,你会发现实现和你的不一样。

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

要解决此问题,您需要链接您的 callSendAPI 函数,以保证下一个 callSendAPI 调用仅在第一条消息已发送后发生。您可以在 NodeJS 中通过使用回调或 promise 来做到这一点。如果您对其中任何一个都不熟悉,可以阅读this用于回调和 this promise 。

您需要修改 callSendAPI 函数,尤其是向 Facebook 发送 POST 请求的部分。我将使用 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),
  });
}

关于json - 在 Facebook Messenger Bots 中的单个回发中发送多条回复消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47483190/

相关文章:

Facebook 分享。更改 "say something more about this",同一页面上的多个按钮

html - CSS:DIV 中的文本被截断

arrays - 使用 MarkLogic Patch Builder 在 JSON 数组的末尾插入一个新的数组项

json - 使用 jq + bash 将 json 转换为 ini 文件

php - 如何在 PHP 中使用 Twitter Streaming API?

json - Flutter 从复杂的 json 中获取数据

node.js - 为什么 apache 重写 URL 两次?

javascript - 使用 crypto 模块进行 Node.js MD5 解密

node.js - 更改 Webstorm 中 Node js 调试库的控制台字体颜色

iphone - 通过 API 成为 Facebook 页面的粉丝?