Tìm kiếm không gian

Hướng dẫn này giải thích cách sử dụng phương thức search() trên tài nguyên Space của Google Chat API để tìm kiếm các không gian có tên trong một tổ chức Google Workspace.

Tài nguyên Space đại diện cho một nơi mà mọi người và các ứng dụng Chat có thể gửi tin nhắn, chia sẻ tệp và cộng tác. Có một số loại không gian như sau:

  • Tin nhắn trực tiếp (DM) là cuộc trò chuyện giữa hai người dùng hoặc giữa một người dùng và một ứng dụng Chat.
  • Cuộc trò chuyện nhóm là cuộc trò chuyện giữa 3 người dùng trở lên và các ứng dụng Chat.
  • Không gian có tên là những nơi ổn định để mọi người gửi tin nhắn, chia sẻ tệp và cộng tác.

Nếu bạn là quản trị viên Google Workspace và muốn tìm kiếm trên tất cả các không gian trong tổ chức của mình, kể cả những không gian riêng tư mà bạn chưa tham gia, hãy xem bài viết Tìm kiếm và quản lý không gian với tư cách là quản trị viên Google Workspace để gọi API bằng đặc quyền quản trị viên (useAdminAccess=true).

Khi tìm kiếm không gian có xác thực người dùng mà không có đặc quyền quản trị, phương thức này sẽ tìm kiếm các không gian có tên (spaceType của SPACE) mà người dùng đã xác thực có quyền truy cập, chẳng hạn như các không gian mà họ là thành viên, trong tổ chức của họ.

Điều kiện tiên quyết

Node.js

Python

Java

Apps Script

Tìm kiếm không gian có xác thực người dùng

Để tìm kiếm không gian trong Google Chat mà không có đặc quyền quản trị, hãy truyền các thông tin sau trong yêu cầu của bạn:

  • Với xác thực người dùng, hãy chỉ định phạm vi uỷ quyền chat.spaces.readonly hoặc chat.spaces.
  • Gọi phương thức search() trên tài nguyên Space.
  • Đặt useAdminAccess thành false (hoặc bỏ qua tham số).
  • Chỉ định các tham số tìm kiếm query để lọc kết quả:
    • spaceType = "SPACE" – bắt buộc khi bạn chỉ định query và giá trị được hỗ trợ duy nhất là SPACE.
    • displayName – lọc theo tên hiển thị của không gian bằng toán tử HAS (:). Ví dụ: displayName:"Project". Văn bản cần khớp được mã hoá và mỗi mã thông báo được khớp theo tiền tố một cách độc lập và không phân biệt chữ hoa chữ thường dưới dạng chuỗi con ở bất kỳ vị trí nào trong displayName của không gian. Lưu ý: Khi useAdminAccessfalse, bạn phải có displayName trong truy vấn để truy xuất kết quả có ý nghĩa; nếu không, phương thức này sẽ trả về một phản hồi trống.
    • externalUserAllowed – lọc (không bắt buộc) theo việc khách bên ngoài có được phép tham gia không gian hay không (true hoặc false).
  • Nếu muốn, hãy chỉ định pageSize để giới hạn số lượng không gian tối đa cần trả về (tối đa là 1000) hoặc pageToken để truy xuất các trang kết quả tiếp theo.
  • Bạn có thể chỉ định orderBy để sắp xếp kết quả tìm kiếm (createTime desc hoặc relevance desc). Lưu ý: Bạn có thể sử dụng relevance desc thông qua Chương trình Bản dùng thử cho nhà phát triển của Google Workspace.

Trong các trường khác nhau trong truy vấn, chỉ toán tử AND được hỗ trợ. Ví dụ: spaceType = "SPACE" AND displayName:"Hello" AND externalUserAllowed = "true". Trong displayNameexternalUserAllowed, các toán tử OR được hỗ trợ nếu bạn muốn so khớp nhiều tiêu chí.

Ví dụ sau đây tìm kiếm các không gian có tên chứa "Dự án" trong tên hiển thị:

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 trả về một danh sách không gian được phân trang khớp với truy vấn và người dùng gọi có thể truy cập.