本指南說明如何使用 Google Chat API Media
資源的 download
方法,從 Google Chat 訊息下載媒體 (檔案)。
使用者傳送訊息給應用程式時,Google Chat 會傳送MESSAGE
互動事件。
應用程式收到的互動事件包含要求內文,也就是代表互動事件的 JSON 酬載,包括任何附件。附件中的資料會因附件是上傳內容 (本機檔案) 或儲存在雲端硬碟中的檔案而異。「Media
」資源代表上傳至 Google Chat 的檔案,例如圖片、影片和文件。Attachment
資源代表附加至訊息的媒體 (檔案) 執行個體。Attachment
資源包含附件的中繼資料,例如附件的儲存位置。
必要條件
Python
- 具有 Google Chat 存取權的 Business 或 Enterprise 版 Google Workspace 帳戶。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用並設定 Google Chat API,為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Python Google API 用戶端程式庫。
- 根據您要在 Google Chat API 要求中驗證的方式,建立存取憑證:
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄,命名為
credentials.json
的 JSON 檔案。 - 如要以 Chat 應用程式的身分進行驗證,請建立服務帳戶憑證,然後將憑證儲存為名為
credentials.json
的 JSON 檔案。
- 如要以 Chat 使用者身分進行驗證,請建立 OAuth 用戶端 ID 憑證,並將憑證儲存至本機目錄,命名為
- 根據您要以使用者或 Chat 應用程式的身分驗證,選擇授權範圍。
從檔案附件下載
如要從檔案附件下載媒體,請在要求中傳遞下列內容:
- 使用使用者驗證時,請指定
chat.messages.readonly
或chat.messages
授權範圍。使用應用程式驗證,指定chat.bot
授權範圍。 - 呼叫下列 Google Chat 方法:
- 呼叫下列其中一種方法,取得
attachmentDataRef
:Attachment
資源的get
方法。Message
資源的get
方法或list
方法。Message
- 在
Media
資源上呼叫download
方法,並將先前擷取的attachmentDataRef.resourceName
指定為media.download.resourceName
。
- 呼叫下列其中一種方法,取得
以下範例會下載附加至郵件的檔案:
Python
- 在工作目錄中,建立名為
chat_media_and_attachment_download.py
的檔案。 在
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()
在程式碼中,將
RESOURCE_NAME
替換為attachmentDataRef.resourceName
,您可以透過下列其中一種方式擷取attachmentDataRef.resourceName
:在工作目錄中,建構並執行範例:
python3 chat_media_and_attachment_download.py
如果成功,這個方法會以位元組形式傳回檔案內容。
如要下載檔案內容,請選擇下列其中一種做法:
建議您使用 Python 中的
MediaIoBaseDownload
類別,其中包含以區段下載檔案,並將內容儲存至輸出串流的方法。如要手動發出 HTTP 要求,請呼叫
download
方法,並使用Range
標頭中的位元組範圍指定要下載的檔案部分,例如:Range: bytes=500-999
。
相關主題
- 如果郵件是雲端硬碟檔案,請使用 Drive API 取得檔案存取權。
- 以檔案附件形式上傳媒體
- 將媒體下載為檔案附件
- 取得郵件附件的中繼資料