Zaktualizuj wiadomość

Ten przewodnik wyjaśnia, jak używać metody update w zasobie Message interfejsu Google Chat API, aby zaktualizować wiadomość tekstową lub wiadomość z kartą w pokoju. Zaktualizuj wiadomość, aby zmienić jej atrybuty, takie jak treść lub zawartość karty. Możesz też dodać wiadomość tekstową przed wiadomością z kartą lub dołączyć kartę po wiadomości tekstowej.

W interfejsie Chat API wiadomość na czacie jest reprezentowana przez zasób Message. Użytkownicy Google Chat mogą wysyłać tylko wiadomości tekstowe, ale aplikacje do Google Chat mogą korzystać z wielu innych funkcji, takich jak wyświetlanie statycznych lub interaktywnych interfejsów, zbieranie informacji od użytkowników i dostarczanie wiadomości prywatnych. Więcej informacji o funkcjach przesyłania wiadomości dostępnych w interfejsie Chat API znajdziesz w omówieniu wiadomości na czacie w Google Chat.

Wymagania wstępne

Node.js

Python

Java

Google Apps Script

Aktualizowanie wiadomości w imieniu użytkownika

W przypadku uwierzytelniania użytkownika można zaktualizować tylko tekst wiadomości.

Aby zaktualizować wiadomość z uwierzytelnianiem użytkownika, przekaż w żądaniu te informacje:

  • Określ zakres autoryzacji chat.messages.
  • Wywołaj metodę UpdateMessage.
  • Przekaż message jako instancję Message z tymi wartościami:
    • Pole name ustawione na wiadomość do zaktualizowania, która zawiera identyfikator pokoju i identyfikator wiadomości.
    • Pole text z nowym tekstem.
  • Przekaż updateMask z wartością text.

Jeśli zaktualizowana wiadomość jest wiadomością na karcie, tekst jest dodawany na początku kart (które nadal się wyświetlają).

Aby zaktualizować wiadomość lub dodać wiadomość tekstową przed wiadomością na karcie, użyj uwierzytelniania użytkownika:

Node.js

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

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

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

  // Initialize request argument(s)
  const request = {
    message: {
      // Replace SPACE_NAME and MESSAGE_NAME here
      name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
      text: 'Updated with user credential!',
    },
    // The field paths to update. Separate multiple values with commas or use `*`
    // to update all field paths.
    updateMask: {
      // The field paths to update.
      paths: ['text'],
    },
  };

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

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

await main();

Python

chat/client-libraries/cloud/update_message_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"]

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

    # Initialize request argument(s)
    request = google_chat.UpdateMessageRequest(
        message = {
            # Replace SPACE_NAME and MESSAGE_NAME here
            "name": "spaces/SPACE_NAME/messages/MESSAGE_NAME",
            "text": "Updated with user credential!"
        },
        # The field paths to update. Separate multiple values with commas or use
        # `*` to update all field paths.
        update_mask = "text"
    )

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

    # Handle the response
    print(response)

update_message_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.UpdateMessageRequest;
import com.google.chat.v1.Message;
import com.google.protobuf.FieldMask;

// This sample shows how to update message with user credential.
public class UpdateMessageUserCred {

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

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder()
        .setMessage(Message.newBuilder()
          // replace SPACE_NAME and MESSAGE_NAME here
          .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME")
          .setText("Updated with user credential!"))
        .setUpdateMask(FieldMask.newBuilder()
          // The field paths to update.
          .addPaths("text"));
      Message response = chatServiceClient.updateMessage(request.build());

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

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to update a message with user credential
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages'
 * referenced in the manifest file (appsscript.json).
 */
function updateMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = "spaces/SPACE_NAME/messages/MESSAGE_NAME";
  const message = {
    text: "Updated with user credential!",
  };
  // The field paths to update. Separate multiple values with commas or use
  // `*` to update all field paths.
  const updateMask = "text";

  // Make the request
  const response = Chat.Spaces.Messages.patch(message, name, {
    updateMask: updateMask,
  });

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

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

  • SPACE_NAME: identyfikator z name pokoju. Identyfikator możesz 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 asynchronicznym utworzeniu wiadomości za pomocą interfejsu Chat API lub z nazwy niestandardowej przypisanej do wiadomości podczas jej tworzenia.

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

Aktualizowanie wiadomości jako aplikacja Google Chat

Dzięki uwierzytelnianiu aplikacji można aktualizować zarówno tekst, jak i karty wiadomości.

Aby zaktualizować wiadomość za pomocą uwierzytelniania aplikacji, przekaż w żądaniu te informacje:

  • Określ zakres autoryzacji chat.bot.
  • Wywołaj metodę UpdateMessage.
  • Przekaż message jako instancję Message z tymi wartościami:
    • Pole name ustawione na wiadomość do zaktualizowania, która zawiera identyfikator pokoju i identyfikator wiadomości.
    • Pole text z nowym tekstem, jeśli wymaga on aktualizacji.
    • Pole cardsV2 z nowymi kartami, jeśli wymagają aktualizacji.
  • Przekaż updateMask z listą pól do aktualizacji, takich jak text i cardsV2.

Jeśli zaktualizowana wiadomość jest wiadomością z kartą i tekst został zaktualizowany, zaktualizowany tekst jest dodawany na początku kart (które nadal są wyświetlane). Jeśli zaktualizowana wiadomość jest wiadomością tekstową i karty są aktualizowane, zaktualizowane karty są dołączane do tekstu (który nadal jest wyświetlany).

Aby zaktualizować tekst i karty wiadomości z uwierzytelnianiem aplikacji:

Node.js

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

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

  // Initialize request argument(s)
  const request = {
    message: {
      // Replace SPACE_NAME and MESSAGE_NAME here
      name: 'spaces/SPACE_NAME/messages/MESSAGE_NAME',
      text: 'Text updated with app credential!',
      cardsV2: [
        {
          card: {
            header: {
              title: 'Card updated with app credential!',
              imageUrl:
                'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg',
            },
          },
        },
      ],
    },
    // The field paths to update. Separate multiple values with commas or use `*`
    // to update all field paths.
    updateMask: {
      // The field paths to update.
      paths: ['text', 'cards_v2'],
    },
  };

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

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

await main();

Python

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

    # Initialize request argument(s)
    request = google_chat.UpdateMessageRequest(
        message = {
            # Replace SPACE_NAME and MESSAGE_NAME here
            "name": "spaces/SPACE_NAME/messages/MESSAGE_NAME",
            "text": "Text updated with app credential!",
            "cards_v2" : [{ "card": { "header": {
                "title": 'Card updated with app credential!',
                "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
            }}}]
        },
        # The field paths to update. Separate multiple values with commas or use
        # `*` to update all field paths.
        update_mask = "text,cardsV2"
    )

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

    # Handle the response
    print(response)

update_message_with_app_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateMessageAppCred.java
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.UpdateMessageRequest;
import com.google.chat.v1.Message;
import com.google.protobuf.FieldMask;

// This sample shows how to update message with app credential.
public class UpdateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      UpdateMessageRequest.Builder request = UpdateMessageRequest.newBuilder()
        .setMessage(Message.newBuilder()
          // replace SPACE_NAME and MESSAGE_NAME here
          .setName("spaces/SPACE_NAME/messages/MESSAGE_NAME")
          .setText("Text updated with app credential!")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("Card updated with app credential!")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg")))))
        .setUpdateMask(FieldMask.newBuilder()
          // The field paths to update.
          .addAllPaths(List.of("text", "cards_v2")));
      Message response = chatServiceClient.updateMessage(request.build());

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

Google Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to update a message with app credential
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function updateMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME and MESSAGE_NAME here
  const name = "spaces/SPACE_NAME/messages/MESSAGE_NAME";
  const message = {
    text: "Text updated with app credential!",
    cardsV2: [
      {
        card: {
          header: {
            title: "Card updated with app credential!",
            imageUrl:
              "https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg",
          },
        },
      },
    ],
  };
  // The field paths to update. Separate multiple values with commas or use
  // `*` to update all field paths.
  const updateMask = "text,cardsV2";

  // Make the request
  const response = Chat.Spaces.Messages.patch(
    message,
    name,
    {
      updateMask: updateMask,
    },
    getHeaderWithAppCredentials(),
  );

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

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

  • SPACE_NAME: identyfikator z name pokoju. Identyfikator możesz 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 asynchronicznym utworzeniu wiadomości za pomocą interfejsu Chat API lub z nazwy niestandardowej przypisanej do wiadomości podczas jej tworzenia.

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

Aktualizuj karty asynchronicznie

Karty w wiadomości możesz aktualizować asynchronicznie za pomocą metody replaceCards. Jest to przydatne do aktualizowania zawartości karty bez interakcji użytkownika, np. odświeżania podglądu linku lub aktualizowania stanu zadania. Ta metoda działa w przypadku wiadomości utworzonych przez aplikację, w tym tych utworzonych w imieniu użytkownika.

Więcej informacji znajdziesz w artykule Tworzenie i aktualizowanie kart interaktywnych.