更新訊息

本指南說明如何使用 Google Chat API Message 資源的 update() 方法,更新聊天室中的文字或訊息卡片。更新訊息即可變更訊息屬性,例如訊息內容或資訊卡內容。你也可以在訊息卡片前加上文字訊息,或在文字訊息後加上訊息卡片。

在 Chat API 中,Chat 訊息以 Message 資源表示。Chat 使用者只能傳送含有文字的訊息,但 Chat 擴充應用程式可以使用許多其他訊息功能,包括顯示靜態或互動式使用者介面、向使用者收集資訊,以及私下傳送訊息。如要進一步瞭解 Chat API 提供的訊息功能,請參閱「Google Chat 訊息總覽」。

必要條件

Node.js

Python

Java

Apps Script

代表使用者更新訊息

透過使用者驗證,只能更新訊息文字。

如要使用使用者驗證更新訊息,請在要求中傳遞下列內容:

  • 指定 chat.messages 授權範圍。
  • 呼叫 UpdateMessage() 方法。
  • message 做為 Message 的執行個體傳遞,並使用下列項目:
    • name 欄位設為要更新的訊息,包括空間 ID 和訊息 ID。
    • 以新文字設定的 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);
}

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

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室的 ID。name。您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。
  • MESSAGE_NAME:訊息 name 中的 ID。您可以透過使用 Chat API 非同步建立訊息後傳回的回應主體,或透過建立訊息時指派給訊息的自訂名稱,取得 ID。

Chat API 會傳回 Message 的執行個體,其中詳述更新的訊息。

以 Chat 應用程式身分更新訊息

透過應用程式驗證,即可更新訊息的文字和卡片。

如要使用應用程式驗證更新訊息,請在要求中傳遞下列項目:

  • 指定 chat.bot 授權範圍。
  • 呼叫 UpdateMessage() 方法。
  • message 做為 Message 的執行個體傳遞,並使用下列項目:
    • name 欄位設為要更新的訊息,包括空間 ID 和訊息 ID。
    • 如果需要更新,請使用新文字設定 text 欄位。
    • 如果需要更新,請使用新卡片設定 cardsV2 欄位。
  • 傳遞 updateMask,其中包含要更新的欄位清單,例如 textcardsV2

如果更新後的訊息是資訊卡訊息,且文字已更新,更新後的文字會加在資訊卡前面 (資訊卡會繼續顯示)。如果更新後的訊息是簡訊,且卡片已更新,更新後的卡片會附加到文字訊息 (文字訊息會繼續顯示)。

如要透過應用程式驗證更新訊息的文字和卡片,請按照下列步驟操作:

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

如要執行這個範例,請替換下列項目:

  • SPACE_NAME:來自聊天室的 ID。name。您可以呼叫 ListSpaces() 方法,或從空間的網址取得 ID。
  • MESSAGE_NAME:訊息 name 中的 ID。您可以透過使用 Chat API 非同步建立訊息後傳回的回應主體,或透過建立訊息時指派給訊息的自訂名稱,取得 ID。

Chat API 會傳回 Message 的執行個體,其中詳述更新的訊息。