Cập nhật tin nhắn

Hướng dẫn này giải thích cách sử dụng update phương thức trên tài nguyên Message của API Google Chat để cập nhật tin nhắn văn bản hoặc tin nhắn thẻ trong một không gian. Cập nhật tin nhắn để thay đổi các thuộc tính của tin nhắn, chẳng hạn như nội dung tin nhắn hoặc nội dung của thẻ. Bạn cũng có thể thêm tin nhắn văn bản vào trước tin nhắn thẻ hoặc thêm thẻ vào sau tin nhắn văn bản.

Trong API Chat, tin nhắn Chat được biểu thị bằng tài nguyên Message. Mặc dù người dùng Chat chỉ có thể gửi tin nhắn có chứa văn bản, nhưng ứng dụng Chat có thể sử dụng nhiều tính năng nhắn tin khác, bao gồm cả việc hiển thị giao diện người dùng tĩnh hoặc tương tác, thu thập thông tin từ người dùng và gửi tin nhắn riêng tư. Để tìm hiểu thêm về các tính năng nhắn tin có sẵn cho API Chat, hãy xem bài viết Tổng quan về tin nhắn Google Chat.

Điều kiện tiên quyết

Node.js

Python

Java

Apps Script

Cập nhật tin nhắn thay mặt người dùng

Khi xác thực người dùng, bạn chỉ có thể cập nhật văn bản của tin nhắn.

Để cập nhật tin nhắn bằng tính năng xác thực người dùng, hãy truyền các thông tin sau trong yêu cầu:

  • Chỉ định phạm vi uỷ quyền chat.messages.
  • Gọi UpdateMessage phương thức.
  • Truyền message dưới dạng một thực thể của Message với các thông tin sau:
    • Trường name được đặt thành tin nhắn cần cập nhật, bao gồm mã không gian và mã tin nhắn.
    • Trường text được đặt bằng văn bản mới.
  • Truyền updateMask với giá trị text.

Nếu tin nhắn đã cập nhật là tin nhắn thẻ, thì văn bản sẽ được thêm vào trước các thẻ (vẫn hiển thị).

Dưới đây là cách cập nhật tin nhắn hoặc thêm tin nhắn văn bản vào trước tin nhắn thẻ bằng tính năng xác thực người dùng:

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

Để chạy mẫu này, hãy thay thế các thông tin sau:

API Chat trả về một thực thể của Message nêu chi tiết tin nhắn đã cập nhật.

Cập nhật tin nhắn với tư cách là ứng dụng Chat

Khi xác thực ứng dụng, bạn có thể cập nhật cả văn bản và thẻ của tin nhắn.

Để cập nhật tin nhắn bằng tính năng xác thực ứng dụng, hãy truyền các thông tin sau trong yêu cầu:

  • Chỉ định phạm vi uỷ quyền chat.bot.
  • Gọi UpdateMessage phương thức.
  • Truyền message dưới dạng một thực thể của Message với các thông tin sau:
    • Trường name được đặt thành tin nhắn cần cập nhật, bao gồm mã không gian và mã tin nhắn.
    • Trường text được đặt bằng văn bản mới nếu cần cập nhật.
    • Trường cardsV2 được đặt bằng các thẻ mới nếu cần cập nhật.
  • Truyền updateMask với danh sách các trường cần cập nhật, chẳng hạn như textcardsV2.

Nếu tin nhắn đã cập nhật là tin nhắn thẻ và văn bản được cập nhật, thì văn bản đã cập nhật sẽ được thêm vào trước các thẻ (vẫn hiển thị). Nếu tin nhắn đã cập nhật là tin nhắn văn bản và thẻ được cập nhật, thì các thẻ đã cập nhật sẽ được thêm vào sau văn bản (vẫn hiển thị).

Dưới đây là cách cập nhật văn bản và thẻ của tin nhắn bằng tính năng xác thực ứng dụng:

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

Để chạy mẫu này, hãy thay thế các thông tin sau:

API Chat trả về một thực thể của Message nêu chi tiết tin nhắn đã cập nhật.

Cập nhật thẻ không đồng bộ

Trong Bản dùng trước cho nhà phát triển, bạn có thể cập nhật thẻ trong tin nhắn không đồng bộ bằng phương thức replaceCards. Tính năng này hữu ích khi cập nhật nội dung của thẻ mà không cần người dùng tương tác, chẳng hạn như làm mới bản xem trước đường liên kết hoặc cập nhật trạng thái của một nhiệm vụ. Phương thức này hoạt động đối với các tin nhắn do ứng dụng tạo, bao gồm cả những tin nhắn được tạo thay mặt người dùng.

Để biết thông tin chi tiết, hãy xem bài viết Tạo và cập nhật thẻ.