通过 NodeJS 将文件加载到 facebook messenger 时出现问题



我正在使用 NodeJS 为 facebook 构建一个聊天机器人,我很难尝试通过 Facebook 的 API 通过 messeger 发送本地文件,根据文档执行文件加载,有必要进行远程调用,如下例所示:

curl  
-F 'message={"attachment":{"type":"image", "payload":{"is_reusable":true}}}' 
-F 'filedata=@/tmp/shirt.png;type=image/png' 
"https://graph.facebook.com/v2.6/me/message_attachments?access_token=<PAGE_ACCESS_TOKEN>"

实际上,使用示例,执行文件的上传,并返回"attachment_id",以便我可以将文件附加到一条或多条消息中,但是我无法通过我的应用程序上传,我已经尝试在对象上以不同的方式构建文件,尝试放置路径, 尝试放置文件流等,但始终返回以下错误:

{
message: '(#100) Incorrect number of files uploaded. Must upload exactly one file.',
type: 'OAuthException',
code: 100,
error_subcode: 2018005,
fbtrace_id: 'XXXXXXXXXX',
{ recipient: { id: 'XXXXXXXXXX' },
message: { attachment: { type: 'file', payload: [Object] } },
filedata: '@pdf_exemple.pdf;type=application/pdf' 
}

我不是 Node/JavaScript 方面的专家,所以我可能会犯一些愚蠢的错误......无论如何,下面是我的代码片段,负责组装对象并将其发送到Facebook。欢迎任何帮助。

function callSendAPI(messageData) {
request({
url: 'https://graph.facebook.com/v2.6/me',
qs : { access_token: TOKEN },
method: 'POST',
json: messageData
}, function(error, response, body) {
if (error) {
console.log(error);
} else if (response.body.error) {
console.log(response.body.error);
}
})
}
function sendAttachment(recipientID) {
var messageData = {
recipient: {
id: recipientID
},
message: {
attachment: {
type: 'file', 
payload: {
'is_reusable': true,
}
}
},
filedata: '@pdf_exemple.pdf;type=application/pdf'
};
callSendAPI(messageData);
}

搜索了很多之后,我能够对应用程序的方法进行必要的更改,以便可以通过messeger传输文件,这个概念几乎是正确的,错误的是发送数据的方式,正确的是通过表单发送它们。这是解决方案:

function callSendAPI(messageData, formData) {
request({
url: 'https://graph.facebook.com/v2.6/me',
qs : { access_token: TOKEN },
method: 'POST',
json: messageData,
formData: formData,
}, function(error, response, body) {
if (error) {
console.log(error);
} else if (response.body.error) {
console.log(response.body.error);
}
})
}
function sendAttachment(recipientID, fileName) {
var fileReaderStream = fs.createReadStream(fileName)
var formData = {
recipient: JSON.stringify({
id: recipientID
}),
message: JSON.stringify({
attachment: {
type: 'file',
payload: {
is_reusable: false
}
}
}),
filedata: fileReaderStream
}
callSendAPI(true, formData);
}

最新更新