Upload media as a file attachment

This guide explains how to use the upload method on the Media resource of the Google Chat API to upload media (a file) to Google Chat and then attach it to a message.

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

  • Python 3.6 or greater
  • The pip package management tool
  • The latest Google client libraries for Python. To install or update them, run the following command in your command-line interface:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app. Uploading media as a file attachment requires User authentication with the chat.messages.create or chat.messages authorization scope.

Upload as a file attachment

To upload media and attach it to a message, pass the following in your request::

  • Specify the chat.messages.create or chat.messages authorization scope.
  • Call the following Google Chat methods:
    1. To upload the file, call the upload method on the Media resource.
      • Set parent to the space name of the space that hosts the file.
      • In body (the request body), set filename to the name of the uploaded file attachment.
      • Set media_body as an instance of the file to be uploaded.
    2. To create a message with the uploaded file attached, call the create method on the Messages resource.

The following example uploads a PNG image file and attaches it to a message.

Python

  1. In your working directory, create a file named chat_media_and_attachment_upload.py.
  2. Include the following code in chat_media_and_attachment_upload.py:

    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaFileUpload
    
    # 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.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then uploads a file as media, creates a message, and
        attaches the file to the message.
        '''
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                      'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        service = build('chat', 'v1', credentials=creds)
    
        # Upload a file to Google Chat.
        media = MediaFileUpload('test_image.png', mimetype='image/png')
    
        # Create a message and attach the uploaded file to it.
        attachment_uploaded = service.media().upload(
    
            # The space to upload the attachment in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The filename of the attachment, including the file extension.
            body={'filename': 'test_image.png'},
    
            # Media resource of the attachment.
            media_body=media
    
        ).execute()
    
        print(attachment_uploaded)
    
        # Create a Chat message with attachment.
        result = service.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Must match the space name that the attachment is uploaded to.
            parent='spaces/SPACE',
    
            # The message to create.
            body={
                'text': 'Hello, world!',
                'attachment': [attachment_uploaded]
            }
    
        ).execute()
    
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. In the code, replace SPACE with the space name to upload the attachment in, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.

  4. In your working directory, build and run the sample:

    python3 chat_media_and_attachment_upload.py
    

The Chat API returns a response body containing attachmentDataRef with details about the uploaded file.

Limits and considerations

As you prepare to upload files and attach them to messages, take note of these limits and considerations: