本指南介绍了如何对 Google Chat API 的 SpaceEvent
资源使用 list
方法,列出聊天室中资源的更改。
SpaceEvent
资源表示对目标空间的更改,包括聊天室的子资源,例如消息、回应和成员。如需详细了解支持的事件类型和事件载荷列表,请参阅 SpaceEvent
资源参考文档的 eventType
和 payload
字段。
您最多可以列出请求发出 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
- 在您的工作目录中,创建一个名为
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
:聊天室名称,可通过 Chat API 中的spaces.list
方法或聊天室网址获取。
在您的工作目录中,构建并运行示例:
python3 chat_space_event_list.py
Chat API 会返回有关新成员资格和消息的 SpaceEvent
资源事件列表。
自定义分页
(可选)传递以下查询参数以自定义分页:
pageSize
:要返回的SpaceEvent
资源数量上限。 服务返回的值可能会少于此值。负值会返回INVALID_ARGUMENT
错误。pageToken
:从上一个列表空间事件调用收到的页面令牌。提供此令牌即可检索后续页面。进行分页时,过滤条件值应与提供页面令牌的调用相匹配。传递其他值可能会导致意外结果。