本页面介绍如何使用 subscriptions.list()
方法列出 Google Workspace 订阅。
当您使用用户身份验证调用此方法时,该方法会返回用户授权的订阅列表。使用应用身份验证时,该方法可以返回包含应用的所有订阅的列表。
前提条件
Apps 脚本
- Google Workspace 订阅。如需创建订阅,请参阅创建订阅。
需要用户通过一个或多个支持订阅的所有事件类型的范围进行身份验证。
- Apps 脚本项目:
- 使用您的 Google Cloud 项目,而不是 Apps 脚本自动创建的默认项目。
- 对于您为配置 OAuth 权限请求页面而添加的所有范围,您还必须将这些范围添加到 Apps 脚本项目中的
appsscript.json
文件中。 例如,如果您指定了chat.messages
范围,请添加以下内容: - 启用
Google Workspace Events
高级服务。
"oauthScopes": [ "https://www.googleapis.com/auth/chat.messages" ]
Python
- Python 3.6 或更高版本
- pip 软件包管理工具
- 适用于 Python 的最新 Google 客户端库。如需安装或更新这些软件包,请在命令行界面中运行以下命令:
pip3 install --upgrade google-api-python-client google-auth-oauthlib
- Google Workspace 订阅。如需创建订阅,请参阅创建订阅。
需要身份验证:
- 对于用户身份验证,需要一个支持订阅的至少一种事件类型的范围。如需确定范围,请参阅按事件类型划分的范围。
- 对于应用身份验证,需要
chat.bot
范围(仅限 Google Chat 应用)。
列出用户授权的订阅
如需列出订阅,您必须按至少一种事件类型进行过滤。您还可以按一个或多个目标资源过滤查询。如需了解支持的查询过滤条件,请参阅 list()
方法文档。
以下代码示例返回按事件类型和目标资源过滤的 Subscription
对象数组。当以用户身份进行身份验证时,该方法仅返回用户授权应用创建的订阅列表。
如需列出指定事件类型和目标资源的订阅,请执行以下操作:
Apps 脚本
在您的 Apps 脚本项目中,创建一个名为
listSubscriptions
的新脚本文件,并添加以下代码:function listSubscriptions() { // Filter for event type (required). const eventType = 'EVENT_TYPE'; // Filter for target resource (optional). const targetResource = 'TARGET_RESOURCE'; const filter = `event_types:"${eventType}" AND target_resource="${targetResource}"` // Call the Workspace Events API using the advanced service. const response = WorkspaceEvents.Subscriptions.list({ filter }); console.log(response); }
替换以下内容:
如需列出订阅,请在您的 Apps 脚本项目中运行函数
listSubscriptions
。
Python
在工作目录中,创建一个名为
list_subscriptions.py
的文件并添加以下代码:"""List subscriptions.""" from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build # Specify required scopes. SCOPES = ['SCOPE'] # Authenticate with Google Workspace and get user authentication. flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES) CREDENTIALS = flow.run_local_server() # Call the Workspace Events API using the service endpoint. service = build( 'workspaceevents', 'v1', credentials=CREDENTIALS, ) # Filter for event type (required). EVENT_TYPE = 'EVENT_TYPE' # Filter for target resource (optional). TARGET_RESOURCE = 'TARGET_RESOURCE' FILTER = f'event_types:"{EVENT_TYPE}" AND target_resource="{TARGET_RESOURCE}"' response = service.subscriptions().list(filter=FILTER).execute() print(response)
替换以下内容:
SCOPE
:支持订阅中的至少一种事件类型的 OAuth 范围。例如,如果您的订阅接收到更新后的 Chat 聊天室的事件,则为https://www.googleapis.com/auth/chat.spaces.readonly
。EVENT_TYPE
:根据 CloudEvents 规范设置格式的事件类型。例如,如需过滤订阅,以接收有关 Google Chat 聊天室新会员的事件,请使用google.workspace.chat.message.v1.created
。TARGET_RESOURCE
:目标资源,格式为完整资源名称。例如,如需按 Google Chat 聊天室的订阅过滤,请使用//chat.googleapis.com/spaces/SPACE_ID
,其中spaces/SPACE_ID
表示Space
资源的name
字段。
在工作目录中,确保您已存储 OAuth 客户端 ID 凭据,并将该文件命名为
credentials.json
。此代码示例使用此 JSON 文件向 Google Workspace 进行身份验证并获取用户凭据。有关说明,请参阅创建 OAuth 客户端 ID 凭证。如需列出订阅,请在终端中运行以下命令:
python3 list_subscriptions.py
Google Workspace Events API 会返回一个分页的 Subscription
对象数组,其中包含与查询过滤条件匹配的事件。