從檔案附件下載媒體

本指南說明如何使用 Google Chat API Media 資源的 download 方法,從 Google Chat 訊息下載媒體 (檔案)。

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

必要條件

Python

從檔案附件下載

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

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

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(
                    '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()
    
  3. 在程式碼中,將 RESOURCE_NAME 替換為 attachmentDataRef.resourceName,您可以透過下列其中一種方式擷取 attachmentDataRef.resourceName

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

    python3 chat_media_and_attachment_download.py

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

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

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

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