本指南介绍了如何对 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
方法。 - 传递
SpaceEvent
的name
即可获取。从 Google Chat 的SpaceEvent
资源获取SpaceEvent
名称。 - 使用用户身份验证时,请指定支持请求中的事件类型的授权范围。最佳实践是选择限制性最强的作用域,确保应用仍能正常运行。
通过用户身份验证获取 SpaceEvent
的方法如下:
Python
- 在您的工作目录中,创建一个名为
chat_space_event_get.py
的文件。 在
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)
在代码中,替换以下内容:
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
方法获取。
在您的工作目录中,构建并运行示例:
python3 chat_space_event_get.py
Chat API 会返回 SpaceEvent
的实例,其中包含有关事件的详细信息。