本指南說明如何使用 Google Chat API 的 Space 資源中的 search() 方法,在 Google Workspace 機構中搜尋具名聊天室。
「Space」資源代表使用者和 Chat 應用程式可傳送訊息、分享檔案及協作的空間。聊天室分為以下幾種類型:
- 即時訊息 (DM) 是指兩位使用者之間,或使用者與 Chat 應用程式之間的對話。
- 群組對話是指三位以上使用者與即時通訊應用程式之間的對話。
- 具名聊天室是持續存在的空間,可供使用者傳送訊息、分享檔案及協作。
如果您是 Google Workspace 管理員,並想搜尋貴機構的所有即時通空間 (包括您未加入的私人空間),請參閱「以 Google Workspace 管理員身分搜尋及管理空間」,使用管理員權限 (useAdminAccess=true) 呼叫 API。
如果沒有管理員權限,使用使用者驗證搜尋聊天室時,系統會搜尋已驗證使用者所屬機構中,他們有權存取的具名聊天室 (spaceType of SPACE),例如他們所屬的聊天室。
必要條件
Node.js
- 公司或企業專用 Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Node.js Cloud 用戶端程式庫。
-
為電腦應用程式建立 OAuth 用戶端 ID 憑證。如要在本指南中執行範例,請將憑證儲存為名為
credentials.json的 JSON 檔案,並儲存至本機目錄。
- 選擇支援使用者驗證的授權範圍。
Python
- 公司或企業專用 Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Python Cloud 用戶端程式庫。
-
為電腦應用程式建立 OAuth 用戶端 ID 憑證。如要在本指南中執行範例,請將憑證儲存為名為
credentials.json的 JSON 檔案,並儲存至本機目錄。
- 選擇支援使用者驗證的授權範圍。
Java
- 公司或企業專用 Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 安裝 Java Cloud 用戶端程式庫。
-
為電腦應用程式建立 OAuth 用戶端 ID 憑證。如要在本指南中執行範例,請將憑證儲存為名為
credentials.json的 JSON 檔案,並儲存至本機目錄。
- 選擇支援使用者驗證的授權範圍。
Apps Script
- 公司或企業專用 Google Workspace 帳戶,且可存取 Google Chat。
- 設定環境:
- 建立 Google Cloud 專案。
- 設定 OAuth 同意畫面。
- 啟用及設定 Google Chat API,並為 Chat 應用程式命名、設定圖示和說明。
- 建立獨立的 Apps Script 專案,並開啟進階 Chat 服務。
- 選擇支援使用者驗證的授權範圍。
透過使用者驗證搜尋空間
如要在 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 Script
/**
* 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 會傳回分頁列出的聊天室清單,這些聊天室符合查詢條件,且呼叫 API 的使用者有權存取。