8

How can I receive an attachment in form of an image through the Facebook Messenger API? Their documentation only provides instructions on how to receive text-based messages.

Julian E.
  • 4,687
  • 6
  • 32
  • 49
Vivek Yadav
  • 81
  • 1
  • 1
  • 2
  • Hi and welcome to SO. Please make sure you [read this](http://stackoverflow.com/help/mcve) and try to improve your question. It will make it easier for others to understand it and help you out. – Thiago Sá May 09 '16 at 13:59
  • https://developers.facebook.com/docs/messenger-platform/webhook-reference#received_message has an example what the JSON data structure for a message with an attachment looks like. – CBroe May 09 '16 at 15:26

5 Answers5

8

I am not sure what language you are using to code your bot but since you are referring to the facebook documents where most of the messenger code snippets are in node.js Here's something for you to try, let me know if this helps.

app.post('/webhook/', function (req, res) {
 //Getting the mesagess
 var messaging_events = req.body.entry[0].messaging;
  //Looping through all the messaging events
  for (var i = 0; i < messaging_events.length; i++) {
   var event = req.body.entry[0].messaging[i];
   //Checking for attachments
   if (event.message.attachments) {
    //Checking if there are any image attachments 
    if(atts[0].type === "image"){
     var imageURL = atts[0].payload.url;
     console.log(imageURL);
    }
   }
  }      
 }
Sritam
  • 3,022
  • 1
  • 18
  • 17
  • 3
    FYI I'm not sure if this answer is outdated now. I'm making a facebook bot using ClaudiaJS and its backend is lambda/api gateway. For me now what contains the image is: `request.message.attachments[0].payload.url`. – Stephen Tetreault Feb 01 '17 at 19:32
3

In February 2017 I came across the same issue and struggled to get this up and running for a very long time. Turns out that the message.attachments comes in as object, where the actual attachment is within the object.

The structure goes like this:

Attachments Object > JSON Response >Type & Payload > URL

app.post('/webhook/', function(req, res) {

  let messaging_events = req.body.entry[0].messaging

  for (let i = 0; i < messaging_events.length; i++) {
    let event = req.body.entry[0].messaging[i]
    let sender = event.sender.id

    // Check if it's a message
    if (event.message) {

      //Create the attachment
      let attachment = event.message.attachments

      // Here we access the JSON as object
      let object1 = attachment[0];

      //Here we access the payload property 
      let payload = object1.payload;

      // Finally we access the URL
      let url = payload.url;

      console.log(url)
    }         
    else if (event.message && event.message.text) {
       // Here you can handle the text 
       console.log("Just Text")
    } 

   }        
  res.sendStatus(200)
})

The more compact version without explanations looks like this:

  if (event.message) {
    let attachment = event.message.attachments
    console.log(attachment[0].payload.url)
  }

As added bonus, you could also check if the type is an Image. You can achieve that by adding doing this adjustment:

  if (event.message && ) {
    let attachment = event.message.attachments[0]
    if (attachment.type === "image") {
        console.log(attachment.payload.url)
    } 
  }

Hope this helps, Julian

Julian E.
  • 4,687
  • 6
  • 32
  • 49
3

While in PYTHON to receive and save an image attachment in your facebook chatbot works:

@app.route('/', methods=['POST'])
def webhook():   # endpoint for processing incoming messaging events

data = request.get_json()

if data["object"] == "page":

    for entry in data["entry"]:
        for messaging_event in entry["messaging"]:
             if messaging_event["message"].get("attachments"):
                 attachment_link = messaging_event["message"]["attachments"][0]["payload"]["url"]
              print("Image received, boss!")
              print(attachment_link)

good chatbot-thing! Marco

2

In PHP,

When user sents it to bot, below response we get which contains attachement type and url

{
  "object": "page",
  "entry": [
    {
      "id": "000000000000000",
      "time": 1511956708068,
      "messaging": [
        {
          "sender": {
            "id": "000000000000000"
          },
          "recipient": {
            "id": "000000000000000"
          },
          "timestamp": 1511956707862,
          "message": {
            "mid": "mid.$xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "seq": 42172,
            "sticker_id": 369239263222822,
            "attachments": [
              {
                "type": "image",
                "payload": {
                  "url": "https:\/\/scontent.xx.fbcdn.net\/v\/t39.1997-6\/851557_369239266556155_759568595_n.png?_nc_ad=z-m&_nc_cid=0&oh=9058fb52f628d0a6ab92f85ea310db0a&oe=5A9DAADC",
                  "sticker_id": 369239263222822
                }
              }
            ]
          }
        }
      ]
    }
  ]
}

This is how you get different type of messages from user

//get the response from user
$input     = json_decode(file_get_contents('php://input'), true);

//first check if attachment is present
$attachment = array_key_exists('attachments', $input['entry'][0]['messaging'][0]['message']);

//get the attachement type and url
$type     = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['type'];
$file_url = $input['entry'][0]['messaging'][0]['message']['attachments'][0]['payload']['url'];

Hope this helps you

Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
0

https://developers.facebook.com/docs/messenger-platform/implementation#receive_message

Check this link out.

It says that, "Messages may have an image, video or audio attachment."

UPDATE:

The above link is broken as Facebook recently updated their documentations in a weirdly downgraded version with many contents missing.

To elaborate as pointed out in the comment, when a user sends a request, your server will receive such a json:

    {
        "mid": "some mid",
        "seq": 26,
        "attachments": [{
            "type": "image",
            "payload": {
                "url": "some image url"
            }
        }]
    }

and you can maybe create a download function to download the image to your server.

To use this data, as mentioned above, you can use the webhook.

  app.post('/webhook', function (req, res) {
    var data = req.body;
    // Make sure this is a page subscription
    if (data.object == 'page') {
      console.log(data.entry);
      // Iterate over each entry
      // There may be multiple if batched
      data.entry.forEach(function(pageEntry) {
        var pageID = pageEntry.id;
        var timeOfEvent = pageEntry.time;

        // Iterate over each messaging event
        pageEntry.messaging.forEach(function(messagingEvent) {
          receivedMessage(messagingEvent);
        });
      });

      // Assume all went well.
      //
      // You must send back a 200, within 20 seconds, to let us know you've
      // successfully received the callback. Otherwise, the request will time out.
      res.sendStatus(200);
    }
  });


  function receivedMessage(event) {
    var senderID = event.sender.id;
    var recipientID = event.recipient.id;
    var timeOfMessage = event.timestamp;
    var message = event.message;

    if (senderID == PAGE_ID) {
      console.error("Sender is self.");
      return;
    }

    console.log("Received message for user %d and page %d at %d with message:",
      senderID, recipientID, timeOfMessage);
    console.log(JSON.stringify(message));

    var messageId = message.mid;

    // You may get a text or attachment but not both
    var messageText = message.text;
    var messageAttachments = message.attachments;

    if (messageText) {

      // If we receive a text message, check to see if it matches any special
      // keywords and send back the corresponding example. Otherwise, just echo
      // the text we received.


    } else if (messageAttachments) {
      messageAttachments.forEach(function(messageAttachment) {
        var attachmentUrl = messageAttachment.payload.url;
        console.log("Received Attachment");
        download(attachmentUrl);
    }
  }

This code was taken from the sample code of Facebook.

Jay Shin
  • 914
  • 1
  • 7
  • 12