Handling message attachments

When the user sends a message to your bot, the message can include attachments. These attachments can be either files from Google Drive or uploaded content (a local file). This guide describes how you can use the GetAttachment API to retrieve attachments.

Using the GetAttachment API

When the user sends a message to your bot, Google Chat dispatches an event. The event received by your bot includes a request body, which is the JSON payload representing the event, including any attachment. The data in the attachment is different depending on whether the attachment is uploaded content or is stored on Drive.

To get the attachment, add code to your bot that takes the following steps:

  • Call GetAttachment to retrieve the attachment metadata from the message.
  • If the attachment is uploaded content, call the Media API to get the bytes of the content.
  • If the message is a Drive file, use the Drive API to get access to the file.

The GetAttachment API is available at the following endpoint:

https://chat.googleapis.com/v1/ + attachment.name

The attachment field is included in the message payload to the bot.

Following is an example function that gets and returns the attachment from a message, using the API endpoint to get the attachment.

/**
 * Gets message attachment and returns it
 */
function getAttachment(attachmentName) {
  var attachment = {};
  var url = "https://chat.googleapis.com/v1/" + attachmentName;

  var service = getOAuth2Service(); 

  var response = UrlFetchApp.fetch(url, {
    method: 'get',
    headers: {
      'Authorization': 'Bearer ' + service.getAccessToken()
    },
    muteHttpExceptions:true,
  });

  if(response.getResponseCode() != 200){
    return "Failed to get attachment with error code: " + response.getResponseCode();
  }
  attachment = JSON.parse(response)
  return attachment;
}

Retrieving uploaded content

After you get the attachment, if the user has included a local file (uploaded content) as the attachment, an AttachmentDataRef will be present. You can use the AttachmentDataRef.resourcename with the Media API to retrieve the contents of the file the user uploaded. The Media API is available at the following endpoint:

https://chat.googleapis.com/v1/media/" + dataRef + "?alt=media"

Following is an example function that retrieves the contents of an uploaded file:

/**
 * Calls Media api to read data. dataRef is the reference to the uploaded
 * file to be read, found in the attachment.
 */
function getByteStream(dataRef) {
 var blob = "";
 var driveFileName = "";
 var url = "https://chat.googleapis.com/v1/media/"+ dataRef +"?alt=media"

 var service = getOAuth2Service();
 var response = UrlFetchApp.fetch(url, {
   headers: {
     'Authorization': 'Bearer ' + service.getAccessToken(),
   },
   'muteHttpExceptions': true,
 });

 if(response.getResponseCode() != 200){
   return "Failed to get file content with error code: " + response.getResponseCode();
 }
 blob = response.getBlob();
 driveFileName = DriveApp.createFile(blob);
 return "The uploaded contents have been saved in a Google Drive file: "+ driveFileName;
}

Note that this function stores the uploaded content in a newly created Drive file. This is optional and just an example of what you can do with the bytes after you retrieve them.

Message examples

Here is an example of the JSON representation of an attachment. The attachment is a field within the message. In this example, the source field contains UPLOADED_CONTENTand the attachmentDataRef field has the resource name of the attachment, which is used with the Media API to get the attachment contents.

{
  "name": "spaces/5o6pDgAAAAE/messages/m6mP13zUHTk.m6mP13zUHTk/attachments/AATUf-J224yPdqsp20yL3RVBl2UK",
  "contentName": "solar.png",
  "contentType": "image/png",
  "attachmentDataRef": {
    "resourceName":    "ClxzcGFjZXMvNW82cERnQUFBQUUvbWVzc2FnZXMvbTZtUDEzelVIVGsubTZtUDEzelVIVGsvYXR0YWNobWVudHMvQUFUVWYtSjIyNHlQZHFzcDIweUwzUlZCbDJVSw=="
  },
  "thumbnailUri": "https://chat.google.com/api/get_attachment_url?url_type=FIFE_URL&content_type=image/png&attachment_token=AAUuIGs8q7EXV7xUy38c5bHCJYpKCDcvJgmeIEWGSZHDAjUBaoQTjUoQ/Mupv/z8rvjGqxJPywmG4RSpeFTXcAiAKM2stSZuScYKYEoQK14JaoWEevYYVO4y3pSXnZ/Kf%2BK/lC%2BjDxOtVCQ1xOsrx6Qk3%2B%2B0UlZfPnHZlghj0%2BMXyquX49pOdOVuSVyxlDmzx/SSvED5ALYzoAbmG%2B9axrE53hZ1vahaoxfD8o10DGcMh0RNBJsYFx5dQpcAMNuW6KQ2Iu5ZtmzrKjuieA%2BkwsQkHx718b60bD25G0AL8OZSGT7K9TbwIA3t2Xxc%2BECM/ccSNhnMsBUuiaYiSf8K07hBoEo3RssoNMK9bBOqkbET90%2BN2Ow%2B0m4DktY%3D&sz=w512",
  "downloadUri": "https://chat.google.com/api/get_attachment_url?url_type=DOWNLOAD_URL&content_type=image/png&attachment_token=AAUuIGs8q7EXV7xUy38c5bHCJYpKCDcvJgmeIEWGSZHDAjUBaoQTjUoQ/Mupv/z8rvjGqxJPywmG4RSpeFTXcAiAKM2stSZuScYKYEoQK14JaoWEevYYVO4y3pSXnZ/Kf%2BK/lC%2BjDxOtVCQ1xOsrx6Qk3%2B%2B0UlZfPnHZlghj0%2BMXyquX49pOdOVuSVyxlDmzx/SSvED5ALYzoAbmG%2B9axrE53hZ1vahaoxfD8o10DGcMh0RNBJsYFx5dQpcAMNuW6KQ2Iu5ZtmzrKjuieA%2BkwsQkHx718b60bD25G0AL8OZSGT7K9TbwIA3t2Xxc%2BECM/ccSNhnMsBUuiaYiSf8K07hBoEo3RssoNMK9bBOqkbET90%2BN2Ow%2B0m4DktY%3D&auto=true",
  "source": "UPLOADED_CONTENT"
}

Note: don’t use the thumbnailUri and downloadUri fields to access the contents of the uploaded file from your bot. Use the Media API instead, as described earlier. The thumbnailUri field can be used to preview the attachment for a human user. The downloadUri field can be used to allow a human user to download the attachment.

Following is an example of a message with a Google Drive attachment. In this example, the source field contains DRIVE_FILE and the driveDataRef field has the file ID of the attachment.

name: "spaces/5o6pDgAAAAE/messages/Ohu1LlUVcS8.Ohu1LlUVcS8/attachments/AATUf-Iz7d8kySEdRRZd-dznqBk3"
content_name: "solar.png"
content_type: "image/png"
drive_data_ref {
  drive_file_id: "1HqaqRuH2Pfd_TOa1fF2_ltwDlV_yKRrr"
}
message_metadata {
  name: "spaces/5o6pDgAAAAE/messages/Ohu1LlUVcS8.Ohu1LlUVcS8"
  sender: "101758396040800075119"
  create_time {
    seconds: 1598383223
    nanos: 650047000
  }
  update_time {
    seconds: 1598383223
    nanos: 650047000
  }
}
source: DRIVE_FILE

More information

For more information on creating bots, see the Chat REST API Reference.