Aggiornare un messaggio

Questa guida spiega come utilizzare il metodo update() nella risorsa Message dell'API Google Chat per aggiornare un messaggio di testo o con scheda in uno spazio. Aggiorna un messaggio per modificare gli attributi, ad esempio il testo o il contenuto di una scheda. Puoi anche anteporre un messaggio di testo a un messaggio della carta o aggiungere una carta a un messaggio di testo.

Nell'API Chat, un messaggio di Chat è rappresentato dalla risorsa Message. Mentre gli utenti di Chat possono inviare solo messaggi di testo, le app di chat possono utilizzare molte altre funzionalità di messaggistica, tra cui la visualizzazione di interfacce utente statiche o interattive, la raccolta di informazioni dagli utenti e l'invio privato di messaggi. Per scoprire di più sulle funzionalità di messaggistica disponibili per l'API Chat, consulta la Panoramica dei messaggi di Google Chat.

Prerequisiti

Node.js

Python

Java

Apps Script

Aggiornare un messaggio per conto di un utente

Con l'autenticazione utente, può essere aggiornato solo il testo di un messaggio.

Per aggiornare un messaggio con l'autenticazione utente, passa quanto segue nella tua richiesta:

  • Specifica l'ambito di autorizzazione chat.messages.
  • Chiama il metodo UpdateMessage().
  • Passa message come istanza di Message con quanto segue:
    • Il campo name impostato sul messaggio da aggiornare, che include un ID spazio e un ID messaggio.
    • Il campo text impostato con il nuovo testo.
  • Passa updateMask con il valore text.

Se il messaggio aggiornato è un messaggio con scheda, il testo viene anteposto alle schede (che continuano a essere visualizzate).

Ecco come aggiornare un messaggio o anteporre un messaggio di testo a un messaggio della scheda con l'autenticazione utente:

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);
}

main().catch(console.error);

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));
    }
  }
}

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);
}

Per eseguire questo esempio, sostituisci quanto segue:

  • SPACE_NAME: l'ID di name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.
  • MESSAGE_NAME: l'ID di name del messaggio. Puoi ottenere l'ID dal corpo della risposta restituito dopo la creazione di un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.

L'API Chat restituisce un'istanza di Message che descrive in dettaglio il messaggio aggiornato.

Aggiornare un messaggio come app di chat

Con l'autenticazione dell'app, possono essere aggiornati sia il testo che le carte di un messaggio.

Per aggiornare un messaggio con l'autenticazione dell'app, passa quanto segue nella richiesta:

  • Specifica l'ambito di autorizzazione chat.bot.
  • Chiama il metodo UpdateMessage().
  • Passa message come istanza di Message con quanto segue:
    • Il campo name impostato sul messaggio da aggiornare, che include un ID spazio e un ID messaggio.
    • Il campo text impostato con il nuovo testo, se deve essere aggiornato.
    • Il campo cardsV2 impostato con le nuove carte, se devono essere aggiornate.
  • Passa updateMask con l'elenco dei campi da aggiornare, ad esempio text e cardsV2.

Se il messaggio aggiornato è un messaggio con scheda e il testo viene aggiornato, il testo aggiornato viene aggiunto all'inizio delle schede (che continuano a essere visualizzate). Se il messaggio aggiornato è un messaggio di testo e le schede vengono aggiornate, le schede aggiornate vengono aggiunte al testo (che continua a essere visualizzato).

Ecco come aggiornare il testo e le schede di un messaggio con l'autenticazione dell'app:

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);
}

main().catch(console.error);

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));
    }
  }
}

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);
}

Per eseguire questo esempio, sostituisci quanto segue:

  • SPACE_NAME: l'ID di name dello spazio. Puoi ottenere l'ID chiamando il metodo ListSpaces() o dall'URL dello spazio.
  • MESSAGE_NAME: l'ID di name del messaggio. Puoi ottenere l'ID dal corpo della risposta restituito dopo la creazione di un messaggio in modo asincrono con l'API Chat o con il nome personalizzato assegnato al messaggio al momento della creazione.

L'API Chat restituisce un'istanza di Message che descrive in dettaglio il messaggio aggiornato.