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