Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a file to Facebook Send API using npm's Request without uploading the file?

I'm implementing a bot that uses Facebook's Send API. According to the documentation it is possible to send files using a request. The documentation offers two methods, one sending a URL to the file and the other uploading the file. I don't want to upload the file and give it a URL as this is an open source library that doesn't want to assume anything about the implementation.

I do want to upload the file directly. The documentation for uploading the file uses cURL for the example and looks as follows:

curl  \
  -F recipient='{"id":"USER_ID"}' \
  -F message='{"attachment":{"type":"file", "payload":{}}}' \
  -F filedata=@/tmp/receipt.pdf \
  "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN"    

My current take is that it should look something like this:

facebook_message.access_token = configuration.access_token;
var fileReaderStream = fs.createReadStream('./sampleData.json')
var formData = {
                "recipient": JSON.stringify({
                  "id":message.channel
               }),
               "attachment": JSON.stringify({
                  "type":"file", 
                  "payload":{}
               }),
               "filedata": fileReaderStream
               }

request({
         "method": 'POST',
         "json": true,
         "formData": formData,
         "uri": 'https://graph.facebook.com/v2.6/me/messages?access_token=' + configuration.access_token
        },
        function(err, res, body) {
               //***
        });

When I run this I receive the following response:

{ 
  message: '(#100) Must send either message or state',
  type: 'OAuthException',
  code: 100,
  error_subcode: 2018015,
  fbtrace_id: '***' 
 }
like image 343
Agam Rafaeli Avatar asked Jan 24 '26 11:01

Agam Rafaeli


1 Answers

The error you are receiving is because "attachment":{} needs to be inside an object called message. You must send either a message or sender_action object with facebook send API.

var formData = {
                "recipient": JSON.stringify({
                  "id":message.channel
               }),
               "message": JSON.stringify({
               "attachment": {
                  "type":"file",
                  "payload":{}
              }
          }),
               "filedata": fileReaderStream

               }

Facebook should accept your api call after this, however I was unable to display a jpg file sent using your code. Perhaps it will work with your JSON file

like image 103
Jon Church Avatar answered Jan 26 '26 23:01

Jon Church



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!