Wyświetlenie listy wiadomości

Ten przewodnik wyjaśnia, jak używać metody list() w zasobie Message interfejsu Google Chat API, aby wyświetlić podzieloną na strony i filtrowaną listę wiadomości w pokoju.

W interfejsie Chat API wiadomość w Google Chat jest reprezentowana przez Message zasób. Użytkownicy Google Chat mogą wysyłać tylko wiadomości tekstowe, ale aplikacje Google Chat mogą korzystać z wielu innych funkcji przesyłania wiadomości, w tym wyświetlać statyczne lub interaktywne interfejsy użytkownika, zbierać informacje od użytkowników i dostarczać wiadomości prywatne. Więcej informacji o funkcjach przesyłania wiadomości dostępnych w interfejsie Chat API znajdziesz w przeglądzie wiadomości w Google Chat.

Wymagania wstępne

Node.js

Python

Java

Google Apps Script

Wyświetlanie wiadomości jako użytkownik

Aby wyświetlić listę wiadomości z uwierzytelnianiem użytkownika, w żądaniu przekaż te informacje:

  • Określ zakres autoryzacji chat.messages.readonly lub chat.messages.
  • Wywołaj metodę ListMessages().

Poniższy przykład zawiera listę wiadomości w pokoju czatu:

Node.js

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

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

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

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here
    parent: 'spaces/SPACE_NAME',
  };

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

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

await main();

Python

chat/client-libraries/cloud/list_messages_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.messages.readonly"]

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

    # Initialize request argument(s)
    request = google_chat.ListMessagesRequest(
        # Replace SPACE_NAME here
        parent = 'spaces/SPACE_NAME',
        # Number of results that will be returned at once
        page_size = 100
    )

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

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

list_messages_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/ListMessagesUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.ListMessagesRequest;
import com.google.chat.v1.ListMessagesResponse;
import com.google.chat.v1.Message;

// This sample shows how to list messages with user credential.
public class ListMessagesUserCred {

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

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      ListMessagesRequest.Builder request = ListMessagesRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Number of results that will be returned at once.
        .setPageSize(10);

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

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to list messages with user credential
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.readonly'
 * referenced in the manifest file (appsscript.json).
 */
function listMessagesUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here
  const parent = "spaces/SPACE_NAME";

  // Iterate through the response pages using page tokens
  let responsePage;
  let pageToken = null;
  do {
    // Request response pages
    responsePage = Chat.Spaces.Messages.list(parent, {
      pageSize: 10,
      pageToken: pageToken,
    });
    // Handle response pages
    if (responsePage.messages) {
      for (const message of responsePage.messages) {
        console.log(message);
      }
    }
    // Update the page token to the next one
    pageToken = responsePage.nextPageToken;
  } while (pageToken);
}

Aby uruchomić ten przykład, zastąp SPACE_NAME identyfikatorem z pola name przestrzeni. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.

Interfejs Chat API zwraca listę wiadomości wysłanych w określonym pokoju. Jeśli w żądaniu nie ma wiadomości, odpowiedź interfejsu Chat API zwraca pusty obiekt. W przypadku korzystania z interfejsu REST/HTTP odpowiedź zawiera pusty obiekt JSON, {}.

Wyświetlanie wiadomości jako aplikacji do obsługi czatu

Uwierzytelnianie aplikacji wymaga jednorazowego zatwierdzenia przez administratora.

Aby wyświetlić listę wiadomości z pokoju z uwierzytelnianiem aplikacji za pomocą interfejsu Chat REST API, w żądaniu podaj te informacje:

  • Określ jeden z tych zakresów autoryzacji:
    • https://www.googleapis.com/auth/chat.app.messages.readonly
  • Wywołaj metodę listmessageszasobie.
  • Przekaż name pokoju, z którego chcesz wyświetlić listę wiadomości.

Napisz skrypt, który wywołuje Chat API

Oto jak wyświetlić listę wiadomości za pomocą uwierzytelniania aplikacji i interfejsu Chat REST API:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_messages_list_app.py.
  2. Dodaj do pliku chat_messages_list_app.py ten kod:

    from google.oauth2 import service_account
    from apiclient.discovery import build
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.app.messages.readonly"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then lists messages from a specified space.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().list(
    
            # The space to list messages from.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE_NAME'
    
        ).execute()
    
        # Print Chat API's response in your command line interface.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. W kodzie zastąp te elementy:

    • SPACE_NAME: nazwa pokoju, którą możesz uzyskać za pomocą spaces.list metody w interfejsie Chat API lub z adresu URL pokoju.
  4. W katalogu roboczym skompiluj i uruchom przykład:

    python3 chat_messages_list_app.py

Interfejs Chat API zwraca listę wiadomości wysłanych w określonym pokoju. Jeśli w żądaniu nie ma wiadomości, odpowiedź interfejsu Chat API zwraca pusty obiekt. W przypadku korzystania z interfejsu REST/HTTP odpowiedź zawiera pusty obiekt JSON, {}.