获取有关 Google Chat 聊天室活动的详细信息

本指南将介绍如何使用 get 方法已开启 SpaceEvent 资源 用于从 Google Chat 聊天室获取活动详细信息的 Google Chat API。

SpaceEvent 资源表示对聊天室或其子级所做的更改 例如消息、回应和成员资格。学习内容 支持的事件类型,请参阅eventType字段 SpaceEvent 资源 参考文档。

您最多可以比请求时间提前 28 天请求活动。活动 包含发生更改的资源的最新版本。例如,如果 您请求了关于新消息的活动,但该消息后来更新了, 服务器会在事件载荷中返回更新后的 Message 资源。

要调用此方法,您必须使用 user 身份验证。要获得 则经过身份验证的用户必须是该活动所在聊天室的成员 错误。

前提条件

Python

  • Python 3.6 或更高版本
  • pip 软件包管理工具
  • 最新的 Google 客户端库。若要安装或更新这些应用 在命令行界面中运行以下命令:
    pip3 install --upgrade google-api-python-client google-auth-oauthlib
    

获取聊天室活动的详细信息

如需在 Google Chat 中获取有关SpaceEvent的详细信息,请执行以下操作:

  • 调用 get 方法SpaceEvent 资源
  • 传递 SpaceEventname 即可获取。获取 SpaceEvent 名称 来源:SpaceEvent 资源 Google Chat。
  • 用户:<ph type="x-smartling-placeholder"></ph> 身份验证,指定 支持您请求中的事件类型的授权范围。作为 最佳实践:选择仍然允许您的应用访问的最严格范围 才能正常运行。

通过以下方式获取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:聊天室名称,您可以从中获取 spaces.list 方法 或通过聊天室网址发送。
    • SPACE_EVENT:聊天室的名称 事件,您可以从 spaces.spaceEvents.list 方法
  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_space_event_get.py
    

Chat API 会返回 SpaceEvent 活动详情