首页 > 解决方案 > 通过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);
}

标签: node.jsfacebookfacebook-graph-apirequestchatbot

解决方案


经过大量搜索,我能够对我的应用程序的方法进行必要的更改,以使通过 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);
}

推荐阅读