本指南說明如何使用 list
SpaceEvent
資源的方法
使用 Google Chat API,列出聊天室資源變更。
SpaceEvent
資源
代表變更目標空間,包括空間的子項資源
例如訊息、回應和會員資格如要進一步瞭解
支援的事件類型和事件酬載清單,請參閱 eventType
和
SpaceEvent
資源的 payload
欄位
參考文件
您最多可以列出要求時間前 28 天的事件。伺服器
會傳回包含受影響資源的最新版本事件。
舉例來說,如果您列出新聊天室成員的事件,伺服器會傳回
Membership
資源,內含最新會員詳細資料。如果是
成員已在要求期間遭到移除,事件酬載會包含
空白的 Membership
資源。
如要呼叫這個方法,您必須使用 user 驗證。待播清單 通過驗證的使用者必須是聊天室成員。
必要條件
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 聊天室中的聊天室事件,請按照下列步驟操作:
- 呼叫
list
方法SpaceEvent
資源 - 使用
filter
敬上 ] 欄位。您必須指定至少一個事件類型,而且也能做為篩選依據 日期。如需支援的事件類型清單,請參閱eventType
欄位。 - 與使用者分享 驗證,指定 一或多個授權範圍,可支援要求中的每個事件類型。 最佳做法是選擇仍然最嚴格的範圍 可讓您的應用程式正常運作如要選擇範圍,請參閱 驗證及授權總覽。
在下列程式碼範例中,您可以列出新會員的相關事件,並 聊天室中的訊息。
Python
- 在工作目錄中,建立名為
chat_space_event_list.py
的檔案。 在
chat_space_event_list.py
中加入下列程式碼:"""Lists SpaceEvent resources from the Chat API.""" 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.memberships.readonly", "https://www.googleapis.com/auth/chat.messages.readonly"] # 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().spaceEvents().list( # The space from which to list events. # # Replace SPACE with a space name. # Obtain the space name from the spaces resource of Chat API, # or from a space's URL. parent='spaces/SPACE', # A required filter. Filters and returns events about new memberships and messages filter='event_types:"google.workspace.chat.membership.v1.created" OR event_types:"google.workspace.chat.message.v1.created"' ).execute() # Prints details about the created space events. print(result)
請在程式碼中替換下列內容:
SPACE
:聊天室名稱,您可以從中取得spaces.list
方法 或聊天室網址傳送
在工作目錄中建構並執行範例:
python3 chat_space_event_list.py
Chat API 會傳回
SpaceEvent
項資源
有關新會員和訊息的通知
自訂分頁
視需要傳送下列查詢參數以自訂分頁:
pageSize
:要傳回的SpaceEvent
資源數量上限。 服務傳回的產品數量可能會少於這個值。負值會傳回INVALID_ARGUMENT
個錯誤。pageToken
:從先前的清單空間事件呼叫接收的網頁權杖。 提供這個權杖即可擷取後續網頁。進行分頁時, 篩選器值應與提供網頁符記的呼叫相符。傳送 否則可能會導致非預期的結果