我正在使用NodeJS为facebook构建一个聊天机器人,根据documentation,我很难尝试通过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);
}
答案 0 :(得分:2)
经过大量搜索后,我能够对应用程序的方法进行必要的更改,从而可以通过Messenger传输文件,这一概念几乎是正确的,错误的是数据的发送方式,正确的一种是通过表格发送给他们。解决方法如下:
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);
}