스페이스 검색

이 가이드에서는 Google Chat API의 Space 리소스에서 search() 메서드를 사용하여 Google Workspace 조직에서 이름이 지정된 스페이스를 검색하는 방법을 설명합니다.

Space 리소스 는 사용자와 Chat 앱이 메시지를 보내고, 파일을 공유하고, 공동작업할 수 있는 공간을 나타냅니다. 스페이스에는 여러 유형이 있습니다.

  • 채팅 메시지 (DM)는 두 사용자 또는 사용자와 Chat 앱 간의 대화입니다.
  • 그룹 채팅은 3명 이상의 사용자와 Chat 앱 간의 대화입니다.
  • 이름이 지정된 스페이스는 사용자가 메시지를 보내고, 파일을 공유하고, 공동작업하는 영구적인 공간입니다.

Google Workspace 관리자이고 가입하지 않은 비공개 스페이스를 포함하여 조직의 모든 스페이스를 검색하려면 Google Workspace 관리자로 스페이스 검색 및 관리를 참고하여 관리자 권한 (useAdminAccess=true)으로 API를 호출하세요.

관리자 권한 없이 사용자 인증으로 스페이스를 검색할 때 메서드는 인증된 사용자가 액세스할 수 있는 이름이 지정된 스페이스(spaceTypeSPACE)를 검색합니다(예: 조직 내에서 사용자가 멤버로 속한 스페이스).

기본 요건

Node.js

Python

자바

Apps Script

사용자 인증으로 스페이스 검색

관리자 권한 없이 Google Chat에서 스페이스를 검색하려면 요청에 다음을 전달합니다.

  • 사용자 인증을 사용하여 chat.spaces.readonly 또는 chat.spaces 승인 범위를 지정합니다.
  • search() 메서드를 Space 리소스에서 호출합니다.
  • useAdminAccessfalse로 설정하거나 매개변수를 생략합니다.
  • 검색 query 매개변수를 지정하여 결과를 필터링합니다.
    • spaceType = "SPACE" - query가 지정된 경우 필수이며 지원되는 유일한 값은 SPACE입니다.
    • displayName - HAS (:) 연산자를 사용하여 스페이스 표시 이름으로 필터링합니다. 예를 들어 displayName:"Project"입니다. 일치시킬 텍스트는 토큰화되고 각 토큰은 스페이스의 displayName에 있는 하위 문자열로 대소문자를 구분하지 않고 독립적으로 접두사 일치됩니다. 참고: useAdminAccessfalse이면 의미 있는 결과를 가져오기 위해 쿼리에 displayName이 필요합니다. 그렇지 않으면 메서드가 빈 응답을 반환합니다.
    • externalUserAllowed - 필요에 따라 스페이스에서 외부 참석자가 허용되는지 여부 (true 또는 false)로 필터링합니다.
  • 필요에 따라 pageSize를 지정하여 반환할 최대 스페이스 수 (최대 1000)를 제한하거나 pageToken을 지정하여 결과의 후속 페이지를 가져옵니다.
  • 필요에 따라 orderBy을 지정하여 검색 결과를 정렬합니다 (createTime desc 또는 relevance desc). 참고: relevance descGoogle Workspace 개발자 미리보기 프로그램을 통해 사용할 수 있습니다.

쿼리의 여러 필드에서 AND 연산자만 지원됩니다. 예를 들어 spaceType = "SPACE" AND displayName:"Hello" AND externalUserAllowed = "true"입니다. displayNameexternalUserAllowed 내에서 여러 기준을 일치시키려면 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()

자바

/**
 * 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는 쿼리와 일치하고 호출 사용자가 액세스할 수 있는 스페이스의 페이지로 나뉜 목록을 반환합니다.