從檔案附件下載媒體

本指南說明如何在 Google Chat API 的 Media 資源上使用 download 方法,從 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 應用程式設定授權。 下載媒體支援以下功能:

從檔案附件下載

如要從檔案附件下載媒體,請在要求中傳遞以下內容:

以下範例會下載郵件中附加的檔案:

Python

  1. 在工作目錄中,建立名為 chat_media_and_attachment_download.py 的檔案。
  2. 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(
                    'client_secrets.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()
    
  3. 在程式碼中,將 RESOURCE_NAME 替換為 attachmentDataRef.resourceName,您可以採用下列其中一種方式擷取:

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

    python3 chat_media_and_attachment_download.py
    

如果成功,這個方法會以位元組形式傳回檔案內容。

如要下載檔案內容,請選擇下列其中一種做法:

  • 建議您在 Python 中使用 MediaIoBaseDownload 類別,其中包含多種方法來下載檔案,並將內容儲存至輸出串流。

  • 如果您必須手動發出 HTTP 要求,請呼叫 download 方法,並使用含有 Range 標頭的位元組範圍指定要下載的檔案部分,例如:Range: bytes=500-999