Sprawdzanie szczegółów wiadomości

Z tego przewodnika dowiesz się, jak używać metody get() w zasobie Message interfejsu Google Chat API, aby zwracać szczegóły wiadomości tekstowej lub karty.

W interfejsie Chat API wiadomość w Google Chat jest reprezentowana przez Messagezasó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 prywatnie. 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

Otrzymywanie wiadomości z uwierzytelnianiem użytkownika

Aby uzyskać szczegółowe informacje o wiadomości z uwierzytelnianiem użytkownika, w żądaniu przekaż te informacje:

  • Określ zakres autoryzacji chat.messages.readonly lub chat.messages.
  • Wywołaj metodę GetMessage().
  • Ustaw name na nazwę zasobu wiadomości, którą chcesz pobrać.

W przykładzie poniżej pobierana jest wiadomość z uwierzytelnianiem użytkownika:

Node.js

chat/client-libraries/cloud/get-message-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 get message 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 and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/get_message_user_cred.py
from authentication_utils import create_client_with_user_credentials
import google.oauth2.credentials

from google.apps import chat_v1 as google_chat

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

# This sample shows how to get message with user credential
def get_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = "spaces/SPACE_NAME/messages/MESSAGE_NAME",
    )

    # Make the request
    response = client.get_message(request)

    # Handle the response
    print(response)

get_message_with_user_cred()

Java

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

// This sample shows how to get message with user credential.
public class GetMessageUserCred {

  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))) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message 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 getMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';

  // Make the request
  const response = Chat.Spaces.Messages.get(name);

  // Handle the response
  console.log(response);
}

Aby uruchomić ten przykład, zastąp te elementy:

  • SPACE_NAME: identyfikator z name pokoju. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.
  • MESSAGE_NAME: identyfikator z pola name wiadomości. Identyfikator możesz uzyskać z treści odpowiedzi zwróconej po utworzeniu wiadomości asynchronicznie za pomocą interfejsu Chat API lub za pomocą niestandardowej nazwy przypisanej do wiadomości podczas jej tworzenia.

Interfejs Chat API zwraca instancję Message, która zawiera szczegółowe informacje o określonej wiadomości.

Otrzymywanie wiadomości z uwierzytelnianiem aplikacji

Aby uzyskać szczegółowe informacje o wiadomości z uwierzytelnianiem aplikacji, w żądaniu przekaż te dane:

W tym przykładzie pobieramy wiadomość z uwierzytelnianiem aplikacji:

Node.js

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

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

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME and MESSAGE_NAME here
    name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME'
  };

  // Make the request
  const response = await chatClient.getMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/get_message_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 get message with app credential
def get_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.GetMessageRequest(
        # Replace SPACE_NAME and MESSAGE_NAME here
        name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
    )

    # Make the request
    response = client.get_message(request=request)

    # Handle the response
    print(response)

get_message_with_app_cred()

Java

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

// This sample shows how to get message with app credential.
public class GetMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      GetMessageRequest.Builder request = GetMessageRequest.newBuilder()
        // replace SPACE_NAME and MESSAGE_NAME here
        .setName("spaces/SPACE_NAME/members/MESSAGE_NAME");
      Message response = chatServiceClient.getMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to get message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function getMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = 'spaces/SPACE_NAME/messages/MESSAGE_NAME';
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.get(name, parameters, getHeaderWithAppCredentials());

  // Handle the response
  console.log(response);
}

Aby uruchomić ten przykład, zastąp te elementy:

  • SPACE_NAME: identyfikator z name pokoju. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.
  • MESSAGE_NAME: identyfikator z pola name wiadomości. Identyfikator możesz uzyskać z treści odpowiedzi zwróconej po utworzeniu wiadomości asynchronicznie za pomocą interfejsu Chat API lub za pomocą niestandardowej nazwy przypisanej do wiadomości podczas jej tworzenia.

Interfejs Chat API zwraca instancję Message, która zawiera szczegółowe informacje o określonej wiadomości.

Otrzymywanie wiadomości jako aplikacja Google Chat po zatwierdzeniu przez administratora

Uwierzytelnianie aplikacji z zakresem autoryzacji chat.app.* wymaga jednorazowego zatwierdzenia przez administratora.

Aby uzyskać szczegółowe informacje o wiadomości z uwierzytelnianiem aplikacji za pomocą interfejsu Chat REST API, w żądaniu podaj te informacje:

  • Wywołaj metodę GetMessage().
  • Określ zakres autoryzacji chat.app.messages.readonly.
  • Ustaw name na nazwę zasobu wiadomości, którą chcesz pobrać.

Tworzenie klucza interfejsu API

Aby wywołać metodę interfejsu API wersji przedpremierowej dla programistów, musisz użyć niepublicznej wersji przedpremierowej dokumentu wykrywania interfejsu API. Aby uwierzytelnić żądanie, musisz przekazać klucz interfejsu API.

Aby utworzyć klucz interfejsu API, otwórz projekt Google Cloud aplikacji i wykonaj te czynności:

  1. W konsoli Google Cloud otwórz Menu  > Interfejsy API i usługi > Dane logowania.

    Przejdź do danych logowania

  2. Kliknij Utwórz dane logowania > Klucz interfejsu API.
  3. Wyświetli się nowy klucz interfejsu API.
    • Kliknij Kopiuj , aby skopiować klucz interfejsu API do użycia w kodzie aplikacji. Klucz interfejsu API można też znaleźć w sekcji „Klucze interfejsu API” w danych logowania projektu.
    • Aby można było zapobiec nieautoryzowanemu użyciu, zalecamy ograniczenie miejsc i interfejsów API, w których można używać klucza API. Więcej informacji znajdziesz w sekcji Dodawanie ograniczeń interfejsu API.

Napisz skrypt, który wywołuje Chat API

Aby uzyskać szczegółowe informacje o wiadomości za pomocą uwierzytelniania aplikacji i zatwierdzenia przez administratora oraz interfejsu API REST Google Chat:

Python

  1. W katalogu roboczym utwórz plik o nazwie chat_messages_get_admin_app.py.
  2. Dodaj do pliku chat_messages_get_admin_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 gets details about a message.
        '''
    
        # 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, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().get(
    
            # The message to get details about.
            #
            # Replace SPACE_NAME with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='spaces/SPACE_NAME/messages/MESSAGE_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:

    • API_KEY: klucz interfejsu API utworzony do budowania punktu końcowego usługi dla interfejsu Chat API.
    • SPACE_NAME: identyfikator z przestrzeni name. Możesz go uzyskać, wywołując metodę ListSpaces() lub z adresu URL pokoju.
    • MESSAGE_NAME: identyfikator z elementu name wiadomości. Identyfikator możesz uzyskać z treści odpowiedzi zwróconej po utworzeniu wiadomości asynchronicznie za pomocą interfejsu Chat API lub za pomocą niestandardowej nazwy przypisanej do wiadomości podczas jej tworzenia.
  4. W katalogu roboczym skompiluj i uruchom przykład:

    python3 chat_messages_get_admin_app.py

Interfejs Chat API zwraca instancję Message, która zawiera szczegółowe informacje o określonej wiadomości.