本指南說明如何針對以下項目的 Message
資源使用 list
方法:
使用 Google Chat API,查看聊天室中可篩選的分頁訊息清單。
Message
項資源
代表的
文字
或
資訊卡
訊息。你可以
create
、get
、update
或 delete
,透過呼叫方式在 Google Chat API 中傳送訊息
對應的方法如要進一步瞭解簡訊和資訊卡訊息,請參閱
Google Chat 訊息總覽。
必要條件
Python
- 企業或企業 具有存取權的 Google Workspace 帳戶 Google Chat。
- Python 3.6 以上版本
- pip 套件管理工具
- 最新的 Google 用戶端程式庫。安裝或更新
在指令列介面中執行下列指令:
pip3 install --upgrade google-api-python-client google-auth-oauthlib
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用並設定 Google Chat API。 圖示和說明
-
為電腦版應用程式建立 OAuth 用戶端 ID 憑證。如要在此環境中執行範例
,請將憑證以 JSON 檔案 (
client_secrets.json
) 的格式儲存至您的 本機目錄
- 選擇支援使用者驗證的授權範圍。
列出訊息
如要列出訊息 使用者驗證 並在要求中傳遞下列資訊:
- 指定
chat.messages.readonly
或chat.messages
授權範圍。 - 在
list
方法 的Message
項資源。
下列範例會列出之後在 Chat 聊天室中傳送的訊息 2023 年 3 月 16 日:
Python
- 在工作目錄中,建立名為
chat_messages_list.py
的檔案。 在
chat_messages_list.py
中加入下列程式碼:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # 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.readonly"] def main(): ''' Authenticates with Chat API via user credentials, then lists messages in a space sent after March 16, 2023. ''' # 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) # Use the service endpoint to call Chat API. result = chat.spaces().messages().list( # The space for which to list messages. parent = 'spaces/SPACE', # An optional filter that returns messages # created after March 16, 2023. filter = 'createTime > "2023-03-16T00:00:00-00:00"' ).execute() # Prints the list of messages. print(result) if __name__ == '__main__': main()
將程式碼中的
SPACE
替換成空格名稱, 您可以從中取得spaces.list
方法 或聊天室網址傳送在工作目錄中建構並執行範例:
python3 chat_messages_list.py
Google Chat API 會傳回指定聊天室中,位於 2023 年 3 月 16 日。