通过 NodeJS 将文件加载到 Facebook Messenger 时出现问题

Problem with loading file to facebook messenger through NodeJS

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

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);
}