列出 Google Chat 聊天室中的活动

本指南介绍了如何使用 Google Chat API 的 SpaceEvent 资源中的 list() 方法列出空间中资源的更改。

SpaceEvent 资源表示对目标聊天室的更改,包括聊天室的子资源,例如消息、回应和成员资格。如需详细了解支持的事件类型和事件载荷列表,请参阅 SpaceEvent 资源参考文档的 eventTypepayload 字段。

您可以列出请求时间之前最多 28 天的活动。服务器会返回包含受影响资源最新版本的事件。例如,如果您列出有关新聊天室成员的事件,服务器会返回包含最新成员资格详细信息的 Membership 资源。如果新会员在请求的时间段内被移除,则事件载荷包含空的 Membership 资源。

如需列出聊天室中的活动,已通过身份验证的用户或 Chat 应用必须是相应聊天室的成员。

前提条件

Node.js

Python

列出会议室活动(用户身份验证)

如需列出 Chat 聊天室中的聊天室活动,请在请求中传递以下内容:

  • 指定一个或多个授权范围,以支持请求中的每种事件类型。最佳实践是,选择最严格的范围,同时仍允许您的应用正常运行。如需选择范围,请参阅身份验证和授权概览

  • 调用 ListSpaceEvents() 方法,并传递要列出的事件类型的 filter。 您必须至少指定一种事件类型,也可以按日期进行过滤。 如需查看支持的事件类型列表,请参阅 SpaceEvent 资源eventType 字段参考文档。

以下示例列出了有关新会员和聊天室中消息的事件:

Node.js

chat/client-libraries/cloud/list-space-events-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

// Authorization scopes based on the event types
const USER_AUTH_OAUTH_SCOPES = [
  'https://www.googleapis.com/auth/chat.memberships.readonly',
  'https://www.googleapis.com/auth/chat.messages.readonly',
];

// This sample shows how to list space events with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(
    USER_AUTH_OAUTH_SCOPES,
  );

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME',
    // A required filter. Filters events about new memberships and messages.
    filter:
      'eventTypes:"google.workspace.chat.membership.v1.created" OR eventTypes:"google.workspace.chat.message.v1.created"',
  };

  // Make the request
  const pageResult = chatClient.listSpaceEventsAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

await main();

如需运行此示例,请将 SPACE_NAME 替换为相应空间的 name 中的 ID。 您可以通过调用 ListSpaces() 方法或从空间的网址中获取 ID。

Chat API 会返回有关新会员和消息的分页聊天室事件列表

列出聊天室事件(Chat 应用身份验证)

应用身份验证需要管理员一次性批准

如需使用 应用身份验证Chat REST API 列出聊天室中的聊天室事件,请在请求中传递以下内容:

  • 指定一个或多个授权范围,以支持请求中的每种事件类型。最佳实践是,选择最严格的范围,同时仍允许您的应用正常运行。如需详细了解如何选择范围,请参阅身份验证和授权概览
    • https://www.googleapis.com/auth/chat.app.memberships
    • https://www.googleapis.com/auth/chat.app.messages.readonly
    • https://www.googleapis.com/auth/chat.app.spaces
  • spaceEvents 资源调用 list 方法
  • 传递要列出消息的聊天室的 name
  • 传递 filter 以查询特定事件类型。

创建 API 密钥

如需调用开发者预览版 API 方法,您必须使用非公开的开发者预览版 API 发现文档。如需对请求进行身份验证,您必须传递 API 密钥。

如需创建 API 密钥,请打开应用的 Google Cloud 项目并执行以下操作:

  1. 在 Google Cloud 控制台中,依次前往菜单 > API 和服务 > 凭据

    进入“凭据”页面

  2. 依次点击创建凭据 > API 密钥
  3. 系统会显示您的新 API 密钥。
    • 点击“复制”图标 即可复制 API 密钥,以便在应用的代码中使用。您还可以在项目的凭据的“API 密钥”部分中找到 API 密钥。
    • 为防止未经授权的使用,我们建议您限制 API 密钥可用于哪些位置和 API。如需了解详情,请参阅添加 API 限制

编写调用 Chat API 的脚本

以下是如何使用应用身份验证Chat REST API 列出会议室事件:

Python

  1. 在工作目录中,创建一个名为 chat_spaceevents_list_app.py 的文件。
  2. chat_spaceevents_list_app.py 中添加以下代码:

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # Set authorization scopes based on the
    # event type. For example, if you are getting a space event
    # about a new membership, use the `chat.app.memberships.readonly` scope.
    #
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.memberships",
              "https://www.googleapis.com/auth/chat.app.messages.readonly",
              "https://www.googleapis.com/auth/chat.app.spaces"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists space events from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().spaceEvents().list(
    
            # The space to list events from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME',
    
            # A required filter. Filters events by event type.
            #
            # Update this filter to match your requirements.
            filter='eventTypes:"google.workspace.chat.message.v1.created"'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,替换以下内容:

    • API_KEY:您创建的用于构建 Chat API 服务端点的 API 密钥。
    • SPACE_NAME:聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或从聊天室的网址中获取。
  4. 在工作目录中,构建并运行示例:

    python3 chat_spaceevents_list_app.py

Chat API 会返回有关新会员和消息的分页聊天室事件列表