以檔案附件的形式上傳媒體

本指南說明如何在 Google Chat API 的 Media 資源上使用 upload 方法,將媒體 (檔案) 上傳至 Google Chat,然後再附加到訊息中。

使用者傳送訊息給您的應用程式時,Google Chat 會派出 MESSAGE 互動事件。應用程式收到的互動事件包含要求主體,這是代表互動事件 (包括任何附件) 的 JSON 酬載。附件中的資料取決於附件是上傳的內容 (本機檔案),或是否為儲存在雲端硬碟的檔案。Media 資源代表上傳至 Google Chat 的檔案,例如圖片、影片和文件。Attachment 資源代表附加在訊息中的媒體例項,也就是檔案。Attachment 資源包含連結的中繼資料,例如連結的儲存位置。

必要條件

Python

  • Python 3.6 或更高版本
  • pip 套件管理工具
  • 最新的 Python 專用 Google 用戶端程式庫。如要安裝或更新,請在指令列介面中執行下列指令:

    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    
  • 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
  • 已設定 Chat 應用程式的授權。如要以檔案附件形式上傳媒體,您必須使用 chat.messages.createchat.messages 授權範圍的使用者驗證功能。

以檔案附件形式上傳

如要上傳媒體並附加到訊息,請在要求中傳遞以下內容:

  • 指定 chat.messages.createchat.messages 授權範圍。
  • 呼叫下列 Google Chat 方法:
    1. 如要上傳檔案,請呼叫 Media 資源上的 upload 方法
      • parent 設為代管檔案的聊天室名稱。
      • body (要求主體) 中,將 filename 設為上傳檔案附件的名稱。
      • media_body 設為要上傳檔案的執行個體。
    2. 如要建立附加已上傳檔案的訊息,請呼叫 Messages 資源上的 create 方法

以下範例會上傳 PNG 圖片檔並附加到訊息中。

Python

  1. 在工作目錄中,建立名為 chat_media_and_attachment_upload.py 的檔案。
  2. 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. 將程式碼中的 SPACE 替換為聊天室名稱即可上傳附件,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。

  4. 在工作目錄中,建構並執行範例:

    python3 chat_media_and_attachment_upload.py
    

Chat API 會傳回包含 attachmentDataRef 的回應主體,以及已上傳檔案的詳細資料。

限制和注意事項

當您準備上傳檔案並附加到訊息時,請注意下列限制和注意事項: