スペースを検索する

このガイドでは、Google Chat API の Space リソースsearch() メソッドを使用して、Google Workspace 組織内の名前付きスペースを検索する方法について説明します。

Space リソースは、ユーザーと Chat 用アプリがメッセージの送信、ファイルの共有、共同編集を行える場所を表します。スペースにはいくつかの種類があります。

  • ダイレクト メッセージ(DM)は、2 人のユーザー間、またはユーザーと Chat 用アプリ間の会話です。
  • グループ チャットは、3 人以上のユーザーと Chat 用アプリ間の会話です。
  • 名前付きスペースは、ユーザーがメッセージの送信、ファイルの共有、共同作業を行うための永続的な場所です。

Google Workspace 管理者で、参加していない非公開スペースを含む組織内のすべてのスペースを検索する場合は、Google Workspace 管理者としてスペースを検索して管理するを参照して、管理者権限(useAdminAccess=true)で API を呼び出してください。

管理者権限のないユーザー認証でスペースを検索する場合、このメソッドは、認証されたユーザーがアクセスできる名前付きスペース(SPACEspaceType)(組織内のメンバーであるスペースなど)を検索します。

前提条件

Node.js

Python

Java

Apps Script

ユーザー認証を使用してスペースを検索する

管理者権限なしで Google Chat のスペースを検索するには、リクエストで次の値を渡します。

  • ユーザー認証では、chat.spaces.readonly または chat.spaces の認可スコープを指定します。
  • Space リソースで search() メソッドを呼び出します。
  • 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 desc は、Google 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()

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 は、クエリに一致し、呼び出し元のユーザーがアクセスできるスペースのページ分割されたリストを返します。