列出 Google Chat 聊天室中的事件

本指南說明如何使用 Google Chat API 的 SpaceEvent 資源中的 list 方法,列出聊天室中資源的變更。

SpaceEvent 資源代表目標空間的變更,包括訊息、回應和成員資格的子項資源。如要進一步瞭解支援的事件類型和事件酬載清單,請參閱 SpaceEvent 資源參考說明文件的 eventTypepayload 欄位。

您可以列出要求時間前 28 天內的事件。伺服器會傳回事件,內含受影響資源的最新版本。例如,如果您列出新聊天室成員的相關事件,伺服器會傳回 Membership 資源,其中包含最新成員詳細資料。如果在要求的期間移除新成員,事件酬載會包含空白的 Membership 資源。

如要呼叫這個方法,您必須使用使用者驗證。如要列出聊天室中的事件,通過驗證的使用者必須是聊天室成員。

必要條件

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 應用程式設定授權。列出 SpaceEvent 資源支援下列驗證方法:

列出聊天室事件

如要列出 Chat 聊天室中的聊天室事件,請按照下列步驟操作:

  • 呼叫 SpaceEvent 資源上的 list 方法
  • 使用 filter 欄位指定要列出的事件類型。您必須至少指定一個事件類型,也可以依日期篩選。如需支援的事件類型清單,請參閱 eventType 欄位
  • 透過使用者驗證功能,請指定一或多個授權範圍,支援要求中的每種事件類型。最佳做法是選擇最嚴格的範圍,確保應用程式仍可正常運作。如要選擇範圍,請參閱驗證和授權總覽

以下程式碼範例將列出聊天室中新成員和訊息的相關事件。

Python

  1. 在工作目錄中,建立名為 chat_space_event_list.py 的檔案。
  2. 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)
    
  3. 在程式碼中,替換以下內容:

    • SPACE:聊天室名稱,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_space_event_list.py
    

Chat API 會傳回與新成員和訊息相關的 SpaceEvent 資源事件清單。

自訂分頁

您也可以選擇傳遞下列查詢參數,以自訂分頁:

  • pageSize:要傳回的 SpaceEvent 資源數量上限。服務傳回的產品數量可能會少於這個值。負值會傳回 INVALID_ARGUMENT 錯誤。
  • pageToken:從先前的清單聊天室事件呼叫收到的網頁權杖。提供這個權杖以擷取後續網頁。進行分頁時,篩選器值應與提供網頁權杖的呼叫相符。傳送不同的值可能會導致非預期的結果。