本指南說明如何針對 Google Chat API 的 Media
資源使用 get
方法,取得訊息附件的相關中繼資料。回應是 Attachment
資源的執行個體。
使用者傳送訊息給您的應用程式時,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-auth
- 已啟用並設定 Google Chat API 的 Google Cloud 專案。相關步驟請參閱「建構 Google Chat 應用程式」。
已為 Chat 應用程式設定授權。如要取得訊息,您必須使用
chat.bot
授權範圍的應用程式驗證。
取得訊息附件
如要在 Google Chat 中以非同步方式取得訊息附件的中繼資料,請在要求中傳遞以下內容:
- 指定
chat.bot
授權範圍。 - 呼叫
Attachment
資源上的get
方法。 - 傳遞訊息附件的
name
。
如何取得訊息附件的中繼資料:
Python
- 在工作目錄中,建立名為
chat_get_message_attachment.py
的檔案。 在
chat_get_message_attachment.py
中加入下列程式碼:from google.oauth2 import service_account from apiclient.discovery import build # Specify required scopes. SCOPES = ['https://www.googleapis.com/auth/chat.bot'] # Specify service account details. CREDENTIALS = ( service_account.Credentials.from_service_account_file('credentials.json') .with_scopes(SCOPES) ) # Build the URI and authenticate with the service account. chat = build('chat', 'v1', credentials=CREDENTIALS) # Get a Chat message. result = chat.spaces().messages().attachments().get( # The message to get. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. # # Replace MESSAGE with a message name. # Obtain the message name from the response body returned # after creating a message asynchronously with Chat REST API. name='spaces/SPACE/messages/MESSAGE/attachments/ATTACHMENT' ).execute() # Print Chat API's response in your command line interface. print(result)
請將程式碼中的
spaces/SPACE/messages/MESSAGE/attachments/ATTACHMENT
替換成訊息附件名稱。在工作目錄中,建構並執行範例:
python3 chat_get_message_attachment.py
Chat API 會傳回 Attachment
的執行個體,詳細說明指定訊息附件的中繼資料。