메시지 업데이트하기

이 가이드에서는 Google Chat API의 Message 리소스에서 update() 메서드를 사용하여 스페이스의 텍스트 또는 카드 메시지를 업데이트하는 방법을 설명합니다. 메시지를 업데이트하여 메시지 속성(예: 메시지 내용 또는 카드 콘텐츠)을 변경합니다. 카드 메시지 앞에 문자 메시지를 추가하거나 문자 메시지에 카드를 추가할 수도 있습니다.

Chat API에서 Chat 메시지는 Message 리소스로 표시됩니다. Chat 사용자는 텍스트가 포함된 메시지만 보낼 수 있지만 Chat 앱은 정적 또는 대화형 사용자 인터페이스 표시, 사용자로부터 정보 수집, 비공개 메시지 전송 등 다양한 메시지 기능을 사용할 수 있습니다. Chat API에서 사용할 수 있는 메시지 기능에 대해 자세히 알아보려면 Google Chat 메시지 개요를 참고하세요.

기본 요건

Node.js

Python

자바

Apps Script

사용자를 대신하여 메시지 업데이트

사용자 인증을 사용하면 메시지의 텍스트만 업데이트할 수 있습니다.

사용자 인증으로 메시지를 업데이트하려면 요청에 다음을 전달하세요.

  • chat.messages 승인 범위를 지정합니다.
  • UpdateMessage() 메서드를 호출합니다.
  • 다음과 같이 messageMessage의 인스턴스로 전달합니다.
    • 업데이트할 메시지로 설정된 name 필드입니다. 여기에는 스페이스 ID와 메시지 ID가 포함됩니다.
    • 새 텍스트로 설정된 text 필드
  • text 값으로 updateMask을 전달합니다.

업데이트된 메시지가 카드 메시지인 경우 텍스트가 카드 앞에 추가됩니다 (카드는 계속 표시됨).

다음은 메시지를 업데이트하거나 사용자 인증을 사용하여 카드 메시지에 문자 메시지를 추가하는 방법입니다.

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()

자바

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에서 가져온 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
  • MESSAGE_NAME: 메시지의 name에서 가져온 ID입니다. Chat API를 사용하여 비동기적으로 메시지를 만든 후 반환되는 응답 본문에서 ID를 가져오거나, 생성 시 메시지에 할당된 맞춤 이름을 사용하여 ID를 가져올 수 있습니다.

Chat API는 업데이트된 메시지를 자세히 설명하는 Message 인스턴스를 반환합니다.

Chat 앱으로 메시지 업데이트

앱 인증을 사용하면 메시지의 텍스트와 카드를 모두 업데이트할 수 있습니다.

앱 인증으로 메시지를 업데이트하려면 요청에 다음을 전달하세요.

  • chat.bot 승인 범위를 지정합니다.
  • UpdateMessage() 메서드를 호출합니다.
  • 다음과 같이 messageMessage의 인스턴스로 전달합니다.
    • 업데이트할 메시지로 설정된 name 필드입니다. 여기에는 스페이스 ID와 메시지 ID가 포함됩니다.
    • 업데이트해야 하는 경우 새 텍스트로 설정된 text 필드
    • 업데이트해야 하는 경우 새 카드로 설정된 cardsV2 필드입니다.
  • text, cardsV2과 같은 업데이트할 필드 목록과 함께 updateMask를 전달합니다.

업데이트된 메시지가 카드 메시지이고 텍스트가 업데이트되면 업데이트된 텍스트가 카드 앞에 추가됩니다 (카드는 계속 표시됨). 업데이트된 메시지가 문자 메시지이고 카드가 업데이트되면 업데이트된 카드가 텍스트에 추가됩니다 (텍스트는 계속 표시됨).

앱 인증을 사용하여 메시지의 텍스트와 카드를 업데이트하는 방법은 다음과 같습니다.

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()

자바

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에서 가져온 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
  • MESSAGE_NAME: 메시지의 name에서 가져온 ID입니다. Chat API를 사용하여 비동기적으로 메시지를 만든 후 반환되는 응답 본문에서 ID를 가져오거나, 생성 시 메시지에 할당된 맞춤 이름을 사용하여 ID를 가져올 수 있습니다.

Chat API는 업데이트된 메시지를 자세히 설명하는 Message 인스턴스를 반환합니다.