取得 Google Chat 聊天室活動的詳細資料

本指南說明如何在 Google Chat API 的 SpaceEvent 資源中使用 get 方法,取得 Google Chat 聊天室中的事件詳細資料。

SpaceEvent 資源代表聊天室或子項資源的變更,例如訊息、回應和成員資格。如要瞭解支援的事件類型,請參閱 SpaceEvent 資源參考說明文件的 eventType 欄位。

您可以要求要求事件發生前 28 天內的事件。該事件會包含變更的資源最新版本。舉例來說,如果您要求的事件與新訊息相關,但訊息後來更新,伺服器會在事件酬載中傳回更新後的 Message 資源。

如要呼叫這個方法,您必須使用使用者驗證。如要取得事件,已驗證的使用者必須是事件發生空間的成員。

必要條件

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 應用程式設定授權。如要取得聊天室事件,您必須使用支援該事件類型的範圍使用者驗證。如要選擇範圍,請參閱驗證和授權總覽

取得聊天室活動的詳細資料

如要在 Google Chat 中取得「SpaceEvent」的詳細資料,請按照下列步驟操作:

  • 呼叫 SpaceEvent 資源上的 get 方法
  • 傳遞 SpaceEventname,即可取得。從 Google Chat 的 SpaceEvent 資源取得 SpaceEvent 名稱。
  • 使用使用者驗證功能,指定支援要求中事件類型的授權範圍。最佳做法是選擇最嚴格的範圍,確保應用程式仍可正常運作。

以下說明如何使用使用者驗證機制取得 SpaceEvent

Python

  1. 在工作目錄中,建立名為 chat_space_event_get.py 的檔案。
  2. chat_space_event_get.py 中加入下列程式碼:

    """Gets a SpaceEvent resource 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 = ['SCOPE']
    
    # 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()
        .get(
            # The space event 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 SPACE_EVENT with a SpaceEvent name.
            # Obtain the spaceEvent name from the SpaceEvent resource of
            # Chat API.
            name='spaces/SPACE/spaceEvents/SPACE_EVENT'
        )
        .execute()
    )
    
    # Prints details about the created spaceEvent.
    print(result)
    
  3. 在程式碼中,替換以下內容:

    • SCOPE:以事件類型為基礎的授權範圍。舉例來說,如果您要取得有關新成員的太空事件,請使用 chat.memberships.readonly 範圍,格式為 https://www.googleapis.com/auth/chat.memberships.readonly。您可以從 spaces.spaceEvents.list 方法取得事件類型。如要瞭解如何使用此方法,請參閱「列出聊天室中的事件」。
    • SPACE:聊天室名稱,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
    • SPACE_EVENT:聊天室事件的名稱,可透過 spaces.spaceEvents.list 方法取得。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_space_event_get.py
    

Chat API 會傳回 SpaceEvent 的執行個體,其中包含事件的詳細資料。