AI-generated Key Takeaways
-
This guide demonstrates how to download media files (like images, videos, or documents) from messages in Google Chat using the Google Chat API's
downloadmethod. -
The process involves retrieving the
attachmentDataReffrom theAttachmentorMessageresource and then using it to call thedownloadmethod on theMediaresource. -
You need a Google Workspace account, a configured Google Cloud project with the Chat API enabled, and the Google API Client Library for Python to implement this functionality.
-
The guide provides a Python code example for authenticating with the API and downloading the file content, along with instructions on how to retrieve the necessary resource names.
This guide explains how to use the download method on the Media resource of
the Google Chat API to download media (a file) from a message in Google Chat.
When the user sends a message to your app, Google Chat dispatches a
MESSAGE interaction event.
The interaction event received by your app includes a request body, which is the
JSON payload representing the interaction event, including any attachments. The
data in the attachment is different depending on whether the attachment is
uploaded content (a local file) or is a file stored on Drive. The
Media resource
represents a file uploaded to Google Chat, like images, videos, and documents.
The
Attachment resource
represents an instance of media—a file—attached to a message. The Attachment
resource includes the metadata about the attachment, such as
where it's saved.
Prerequisites
Python
- A Business or Enterprise Google Workspace account with access to Google Chat.
- Set up your environment:
- Create a Google Cloud project.
- Configure the OAuth consent screen.
- Enable and configure the Google Chat API with a name, icon, and description for your Chat app.
- Install the Python Google API Client Library.
- Create access credentials based on how you want to authenticate in your Google Chat API
request:
- To authenticate as a Chat user,
create OAuth client ID
credentials and save the credentials as a JSON file named
credentials.jsonto your local directory. - To authenticate as the Chat app,
create service account
credentials and save the credentials as a JSON file named
credentials.json.
- To authenticate as a Chat user,
create OAuth client ID
credentials and save the credentials as a JSON file named
- Choose an authorization scope based on whether you want to authenticate as a user or the Chat app.
Download from a file attachment
To download media from a file attachment, pass the following in your request:
- With user authentication, specify the
chat.messages.readonlyorchat.messagesauthorization scope. With app authentication, specify thechat.botauthorization scope. - Call the following Google Chat methods:
- Get
attachmentDataRefby calling one of the following methods:- The
getmethod on theAttachmentresource. - The
getmethod or thelistmethod on theMessageresource.
- The
- Call the
downloadmethod on theMediaresource, and specify the previously retrievedattachmentDataRef.resourceNameasmedia.download.resourceName.
- Get
The following example downloads a file attached to a message:
Python
- In your working directory, create a file named
chat_media_and_attachment_download.py. Include the following code in
chat_media_and_attachment_download.py:import io from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload # Define your app's authorization scopes. # When modifying these scopes, delete the file token.json, if it exists. SCOPES = ["https://www.googleapis.com/auth/chat.messages"] def main(): ''' Authenticates with Chat API via user credentials, then downloads a file attached to a message. ''' # Authenticate with Google Workspace # and get user authorization. flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. chat = build('chat', 'v1', credentials=creds) # Download media resource. request = chat.media().download_media( resourceName=RESOURCE_NAME, ) file = io.BytesIO() downloader = MediaIoBaseDownload(file, request) done = False while done is False: status, done = downloader.next_chunk() if status.total_size: print(f'Total size: {status.total_size}') print(f'Download {int(status.progress() * 100)}') if __name__ == '__main__': main()In the code, replace
RESOURCE_NAMEwithattachmentDataRef.resourceName, which you can retrieve one of the following ways:- The
getmethod on theAttachmentresource. - The
getmethod on theMessageresource. - The
listmethod on theMessageresource.
- The
In your working directory, build and run the sample:
python3 chat_media_and_attachment_download.py
If successful, this method returns the file content as bytes.
To download the file contents, choose one of the following approaches:
We recommend using the
MediaIoBaseDownloadclass in Python, which contains methods to download the file in sections and save the contents to an output stream.If you must make the HTTP request manually, call the
downloadmethod and specify the portion of the file that you want to download by using a byte range with theRangeheader—for example:Range: bytes=500-999.
Related topics
- If the message is a Drive file, use the Drive API to get access to the file.
- Upload media as a file attachment
- Download media as a file attachment
- Get metadata about a message attachment