Messenger Bot: TypeError: Cannot read property 'text' of undefined

Messenger Bot: TypeError: Cannot read property 'text' of undefined

我开始使用 Messenger bot,但遇到了上述错误。我有以下代码:

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' 时,机器人将使用通用模板回复,当按下按钮 'purchase' 时,机器人崩溃了。我的错误日志如下:

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

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

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

正如在 Webhook Reference for Messenger Platform 中提到的那样,您的 webhook 中的回发调用中没有 属性 "message"。

对于回发,不是访问 "message" 属性,而是必须访问 "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 属性 在回发的情况下不存在(未定义),所以当您尝试访问 [=36 的子 属性 =] (event.message.text),代码以错误退出。因此,为了减轻这种情况,您可以每次检查是否定义了 .message 属性,如下所示:

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