在Facebook Messenger Bot中创建动态轮播

时间:2018-01-04 13:49:20

标签: node.js facebook-messenger-bot

要创建轮播,我们应该在有效载荷的元素数组中添加更多元素

"payload": {
  "template_type":"generic",
  "elements":[
    <GENERIC_TEMPLATE>,
    <GENERIC_TEMPLATE>,
    ...
  ]
}

但是在那些模板中,我想添加一个动态值,我从db或某些api中获取

例如,

messageData = {
              // text: "Enter the venue name"
              "attachment": {
                "type": "template",
                "payload": {
                  "template_type": "generic",
                  "elements": [{  
                    "title": "sample",
                    "subtitle":"We'\''ve got the right hat for everyone.",
                    "buttons": [
                      {
                        "type": "postback",
                        "title": data[i],
                        "payload": "Book Me a Venue",
                      }
                    ]
                  },{  
                    "title": "sample",
                    "subtitle":"We'\''ve got the right hat for everyone.",
                    "buttons": [
                      {
                        "type": "postback",
                        "title": data[i],
                        "payload": "Book Me a Venue",
                      }
                    ]
                  },{  
                    "title": "sample",
                    "subtitle":"We'\''ve got the right hat for everyone.",
                    "buttons": [
                      {
                        "type": "postback",
                        "title": data[i],
                        "payload": "Book Me a Venue",
                      }
                    ]
                  }
                ]
                }
              }
            }

我想发送动态值,而不是那些硬编码的值 任何帮助都是有用的

1 个答案:

答案 0 :(得分:0)

要迭代一个对象数组,你需要这样做....

console.log("-------2222222", data.length)
        var objArray = []
        for (var i = 0; i < data.length; i++) {
          var object = {
            "title": data[i].venueName,

            "buttons": [
              {
                "type": "postback",
                "title": "Select",
                "payload": data[i].id,
              }
            ]
          }
          objArray.push(object)
        }
        messageData = {
          "attachment": {
            "type": "template",
            "payload": {
              "template_type": "generic",
              "elements": objArray
            }
          }
        }