메시지 업데이트하기

이 가이드에서는 update() Google Chat API의 Message 리소스에 대한 메서드로 텍스트 또는 카드를 업데이트합니다. 메시지가 표시됩니다. 메시지를 업데이트하여 메시지 속성(예: 또는 카드의 내용입니다. 카드 메시지에 텍스트 메시지를 추가하거나 텍스트 메시지에 카드를 추가할 수도 있습니다.

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

기본 요건

Node.js

Python

자바

Apps Script

<ph type="x-smartling-placeholder">

사용자 대신 메일 업데이트

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

사용자 인증을 사용하여 메일을 업데이트하려면 다음을 요청:

  • chat.messages 승인 범위를 지정합니다.
  • UpdateMessage() 메서드를 호출합니다.
  • messageMessage 다음과 같이 바꿉니다. <ph type="x-smartling-placeholder">
      </ph>
    • 스페이스 ID를 포함하여 업데이트할 메시지로 설정된 name 필드 메시지 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()

자바

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를 가져올 수 있습니다.

Chat API는 Message 업데이트된 메시지를 표시합니다.

채팅 앱으로 메시지 업데이트하기

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

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

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

업데이트된 메시지가 카드 메시지이고 텍스트가 업데이트되면 업데이트된 텍스트가 카드 앞에 추가되며 카드는 계속 표시됩니다. 업데이트된 메시지가 SMS 및 카드 업데이트되면 업데이트된 카드가 텍스트에 추가되며 합니다.

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

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에서 가져올 수 있습니다.
  • MESSAGE_NAME: 메시지의 name에 있는 ID입니다. Chat API를 사용하여 메시지를 비동기식으로 만들거나 만들 때 메시지에 할당된 맞춤 이름으로 메시지를 만든 후 반환된 응답 본문에서 ID를 가져올 수 있습니다.

Chat API는 업데이트된 메시지에 관한 세부정보가 포함된 Message의 인스턴스를 반환합니다.