本指南介绍了如何使用 Google Chat API 的 Space 资源中的 search() 方法在 Google Workspace 组织中搜索已命名的空间。
Space 资源表示用户和 Chat 应用可以在其中发送消息、共享文件和协作处理事务。聊天室有多种类型:
- 私信 (DM) 是两位用户之间或用户与 Chat 应用之间的对话。
- 群聊是指三位或更多用户与聊天应用之间的对话。
- 命名聊天室是持久存在的聊天室,用户可以在其中发送消息、分享文件和协作。
如果您是 Google Workspace 管理员,并且想要搜索组织中的所有聊天室(包括您未加入的私密聊天室),请参阅以 Google Workspace 管理员身份搜索和管理聊天室,以使用管理员权限 (useAdminAccess=true) 调用 API。
当搜索具有用户身份验证且没有管理员权限的聊天室时,该方法会搜索经过身份验证的用户有权访问的命名聊天室(SPACE 的 spaceType),例如其组织中用户加入的聊天室。
前提条件
Node.js
- 拥有可访问 Google Chat 的 Google Workspace 商务版或企业版账号。
- 设置环境:
- 创建 Google Cloud 项目。
- 配置 OAuth 权限请求页面。
- 启用并配置 Google Chat API,为您的 Chat 应用指定名称、图标和说明。
- 安装 Node.js Cloud 客户端库。
- 为桌面应用
创建 OAuth 客户端 ID 凭据。如需运行本指南中的示例,请将凭据保存为名为
credentials.json的 JSON 文件,并将其保存到本地目录。
- 选择支持用户身份验证的授权范围。
Python
- 拥有可访问 Google Chat 的 Google Workspace 商务版或企业版账号。
- 设置环境:
- 创建 Google Cloud 项目。
- 配置 OAuth 权限请求页面。
- 启用并配置 Google Chat API,为您的 Chat 应用指定名称、图标和说明。
- 安装 Python Cloud 客户端库。
- 为桌面应用
创建 OAuth 客户端 ID 凭据。如需运行本指南中的示例,请将凭据保存为名为
credentials.json的 JSON 文件,并将其保存到本地目录。
- 选择支持用户身份验证的授权范围。
Java
- 拥有可访问 Google Chat 的 Google Workspace 商务版或企业版账号。
- 设置环境:
- 创建 Google Cloud 项目。
- 配置 OAuth 权限请求页面。
- 启用并配置 Google Chat API,为您的 Chat 应用指定名称、图标和说明。
- 安装 Java Cloud 客户端库。
- 为桌面应用
创建 OAuth 客户端 ID 凭据。如需运行本指南中的示例,请将凭据保存为名为
credentials.json的 JSON 文件,并将其保存到本地目录。
- 选择支持用户身份验证的授权范围。
Apps 脚本
- 拥有可访问 Google Chat 的 Google Workspace 商务版或企业版账号。
- 设置环境:
- 创建 Google Cloud 项目。
- 配置 OAuth 权限请求页面。
- 启用并配置 Google Chat API,为您的 Chat 应用指定名称、图标和说明。
- 创建独立的 Apps 脚本项目,然后启用高级聊天服务。
- 选择支持用户身份验证的授权范围。
搜索需要用户身份验证的会议室
如需在没有管理员权限的情况下在 Google Chat 中搜索聊天室,请在请求中传递以下内容:
- 使用用户身份验证时,请指定
chat.spaces.readonly或chat.spaces授权范围。 - 对
Space资源调用search()方法。 - 将
useAdminAccess设置为false(或省略该参数)。 - 指定搜索
query参数以过滤结果:spaceType = "SPACE"- 如果指定了query,则为必需参数;唯一支持的值为SPACE。displayName- 使用HAS(:) 运算符按会议室显示名称过滤。例如displayName:"Project"。要匹配的文本会经过词元化处理,每个词元都会以不区分大小写的方式独立进行前缀匹配,作为相应空间displayName中的任意子字符串。注意:当useAdminAccess为false时,您需要在查询中指定displayName才能检索到有意义的结果;否则,该方法会返回空响应。externalUserAllowed:可选,用于按聊天室是否允许外部嘉宾加入进行过滤(true或false)。
- 您可以选择指定
pageSize来限制要返回的会议室数量上限(最多为1000),也可以指定pageToken来检索后续页面的结果。 - (可选)指定
orderBy以对搜索结果进行排序(createTime desc或relevance desc)。注意:relevance desc可通过 Google Workspace 开发者预览版计划使用。
在查询的不同字段中,仅支持 AND 运算符。例如:spaceType = "SPACE" AND displayName:"Hello" AND externalUserAllowed = "true"。在 displayName 和 externalUserAllowed 中,如果您想匹配多个条件,则支持 OR 运算符。
以下示例搜索显示名称中包含“Project”的命名空间:
Node.js
/**
* This sample shows how to search for spaces without administrator privileges.
*
* It relies on the @google-apps/chat npm package.
*/
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
const {ChatServiceClient} = require('@google-apps/chat');
const {auth} = require('google-auth-library');
async function main() {
// Create a client
const chatClient = new ChatServiceClient({
authClient: await auth.getClient({
scopes: ['https://www.googleapis.com/auth/chat.spaces.readonly']
})
});
// Initialize request arguments.
// When useAdminAccess is false, spaceType and displayName are required in query.
const request = {
query: 'spaceType = "SPACE" AND displayName:"Project"',
useAdminAccess: false
};
// Call the API and iterate over the paginated response
const iterable = chatClient.searchSpacesAsync(request);
for await (const result of iterable) {
console.log('Found space:', result.space.displayName, result.space.name);
}
}
main().catch(console.error);
Python
"""
This sample shows how to search for spaces without administrator privileges.
"""
from google.apps import chat_v1
import google.auth
# Read the documentation for more details:
# https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
def search_spaces():
# Create a client
scopes = ["https://www.googleapis.com/auth/chat.spaces.readonly"]
credentials, _ = google.auth.default(scopes=scopes)
client = chat_v1.ChatServiceClient(credentials=credentials)
# Initialize request arguments.
# When use_admin_access is False, space_type and display_name are required in query.
request = chat_v1.SearchSpacesRequest(
query='spaceType = "SPACE" AND displayName:"Project"',
use_admin_access=False
)
# Make the request and iterate over the paginated results.
page_result = client.search_spaces(request)
for result in page_result.results:
print(f"Found space: {result.space.display_name} ({result.space.name})")
if __name__ == "__main__":
search_spaces()
Java
/**
* This sample shows how to search for spaces without administrator privileges.
*/
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ChatServiceClient.SearchSpacesPagedResponse;
import com.google.chat.v1.SearchSpacesRequest;
import com.google.chat.v1.SearchSpaceResult;
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
public class SearchSpaces {
public static void main(String[] args) throws Exception {
// See https://github.com/googleworkspace/java-samples/blob/main/chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/AuthenticationUtils.java
// for an example of how to authenticate the request.
try (ChatServiceClient chatServiceClient = AuthenticationUtils.createClientWithUserCredentials(
ImmutableList.of("https://www.googleapis.com/auth/chat.spaces.readonly"))) {
SearchSpacesRequest request = SearchSpacesRequest.newBuilder()
.setQuery("spaceType = \"SPACE\" AND displayName:\"Project\"")
.setUseAdminAccess(false)
.build();
SearchSpacesPagedResponse response = chatServiceClient.searchSpaces(request);
for (SearchSpaceResult result : response.iterateAll()) {
System.out.printf("Found space: %s (%s)\n", result.space.getDisplayName(), result.space.getName());
}
}
}
}
Apps 脚本
/**
* This sample shows how to search for spaces without administrator privileges.
*/
// Read the documentation for more details:
// https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces/search
function searchSpaces() {
try {
// Call the API
// When useAdminAccess is false, spaceType and displayName are required in query.
const response = Chat.Spaces.search({
query: 'spaceType = "SPACE" AND displayName:"Project"',
useAdminAccess: false
});
if (response.results && response.results.length > 0) {
response.results.forEach(result => {
console.log('Found space: %s (%s)', result.space.displayName, result.space.name);
});
} else {
console.log('No matching spaces found.');
}
} catch (err) {
console.log('Failed to search spaces: ' + err.message);
}
}
Chat API 会返回与查询匹配且调用用户可访问的分页空间列表。