Wyświetlenie listy pokoi

Z tego przewodnika dowiesz się, jak używać metody list() w zasobach Space interfejsu Google Chat API, aby wyświetlić listę pokoi. Listing spaces zwraca posortowaną listę pokoi, którą można filtrować.

SpaceZasób to miejsce, w którym użytkownicy i aplikacje czatu mogą wysyłać wiadomości, udostępniać pliki i współpracować. Istnieje kilka typów pokoi:

  • Czaty to rozmowy między dwoma użytkownikami lub użytkownikiem a aplikacją czatu.
  • Czaty grupowe to rozmowy między 3 lub większą liczbą użytkowników i aplikacji Google Chat.
  • Nazwane pokoje to trwałe miejsca, w których użytkownicy wysyłają wiadomości, udostępniają pliki i współpracują.

Wyświetlanie pokoi z uwierzytelnianiem w aplikacji wyświetla listę pokoi, do których aplikacja Google Chat ma dostęp. Wyświetlanie spaces z Uwierzytelnianie użytkownika wyświetla pokoje, do których uwierzytelniony użytkownik ma dostęp.

Wymagania wstępne

Node.js

Python

Java

Google Apps Script

Wyświetlanie czatu z uwierzytelnianiem użytkowników

Aby wyświetlić listę pokoi w Google Chat, w żądaniu podaj:

W tym przykładzie wymieniono nazwane pokoje (ale nie czaty grupowe ani wiadomości bezpośrednie, które są filtrowane) widoczne dla uwierzytelnionego użytkownika:

Node.js

chat/client-libraries/cloud/list-spaces-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces.readonly'];

// This sample shows how to list spaces with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
    filter: 'space_type = "SPACE"'
  };

  // Make the request
  const pageResult = chatClient.listSpacesAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_spaces_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.spaces.readonly"]

# This sample shows how to list spaces with user credential
def list_spaces_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.ListSpacesRequest(
        # Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
        filter = 'space_type = "SPACE"',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_spaces(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_spaces_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListSpacesRequest;
import com.google.chat.v1.ListSpacesResponse;
import com.google.chat.v1.Space;

// This sample shows how to list spaces with user credential.
public class ListSpacesUserCred{

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.spaces.readonly";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListSpacesRequest.Builder request = ListSpacesRequest.newBuilder()
        // Filter spaces by space type (SPACE or GROUP_CHAT or
        // DIRECT_MESSAGE).
        .setFilter("spaceType = \"SPACE\"")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Space response :
          chatServiceClient.listSpaces(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to list spaces with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listSpacesUserCred() {
  // Initialize request argument(s)
  // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
  const filter = 'space_type = "SPACE"';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.list({
      filter: filter,
      pageSize: 10,
      pageToken: pageToken
    });
    // Handle response pages
    if (responsePage.spaces) {
      responsePage.spaces.forEach((space) => console.log(space));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

Interfejs Chat API zwraca listę pokoi podzieloną na strony.

Wyświetlanie pokoi z uwierzytelnianiem w aplikacji

Aby wyświetlić listę pokoi w Google Chat, w żądaniu podaj:

W tym przykładzie wymieniono nazwane pokoje (ale nie czaty grupowe ani bezpośrednie) widoczne w aplikacji Google Chat:

Node.js

chat/client-libraries/cloud/list-spaces-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to list spaces with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
    filter: 'space_type = "SPACE"'
  };

  // Make the request
  const pageResult = chatClient.listSpacesAsync(request);

  // Handle the response. Iterating over pageResult will yield results and
  // resolve additional pages automatically.
  for await (const response of pageResult) {
    console.log(response);
  }
}

main().catch(console.error);

Python

chat/client-libraries/cloud/list_spaces_app_cred.py
from authentication_utils import create_client_with_app_credentials
from google.apps import chat_v1 as google_chat

# This sample shows how to list spaces with app credential
def list_spaces_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.ListSpacesRequest(
        # Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
        filter = 'space_type = "SPACE"',
        # Number of results that will be returned at once
        page_size = 100
    )

    # Make the request
    page_result = client.list_spaces(request)

    # Handle the response. Iterating over page_result will yield results and
    # resolve additional pages automatically.
    for response in page_result:
        print(response)

list_spaces_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListSpacesAppCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListSpacesRequest;
import com.google.chat.v1.ListSpacesResponse;
import com.google.chat.v1.Space;

// This sample shows how to list spaces with app credential.
public class ListSpacesAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      ListSpacesRequest.Builder request = ListSpacesRequest.newBuilder()
        // Filter spaces by space type (SPACE or GROUP_CHAT or
        // DIRECT_MESSAGE).
        .setFilter("spaceType = \"SPACE\"")
        // Number of results that will be returned at once.
        .setPageSize(10);

      // Iterate over results and resolve additional pages automatically.
      for (Space response :
          chatServiceClient.listSpaces(request.build()).iterateAll()) {
        System.out.println(JsonFormat.printer().print(response));
      }
    }
  }
}

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to list spaces with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function listSpacesAppCred() {
  // Initialize request argument(s)
  // Filter spaces by space type (SPACE or GROUP_CHAT or DIRECT_MESSAGE)
  const filter = 'space_type = "SPACE"';

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.list({
      filter: filter,
      pageSize: 10,
      pageToken: pageToken
    }, getHeaderWithAppCredentials());
    // Handle response pages
    if (responsePage.spaces) {
      responsePage.spaces.forEach((space) => console.log(space));
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

Interfejs Chat API zwraca listę pokoi podzieloną na strony.

Dostosowywanie podziału na strony lub filtrowanie listy

Aby wyświetlić listę pokoi w Google Chat, prześlij te opcjonalne parametry zapytania, aby dostosować podział na strony lub filtrować wyświetlane pokoje:

  • pageSize: maksymalna liczba miejsc do zwrócenia. Usługa może zwrócić mniej niż tę wartość. Jeśli nie zostanie podany, zwracane jest maksymalnie 100 miejsc. Maksymalna wartość to 1000; wartości wyższe niż 1000 są automatycznie zmieniane na 1000.
  • pageToken: token strony otrzymany z poprzedniego wywołania listy. Podaj ten token, aby pobrać kolejną stronę. Podczas podziału na strony wartość filtra powinna odpowiadać wywołaniu, które dostarczyło token strony. Podanie innej wartości może spowodować nieoczekiwane wyniki.
  • filter: filtr zapytania. Szczegółowe informacje o obsługiwanych zapytaniach znajdziesz w dokumentacji ListSpacesRequest.