node.js - 通过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);
}
推荐阅读
- ios - 如果计划将 Ruby on Rails 用于 IOS 应用程序,我是否需要使用 Core Data?
- java - 将 jBLAS 与 NVBLAS 一起使用
- r - 如何在 geom_violin 中复制 vioplot?
- python - 合并时保留 csv 文件的副本
- entity-framework-core - Entity Framework Core:有没有办法重用子查询而不是不使用 DRY 的 Include?
- javascript - 是否可以通过 jQuery 全局更改 CSS 变量?
- kubernetes - k8 pod 优先级和测试
- python - 由 bs4 和正则表达式元素创建的 pandas 对象被打印为 python 列表
- java - Mockito/PowerMockito 检查退货
- python - 如何将雪人形状的轮廓分成两个圆圈