gpt4 book ai didi

javascript - Node js :Cannot read property 'text' of undefined

转载 作者:行者123 更新时间:2023-11-30 14:31:35 25 4
gpt4 key购买 nike

我正在使用 node js express 构建一个 Messenger 机器人。我正在尝试将我的 index.js 文件拆分为两个文件。这是新文件 msg.js 的代码

'const
express = require('express'),
bodyParser = require('body-parser'),
request = require('request'),
PAGE_ACCESS_TOKEN ="",
app = express().use(bodyParser.json());
//functions
module.exports = {
//hangles messages
handleMessage:function (sender_psid, received_message) {
let response;

// Checks if the message contains text
if (received_message.text) {
// Create the payload for a basic text message, which
// will be added to the body of our request to the Send API
response = {
"text": `You sent the message: "${received_message.text}". Now send me an attachment!`
}
} else if (received_message.attachments) {
// Get the URL of the message attachment
let attachment_url = received_message.attachments[0].payload.url;
response = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [{
"title": "Is this the right picture?",
"subtitle": "Tap a button to answer.",
"image_url": attachment_url,
"buttons": [
{
"type": "postback",
"title": "Yes!",
"payload": "yes",
},
{
"type": "postback",
"title": "No!",
"payload": "no",
}
],
}]
}
}
}
}

// Send the response message
module.exports.callSendAPI(sender_psid, response);
},

// Handles messaging_postbacks events
handlePostback:function (sender_psid, received_postback) {
let response;
// Get the payload for the postback
if (received_postback) {
let payload = received_postback.payload;
}
// Send the message to acknowledge the postback
module.exports.callSendAPI(sender_psid, response);
},

// Sends response messages via the Send API
callSendAPI:function (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 message:" + err);
}
});
}
};

我的 index.js 文件底部有以下代码。

//Imports functions from other files
let msg = require('./msg.js'),
handleMessage = msg.handleMessage(),
handlePostback = msg.handlePostback(),
callSendAPI = msg.callSendAPI();

我收到以下错误:

msg.js:14 如果 (received_message.text) { ^

类型错误:无法读取未定义的属性“文本”

最佳答案

问题是这一行:

if (received_message.text) {

当调用它时,传入的 received_message 是未定义的,因此当您尝试从 received_message 变量中获取 text 字段时它会抛出一个错误,因为 received_message 是未定义的,因此不会有任何你可以从中调用的字段。在传递到您的 handleMessage 函数之前检查是否正确设置了 received_message。

关于javascript - Node js :Cannot read property 'text' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51091747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com