Как изменить сообщение

В этом руководстве рассказывается, как использовать метод update для ресурса Message Google Chat API, чтобы обновить текстовое сообщение или сообщение-карточку в чат-группе. Обновление сообщения позволяет изменить его атрибуты, например текст или содержимое карточки. Вы также можете добавить текстовое сообщение перед карточкой или карточку после текстового сообщения.

В Chat API сообщение Chat представлено ресурсом Message. Пользователи Chat могут отправлять только текстовые сообщения, а приложениям Chat доступно множество других функций, включая показ статических или интерактивных пользовательских интерфейсов, сбор информации от пользователей и доставку личных сообщений. Чтобы узнать больше о функциях обмена сообщениями, доступных для Chat API, ознакомьтесь с обзором сообщений Google Chat.

Требования

Node.js

Python

Java

Apps Script

Как обновить сообщение от имени пользователя

При аутентификации пользователя можно изменить только текст сообщения.

Чтобы обновить сообщение с аутентификацией пользователя, передайте в запросе следующее:

  • Укажите область авторизации chat.messages.
  • Вызовите метод UpdateMessage.
  • Передайте message как экземпляр Message со следующими параметрами:
    • Поле name, в котором указано сообщение для обновления, включая идентификатор чат-группы и идентификатор сообщения.
    • Поле text с новым текстом.
  • Передайте updateMask со значением text.

Если обновленное сообщение является сообщением-карточкой, то текст добавляется перед карточками (которые продолжают отображаться).

Ниже описано, как обновить сообщение или добавить текстовое сообщение перед сообщением карточки с аутентификацией пользователя.

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

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

Чтобы запустить этот пример, замените следующие значения:

  • SPACE_NAME – идентификатор из name чат-группы. Идентификатор можно получить, вызвав метод ListSpaces, или из URL чат-группы.
  • MESSAGE_NAME – идентификатор из поля name сообщения. Идентификатор можно получить из тела ответа, возвращенного после асинхронного создания сообщения с помощью Chat API, или с помощью пользовательского имени, назначенного сообщению при создании.

Chat API возвращает экземпляр Message с подробными сведениями об обновленном сообщении.

Как обновить сообщение от имени приложения Chat

При аутентификации приложения можно обновлять и текст, и карточки сообщения.

Чтобы обновить сообщение с помощью аутентификации приложения, передайте в запросе следующее:

  • Укажите область авторизации chat.bot.
  • Вызовите метод UpdateMessage.
  • Передайте message как экземпляр Message со следующими параметрами:
    • Поле name, в котором указано сообщение для обновления, включая идентификатор чат-группы и идентификатор сообщения.
    • Поле text с новым текстом, если его нужно обновить.
    • Поле cardsV2 с новыми картами, если их нужно обновить.
  • Передайте updateMask со списком полей, которые нужно обновить, например text и cardsV2.

Если обновленное сообщение является сообщением-карточкой и текст обновлен, то обновленный текст добавляется в начало карточек (которые продолжают отображаться). Если обновленное сообщение является текстовым сообщением и карточки обновлены, то обновленные карточки добавляются к тексту (который продолжает отображаться).

Чтобы обновить текст и карточки сообщения с помощью аутентификации приложения, выполните следующие действия:

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

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

Чтобы запустить этот пример, замените следующие значения:

  • SPACE_NAME – идентификатор из name чат-группы. Идентификатор можно получить, вызвав метод ListSpaces, или из URL чат-группы.
  • MESSAGE_NAME – идентификатор из поля name сообщения. Идентификатор можно получить из тела ответа, возвращенного после асинхронного создания сообщения с помощью Chat API, или с помощью пользовательского имени, назначенного сообщению при создании.

Chat API возвращает экземпляр Message с подробными сведениями об обновленном сообщении.

Асинхронное обновление карточек

Вы можете асинхронно обновлять карточки в сообщении с помощью метода replaceCards. Это полезно для обновления содержимого карточки без взаимодействия с пользователем, например для обновления предварительного просмотра ссылки или статуса задачи. Этот метод работает для сообщений, созданных приложением, в том числе от имени пользователя.

Подробнее о том, как создавать и обновлять интерактивные карточки…