Messenger Bot:TypeError:无法读取属性' text'未定义的

时间:2017-06-19 12:56:24

标签: javascript facebook-messenger facebook-messenger-bot

我开始使用messenger机器人并且遇到上述错误。我有以下代码:

app.post('/webhook', (req, res) => {
  console.log(req.body);
  if (req.body.object === 'page') {
    req.body.entry.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message.text === 'buy') {
          sendGenericMessage(event)
        } else if (event.postback) {
          processPostback(event)}
      });
    });
    res.status(200).end();
  }
});

function sendGenericMessage(event) {
  const senderID = event.sender.id;

  var messageData = {
    "attachment":{
      "type":"template",
      "payload":{
        "template_type":"generic",
        "elements":[
           {
            ...
            "buttons":[
              {
                "type":"postback",
                "title":"Purchase",
                "payload":"PURCHASE_PAYLOAD"
              },{
                "type":"postback",
                "title":"Start Chatting",
                "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }
            ]
          }, {
           "title":"Welcome to Peter\'s Hats",
           "image_url":"https://static.pexels.com/photos/177809/pexels-photo-177809.jpeg",
           "subtitle":"We\'ve got the right hat for everyone.",
           "buttons":[
             {
               ...
             }
           ]
         }
        ]
      }
    }
  }

  request({
    url: 'https://graph.facebook.com/v2.6/me/messages',
    qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
    method: 'POST',
    json: {
      recipient: {id: senderID},
      message: messageData
    }
  }, function (error, response) {
    if (error) {
        console.log('Error sending message: ', error);
    } else if (response.body.error) {
        console.log('Error: ', response.body.error);
    }
  });
}

function processPostback(event) {
  const senderID = event.sender.id;
  const payload = event.postback.payload;

 if (payload === "PURCHASE_PAYLOAD") {
    var message = event.message.text + " payment"
    sendMessage(event, message)
  }
}

当我输入' buy'时,机器人会回复一个通用模板,当按钮“购买”时,被迫,机器人坠毁了。我的错误日志如下:

enter image description here

我已经搜索过并发现了类似的类似问题,但是与我们相比,我的搜索来自回发而不是短信。 How to avoid 'cannot read property of undefined' errors?

I'm having "TypeError: Cannot read property 'text' of undefined" while developing Facebook Messenger bot

这里的一些帮助会很棒,谢谢。

1 个答案:

答案 0 :(得分:1)

正如Webhook Reference for Messenger Platform中提到的那样,您的webhook中的回发调用中没有属性“消息”。

对于回发,您不必访问“messages”属性,而是必须访问“payload”属性以获取与回发调用关联的数据(在您的情况下,按下按钮的有效负载)。

为了实现这一点,我首先会在按下有效负载内添加一些内容,如下所示:

"buttons":
  [
    {
      "type":"postback",
      "title":"Purchase",
      "payload": "{"type": "PURCHASE_PAYLOAD", "message": "WHATEVER YOU WANT"}"
    },
    {
      "type":"postback",
      "title":"Start Chatting",
      "payload":"DEVELOPER_DEFINED_PAYLOAD"
    }
  ]

然后我以这种方式重写代码的 processPostback 函数:

function processPostback(event) {
  const senderID = event.sender.id;
  const payload = JSON.parse(event.postback.payload);

  if (payload.type === "PURCHASE_PAYLOAD") {
    var message = payload.message + " payment"
    sendMessage(event, message)
  }
}

通过这些更改,您实际上会传递要在按下的按钮的有效负载内发送的消息,这样,只要用户按下按钮,您的代码就会知道要发送的内容。

您还需要更改 entry.messaging.forEach 中的代码。因为您的代码尝试访问event.message属性,该属性在回发的情况下不存在(未定义),所以当您尝试访问event.message(event.message.text)的子属性时,代码退出有错误。因此,为了缓解这种情况,您可以每次检查是否定义了.message属性,如下所示:

entry.messaging.forEach((event) => {
  if (event.message) {
    if (event.message.text === 'buy') {
      sendGenericMessage(event)
    }
  } else if (event.postback) {
    processPostback(event)
  }
});