本指南說明如何針對 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 應用程式設定授權。下載媒體支援以下兩者:
從檔案附件下載
如要從檔案附件下載媒體,請在要求中傳遞以下內容:
- 透過使用者驗證,指定
chat.messages.readonly
或chat.messages
授權範圍。透過應用程式驗證,指定chat.bot
授權範圍。 - 呼叫以下 Google Chat 方法:
- 呼叫以下其中一種方法,即可取得
attachmentDataRef
: - 呼叫
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( '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()
將程式碼中的
RESOURCE_NAME
替換為attachmentDataRef.resourceName
,您可以透過下列任一方式擷取其中一種:在工作目錄中建構並執行範例:
python3 chat_media_and_attachment_download.py
如果成功,此方法會以位元組形式傳回檔案內容。
如要下載檔案內容,請選擇下列其中一種做法:
我們建議在 Python 中使用
MediaIoBaseDownload
類別,該類別包含以各節下載檔案的方法,並將內容儲存至輸出串流。如果您必須手動提出 HTTP 要求,請呼叫
download
方法,並使用位元組範圍搭配Range
標頭,指定要下載的檔案部分,例如Range: bytes=500-999
。
相關主題
- 如果訊息是雲端硬碟檔案,請使用 Drive API 存取檔案。
- 以檔案附件上傳媒體
- 以檔案附件下載媒體
- 取得訊息附件的相關中繼資料