取得郵件附件的相關中繼資料

本指南說明如何針對以下項目的 Media 資源使用 get 方法: 用於取得訊息附件的中繼資料。系統會 執行個體 Attachment 資源

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

必要條件

Python

  • Python 3.6 以上版本
  • pip 套件管理工具
  • 最新的 Google 用戶端程式庫。安裝或更新 在指令列介面中執行下列指令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

取得訊息附件

如要以非同步方式取得 Google Chat 訊息附件的中繼資料,請 包括:

如何取得郵件附件的相關中繼資料:

Python

  1. 在工作目錄中,建立名為 chat_get_message_attachment.py
  2. chat_get_message_attachment.py 中加入下列程式碼:

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = (
        service_account.Credentials.from_service_account_file('credentials.json')
        .with_scopes(SCOPES)
    )
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Get a Chat message.
    result = chat.spaces().messages().attachments().get(
    
        # The message to get.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        #
        # Replace MESSAGE with a message name.
        # Obtain the message name from the response body returned
        # after creating a message asynchronously with Chat REST API.
        name='spaces/SPACE/messages/MESSAGE/attachments/ATTACHMENT'
    
      ).execute()
    
    # Print Chat API's response in your command line interface.
    print(result)
    
  3. 在程式碼中,以 spaces/SPACE/messages/MESSAGE/attachments/ATTACHMENT 改為訊息附件名稱

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

    python3 chat_get_message_attachment.py
    

Chat API 會傳回 Attachment敬上 詳細列出指定訊息附件的中繼資料。