Google Chat API를 사용하여 메시지 보내기

이 가이드에서는 Google Chat API의 Message 리소스에서 create() 메서드를 사용하여 다음 작업을 실행하는 방법을 설명합니다.

  • 텍스트, 카드, 대화형 위젯이 포함된 메시지를 보냅니다.
  • 특정 Chat 사용자에게 비공개로 메시지를 보냅니다.
  • 메시지 대화목록을 시작하거나 답장합니다.
  • 다른 Chat API 요청에서 지정할 수 있도록 메시지 이름을 지정합니다.

최대 메시지 크기 (텍스트 또는 카드 포함)는 32,000바이트입니다. 이 크기를 초과하는 메시지를 보내려면 Chat 앱에서 대신 여러 메시지를 보내야 합니다.

Chat API를 호출하여 메시지를 만드는 것 외에도 Chat 앱은 사용자가 스페이스에 Chat 앱을 추가한 후 환영 메시지를 게시하는 등 사용자 상호작용에 답장하는 메시지를 만들고 보낼 수 있습니다. 상호작용에 응답할 때 채팅 앱은 대화형 대화상자 및 링크 미리보기 인터페이스를 비롯한 다른 유형의 메시지 기능을 사용할 수 있습니다. 사용자에게 답장하기 위해 Chat 앱은 Chat API를 호출하지 않고 메시지를 동기식으로 반환합니다. 상호작용에 응답하는 메시지를 보내는 방법을 알아보려면 Google Chat 앱과의 상호작용 수신 및 응답을 참고하세요.

Chat API로 생성된 메시지가 Chat에 표시되고 속성이 지정되는 방식

앱 인증사용자 인증을 사용하여 create() 메서드를 호출할 수 있습니다. Chat은 사용하는 인증 유형에 따라 메시지 발신자를 다르게 표시합니다.

Chat 앱으로 인증하면 Chat 앱에서 메시지를 전송합니다.

앱 인증으로 create() 메서드를 호출합니다.
그림 1: 앱 인증을 사용하면 Chat 앱에서 메시지를 보냅니다. 보낸 사람이 사람이 아님을 알리기 위해 채팅에는 이름 옆에 App가 표시됩니다.

사용자로 인증하면 Chat 앱이 사용자를 대신하여 메시지를 보냅니다. 또한 Chat은 이름을 표시하여 메시지에 Chat 앱을 표시합니다.

사용자 인증으로 create() 메서드를 호출합니다.
그림 2: 사용자 인증을 사용하면 사용자가 메시지를 보내고 Chat에 사용자 이름 옆에 Chat 앱 이름이 표시됩니다.

인증 유형에 따라 메시지에 포함할 수 있는 메시지 기능과 인터페이스도 결정됩니다. 앱 인증을 사용하면 채팅 앱이 서식 있는 텍스트, 카드 기반 인터페이스, 대화형 위젯이 포함된 메시지를 보낼 수 있습니다. Chat 사용자는 메시지에 텍스트만 보낼 수 있으므로 사용자 인증을 사용하여 메시지를 만들 때는 텍스트만 포함할 수 있습니다. Chat API에서 사용할 수 있는 메시지 기능에 대해 자세히 알아보려면 Google Chat 메시지 개요를 참고하세요.

이 가이드에서는 인증 유형을 사용하여 Chat API로 메시지를 보내는 방법을 설명합니다.

기본 요건

Node.js

Python

자바

Apps Script

Chat 앱으로 메시지 보내기

이 섹션에서는 앱 인증을 사용하여 텍스트, 카드, 대화형 액세서리 위젯이 포함된 메시지를 전송하는 방법을 설명합니다.

앱 인증을 통해 전송된 메일
그림 4. Chat 앱이 텍스트, 카드, 액세서리 버튼이 포함된 메시지를 보냅니다.

앱 인증을 사용하여 CreateMessage() 메서드를 호출하려면 요청에서 다음 필드를 지정해야 합니다.

  • chat.bot 승인 범위입니다.
  • 메시지를 게시하려는 Space 리소스입니다. Chat 앱이 스페이스의 구성원이어야 합니다.
  • 생성할 Message 리소스입니다. 메시지의 콘텐츠를 정의하려면 서식 있는 텍스트(text), 하나 이상의 카드 인터페이스(cardsV2) 또는 둘 다를 포함하면 됩니다.

선택적으로 다음을 포함할 수 있습니다.

다음 코드는 텍스트, 카드, 메시지 하단의 클릭 가능한 버튼이 포함된 채팅 앱으로 게시된 메시지를 채팅 앱이 전송하는 방법을 보여줍니다.

Node.js

chat/client-libraries/cloud/create-message-app-cred.js
import {createClientWithAppCredentials} from './authentication-utils.js';

// This sample shows how to create message with app credential
async function main() {
  // Create a client
  const chatClient = createClientWithAppCredentials();

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world! I created this message by calling ' +
            'the Chat API\'s `messages.create()` method.',
      cardsV2 : [{ card: {
        header: {
          title: 'About this message',
          imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
        },
        sections: [{
          header: 'Contents',
          widgets: [{ textParagraph: {
              text: '🔡 <b>Text</b> which can include ' +
                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
            }}, { textParagraph: {
              text: '🖼️ A <b>card</b> to display visual elements' +
                    'and request information such as text 🔤, ' +
                    'dates and times 📅, and selections ☑️.'
            }}, { textParagraph: {
              text: '👉🔘 An <b>accessory widget</b> which adds ' +
                    'a button to the bottom of a message.'
            }}
          ]}, {
            header: "What's next",
            collapsible: true,
            widgets: [{ textParagraph: {
                text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
              }}, { textParagraph: {
                text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                      "or ❌ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                      "the message."
              }
            }]
          }
        ]
      }}],
      accessoryWidgets: [{ buttonList: { buttons: [{
        text: 'View documentation',
        icon: { materialIcon: { name: 'link' }},
        onClick: { openLink: {
          url: 'https://developers.google.com/workspace/chat/create-messages'
        }}
      }]}}]
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_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 create message with app credential
def create_message_with_app_cred():
    # Create a client
    client = create_client_with_app_credentials()

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world! I created this message by calling ' +
                    'the Chat API\'s `messages.create()` method.',
            "cards_v2" : [{ "card": {
                "header": {
                    "title": 'About this message',
                    "image_url": 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
                },
                "sections": [{
                    "header": "Contents",
                    "widgets": [{ "text_paragraph": {
                            "text": '🔡 <b>Text</b> which can include ' +
                                    'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
                        }}, { "text_paragraph": {
                            "text": '🖼️ A <b>card</b> to display visual elements' +
                                    'and request information such as text 🔤, ' +
                                    'dates and times 📅, and selections ☑️.'
                        }}, { "text_paragraph": {
                            "text": '👉🔘 An <b>accessory widget</b> which adds ' +
                                    'a button to the bottom of a message.'
                        }}
                    ]}, {
                        "header": "What's next",
                        "collapsible": True,
                        "widgets": [{ "text_paragraph": {
                                "text": "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
                            }}, { "text_paragraph": {
                                "text": "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                                        "or ❌ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                                        "the message."
                            }
                        }]
                    }
                ]
            }}],
            "accessory_widgets": [{ "button_list": { "buttons": [{
                "text": 'View documentation',
                "icon": { "material_icon": { "name": 'link' }},
                "on_click": { "open_link": {
                    "url": 'https://developers.google.com/workspace/chat/create-messages'
                }}
            }]}}]
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_app_cred()

자바

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageAppCred.java
import com.google.apps.card.v1.Button;
import com.google.apps.card.v1.ButtonList;
import com.google.apps.card.v1.Card;
import com.google.apps.card.v1.Icon;
import com.google.apps.card.v1.MaterialIcon;
import com.google.apps.card.v1.OnClick;
import com.google.apps.card.v1.OpenLink;
import com.google.apps.card.v1.TextParagraph;
import com.google.apps.card.v1.Widget;
import com.google.apps.card.v1.Card.CardHeader;
import com.google.apps.card.v1.Card.Section;
import com.google.chat.v1.AccessoryWidget;
import com.google.chat.v1.CardWithId;
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with app credential.
public class CreateMessageAppCred {

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithAppCredentials()) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world! I created this message by calling " +
                    "the Chat API\'s `messages.create()` method.")
          .addCardsV2(CardWithId.newBuilder().setCard(Card.newBuilder()
            .setHeader(CardHeader.newBuilder()
              .setTitle("About this message")
              .setImageUrl("https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg"))
            .addSections(Section.newBuilder()
              .setHeader("Contents")
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔡 <b>Text</b> which can include " +
                "hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🖼️ A <b>card</b> to display visual elements " +
                "and request information such as text 🔤, " +
                "dates and times 📅, and selections ☑️.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "👉🔘 An <b>accessory widget</b> which adds " +
                "a button to the bottom of a message."))))
            .addSections(Section.newBuilder()
              .setHeader("What's next")
              .setCollapsible(true)
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>.")))
              .addWidgets(Widget.newBuilder().setTextParagraph(TextParagraph.newBuilder().setText(
                "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                "or ❌ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                "the message."))))))
          .addAccessoryWidgets(AccessoryWidget.newBuilder()
            .setButtonList(ButtonList.newBuilder()
              .addButtons(Button.newBuilder()
                .setText("View documentation")
                .setIcon(Icon.newBuilder()
                  .setMaterialIcon(MaterialIcon.newBuilder().setName("link")))
                .setOnClick(OnClick.newBuilder()
                  .setOpenLink(OpenLink.newBuilder()
                    .setUrl("https://developers.google.com/workspace/chat/create-messages")))))));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with app credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.bot'
 * used by service accounts.
 */
function createMessageAppCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world! I created this message by calling ' +
          'the Chat API\'s `messages.create()` method.',
    cardsV2 : [{ card: {
      header: {
        title: 'About this message',
        imageUrl: 'https://fonts.gstatic.com/s/i/short-term/release/googlesymbols/info/default/24px.svg'
      },
      sections: [{
        header: 'Contents',
        widgets: [{ textParagraph: {
            text: '🔡 <b>Text</b> which can include ' +
                  'hyperlinks 🔗, emojis 😄🎉, and @mentions 🗣️.'
          }}, { textParagraph: {
            text: '🖼️ A <b>card</b> to display visual elements' +
                  'and request information such as text 🔤, ' +
                  'dates and times 📅, and selections ☑️.'
          }}, { textParagraph: {
            text: '👉🔘 An <b>accessory widget</b> which adds ' +
                  'a button to the bottom of a message.'
          }}
        ]}, {
          header: "What's next",
          collapsible: true,
          widgets: [{ textParagraph: {
              text: "❤️ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages.reactions/create'>Add a reaction</a>."
            }}, { textParagraph: {
              text: "🔄 <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/patch'>Update</a> " +
                    "or ❌ <a href='https://developers.google.com/workspace/chat/api/reference/rest/v1/spaces.messages/delete'>delete</a> " +
                    "the message."
            }
          }]
        }
      ]
    }}],
    accessoryWidgets: [{ buttonList: { buttons: [{
      text: 'View documentation',
      icon: { materialIcon: { name: 'link' }},
      onClick: { openLink: {
        url: 'https://developers.google.com/workspace/chat/create-messages'
      }}
    }]}}]
  };
  const parameters = {};

  // Make the request
  const response = Chat.Spaces.Messages.create(
    message, parent, parameters, getHeaderWithAppCredentials()
  );

  // Handle the response
  console.log(response);
}

이 샘플을 실행하려면 SPACE_NAME를 스페이스의 name 필드에 있는 ID로 바꿉니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.

메시지 하단에 대화형 위젯 추가

이 가이드의 첫 번째 코드 샘플에서 채팅 앱 메시지는 메시지 하단에 클릭 가능한 버튼(액세서리 위젯이라고 함)을 표시합니다. 액세서리 위젯은 메일의 텍스트나 카드 뒤에 표시됩니다. 이러한 위젯을 사용하여 다음과 같은 다양한 방법으로 사용자가 메시지와 상호작용하도록 유도할 수 있습니다.

  • 메시지의 정확성 또는 만족도를 평가합니다.
  • 메시지 또는 Chat 앱 관련 문제를 신고합니다.
  • 문서와 같은 관련 콘텐츠 링크를 엽니다.
  • 특정 기간 동안 Chat 앱에서 유사한 메시지를 닫거나 일시중지합니다.

액세서리 위젯을 추가하려면 요청 본문에 accessoryWidgets[] 필드를 포함하고 포함할 위젯을 하나 이상 지정합니다.

다음 이미지는 사용자가 채팅 앱에 대한 경험을 평가할 수 있도록 액세서리 위젯이 포함된 텍스트 메시지를 추가하는 채팅 앱을 보여줍니다.

액세서리 위젯입니다.
그림 5: 텍스트와 액세서리 위젯이 있는 채팅 앱 메시지

다음은 액세서리 버튼이 두 개인 문자 메시지를 만드는 요청의 본문을 보여줍니다. 사용자가 버튼을 클릭하면 해당 함수 (예: doUpvote)가 상호작용을 처리합니다.

{
  text: "Rate your experience with this Chat app.",
  accessoryWidgets: [{ buttonList: { buttons: [{
    icon: { material_icon: {
      name: "thumb_up"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doUpvote"
    }}
  }, {
    icon: { material_icon: {
      name: "thumb_down"
    }},
    color: { red: 0, blue: 255, green: 0 },
    onClick: { action: {
      function: "doDownvote"
    }}
  }]}}]
}

비공개로 메시지 보내기

Chat 앱은 메시지가 스페이스의 특정 사용자에게만 표시되도록 비공개로 메시지를 보낼 수 있습니다. Chat 앱에서 비공개 메시지를 보내면 메시지에 해당 메시지가 본인에게만 표시된다는 내용을 알리는 라벨이 표시됩니다.

Chat API를 사용하여 비공개로 메시지를 보내려면 요청 본문에 privateMessageViewer 필드를 지정합니다. 사용자를 지정하려면 채팅 사용자를 나타내는 User 리소스로 값을 설정합니다. 다음 예시와 같이 User 리소스의 name 필드를 사용할 수도 있습니다.

{
  text: "Hello private world!",
  privateMessageViewer: {
    name: "users/USER_ID"
  }
}

이 샘플을 사용하려면 USER_ID를 사용자 고유 ID(예: 12345678987654321 또는 hao@cymbalgroup.com)로 바꿉니다. 사용자 지정에 대한 자세한 내용은 Google Chat 사용자 식별 및 지정을 참고하세요.

비공개로 메시지를 보내려면 요청에서 다음을 생략해야 합니다.

사용자를 대신하여 문자 메시지 보내기

이 섹션에서는 사용자 인증을 사용하여 사용자를 대신해 메시지를 보내는 방법을 설명합니다. 사용자 인증을 사용하면 메시지 콘텐츠에 텍스트만 포함할 수 있으며 카드 인터페이스, 대화형 위젯 등 채팅 앱에서만 사용할 수 있는 메시지 기능은 생략해야 합니다.

사용자 인증으로 전송된 메일
그림 3. Chat 앱이 사용자를 대신하여 문자 메시지를 보냅니다.

사용자 인증을 사용하여 CreateMessage() 메서드를 호출하려면 요청에서 다음 필드를 지정해야 합니다.

  • 이 메서드의 사용자 인증을 지원하는 승인 범위입니다. 다음 샘플에서는 chat.messages.create 범위를 사용합니다.
  • 메시지를 게시하려는 Space 리소스입니다. 인증된 사용자는 스페이스의 구성원이어야 합니다.
  • 생성할 Message 리소스입니다. 메시지의 콘텐츠를 정의하려면 text 필드를 포함해야 합니다.

선택적으로 다음을 포함할 수 있습니다.

다음 코드는 인증된 사용자를 대신하여 Chat 앱이 지정된 스페이스에서 텍스트 메시지를 보낼 수 있는 방법을 보여줍니다.

Node.js

chat/client-libraries/cloud/create-message-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    message: {
      text: '👋🌎 Hello world!' +
            'Text messages can contain things like:\n\n' +
            '* Hyperlinks 🔗\n' +
            '* Emojis 😄🎉\n' +
            '* Mentions of other Chat users `@` \n\n' +
            'For details, see the ' +
            '<https://developers.google.com/workspace/chat/format-messages' +
            '|Chat API developer documentation>.'
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_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.create"]

def create_message_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here.
        parent = "spaces/SPACE_NAME",
        message = {
            "text": '👋🌎 Hello world!' +
                    'Text messages can contain things like:\n\n' +
                    '* Hyperlinks 🔗\n' +
                    '* Emojis 😄🎉\n' +
                    '* Mentions of other Chat users `@` \n\n' +
                    'For details, see the ' +
                    '<https://developers.google.com/workspace/chat/format-messages' +
                    '|Chat API developer documentation>.'
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred()

자바

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with user credential.
public class CreateMessageUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText( "👋🌎 Hello world!" +
                    "Text messages can contain things like:\n\n" +
                    "* Hyperlinks 🔗\n" +
                    "* Emojis 😄🎉\n" +
                    "* Mentions of other Chat users `@` \n\n" +
                    "For details, see the " +
                    "<https://developers.google.com/workspace/chat/format-messages" +
                    "|Chat API developer documentation>."));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const message = {
    text: '👋🌎 Hello world!' +
          'Text messages can contain things like:\n\n' +
          '* Hyperlinks 🔗\n' +
          '* Emojis 😄🎉\n' +
          '* Mentions of other Chat users `@` \n\n' +
          'For details, see the ' +
          '<https://developers.google.com/workspace/chat/format-messages' +
          '|Chat API developer documentation>.'
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent);

  // Handle the response
  console.log(response);
}

이 샘플을 실행하려면 SPACE_NAME를 스페이스의 name 필드에 있는 ID로 바꿉니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.

대화목록 시작 또는 답장

대화목록을 사용하는 스페이스의 경우 새 메시지가 대화목록을 시작하는지 아니면 기존 대화목록에 답글을 다는지를 지정할 수 있습니다.

기본적으로 Chat API를 사용하여 만든 메시지는 새 스레드를 시작합니다. 나중에 스레드를 식별하고 스레드에 답장할 수 있도록 요청에 스레드 키를 지정할 수 있습니다.

  • 요청 본문에서 thread.threadKey 필드를 지정합니다.
  • 키가 이미 있는 경우의 동작을 결정하려면 messageReplyOption 쿼리 매개변수를 지정합니다.

기존 대화목록에 답장하는 메시지를 만들려면 다음 단계를 따르세요.

  • 요청 본문에 thread 필드를 포함합니다. 설정된 경우 생성한 threadKey를 지정할 수 있습니다. 그렇지 않으면 스레드의 name를 사용해야 합니다.
  • messageReplyOption 쿼리 매개변수를 지정합니다.

다음 코드는 인증된 사용자를 대신하여 채팅 앱이 지정된 스페이스의 키로 식별되는 지정된 스레드를 시작하거나 스레드에 답장하는 텍스트 메시지를 전송하는 방법을 보여줍니다.

Node.js

chat/client-libraries/cloud/create-message-user-cred-thread-key.js
import {createClientWithUserCredentials} from './authentication-utils.js';
const {MessageReplyOption} = require('@google-apps/chat').protos.google.chat.v1.CreateMessageRequest;

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with thread key
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Creates the message as a reply to the thread specified by thread_key
    // If it fails, the message starts a new thread instead
    messageReplyOption: MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
    message: {
      text: 'Hello with user credential!',
      thread: {
        // Thread key specifies a thread and is unique to the chat app
        // that sets it
        threadKey: 'THREAD_KEY'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_thread_key.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

import google.apps.chat_v1.CreateMessageRequest.MessageReplyOption

SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]

# This sample shows how to create message with user credential with thread key
def create_message_with_user_cred_thread_key():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Creates the message as a reply to the thread specified by thread_key.
        # If it fails, the message starts a new thread instead.
        message_reply_option = MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD,
        message = {
            "text": "Hello with user credential!",
            "thread": {
                # Thread key specifies a thread and is unique to the chat app
                # that sets it.
                "thread_key": "THREAD_KEY"
            }
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_thread_key()

자바

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredThreadKey.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.CreateMessageRequest.MessageReplyOption;
import com.google.chat.v1.Message;
import com.google.chat.v1.Thread;

// This sample shows how to create message with a thread key with user
// credential.
public class CreateMessageUserCredThreadKey {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        // Creates the message as a reply to the thread specified by thread_key.
        // If it fails, the message starts a new thread instead.
        .setMessageReplyOption(
          MessageReplyOption.REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD)
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!")
          // Thread key specifies a thread and is unique to the chat app
          // that sets it.
          .setThread(Thread.newBuilder().setThreadKey("THREAD_KEY")));
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with thread key
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredThreadKey() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Creates the message as a reply to the thread specified by thread_key
  // If it fails, the message starts a new thread instead
  const messageReplyOption = 'REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD';
  const message = {
    text: 'Hello with user credential!',
    thread: {
      // Thread key specifies a thread and is unique to the chat app
      // that sets it
      threadKey: 'THREAD_KEY'
    }
  };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageReplyOption: messageReplyOption
  });

  // Handle the response
  console.log(response);
}

이 샘플을 실행하려면 다음을 바꾸세요.

  • THREAD_KEY: 스페이스의 기존 스레드 키 또는 새 스레드를 만드는 경우 스레드의 고유한 이름입니다.
  • SPACE_NAME: 스페이스의 name 필드에 있는 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.

메시지 이름 지정

향후 API 호출에서 메시지를 검색하거나 지정하려면 요청에서 messageId 필드를 설정하여 메시지 이름을 지정하면 됩니다. 메시지에 이름을 지정하면 메시지의 리소스 이름에서 시스템 할당 ID (name 필드에 표시됨)를 저장하지 않고도 메시지를 지정할 수 있습니다.

예를 들어 get() 메서드를 사용하여 메시지를 검색하려면 리소스 이름을 사용하여 검색할 메시지를 지정합니다. 리소스 이름은 spaces/{space}/messages/{message} 형식으로 지정됩니다. 여기서 {message}은 시스템 할당 ID 또는 메시지를 만들 때 설정한 맞춤 이름을 나타냅니다.

메시지 이름을 지정하려면 메시지를 만들 때 messageId 필드에 맞춤 ID를 지정합니다. messageId 필드는 Message 리소스의 clientAssignedMessageId 필드 값을 설정합니다.

메시지를 만들 때만 메시지 이름을 지정할 수 있습니다. 기존 메일의 맞춤 ID를 지정하거나 수정할 수는 없습니다. 맞춤 ID는 다음 요구사항을 충족해야 합니다.

  • client-로 시작합니다. 예를 들어 client-custom-name는 유효한 맞춤 ID이지만 custom-name는 그렇지 않습니다.
  • 최대 63자(영문 기준)이며 소문자, 숫자, 하이픈만 포함합니다.
  • 스페이스 내에서 고유합니다. 채팅 앱은 서로 다른 메시지에 동일한 맞춤 ID를 사용할 수 없습니다.

다음 코드는 Chat 앱이 인증된 사용자를 대신하여 ID가 포함된 텍스트 메시지를 지정된 스페이스로 전송하는 방법을 보여줍니다.

Node.js

chat/client-libraries/cloud/create-message-user-cred-message-id.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.messages.create'];

// This sample shows how to create message with user credential with message id
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    // Message id lets chat apps get, update or delete a message without needing
    // to store the system assigned ID in the message's resource name
    messageId: 'client-MESSAGE-ID',
    message: { text: 'Hello with user credential!' }
  };

  // Make the request
  const response = await chatClient.createMessage(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_message_user_cred_message_id.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.create"]

# This sample shows how to create message with user credential with message id
def create_message_with_user_cred_message_id():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMessageRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        # Message id let chat apps get, update or delete a message without needing
        # to store the system assigned ID in the message's resource name.
        message_id = "client-MESSAGE-ID",
        message = {
            "text": "Hello with user credential!"
        }
    )

    # Make the request
    response = client.create_message(request)

    # Handle the response
    print(response)

create_message_with_user_cred_message_id()

자바

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMessageUserCredMessageId.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMessageRequest;
import com.google.chat.v1.Message;

// This sample shows how to create message with message id specified with user
// credential.
public class CreateMessageUserCredMessageId {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.messages.create";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMessageRequest.Builder request = CreateMessageRequest.newBuilder()
        // Replace SPACE_NAME here.
        .setParent("spaces/SPACE_NAME")
        .setMessage(Message.newBuilder()
          .setText("Hello with user credentials!"))
        // Message ID lets chat apps get, update or delete a message without
        // needing to store the system assigned ID in the message's resource
        // name.
        .setMessageId("client-MESSAGE-ID");
      Message response = chatServiceClient.createMessage(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps Script

chat/advanced-service/Main.gs
/**
 * This sample shows how to create message with user credential with message id
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.messages.create'
 * referenced in the manifest file (appsscript.json).
 */
function createMessageUserCredMessageId() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  // Message id lets chat apps get, update or delete a message without needing
  // to store the system assigned ID in the message's resource name
  const messageId = 'client-MESSAGE-ID';
  const message = { text: 'Hello with user credential!' };

  // Make the request
  const response = Chat.Spaces.Messages.create(message, parent, {
    messageId: messageId
  });

  // Handle the response
  console.log(response);
}

이 샘플을 실행하려면 다음을 바꾸세요.

  • SPACE_NAME: 스페이스의 name 필드에 있는 ID입니다. ListSpaces() 메서드를 호출하거나 스페이스의 URL에서 ID를 가져올 수 있습니다.
  • MESSAGE-ID: custom-로 시작하는 메시지의 이름입니다. 지정된 스페이스에서 Chat 앱이 만든 다른 메시지 이름과 달라야 합니다.

문제 해결

Google Chat 앱 또는 카드에서 오류를 반환하면 Chat 인터페이스에 '문제가 발생했습니다'라는 메시지가 표시됩니다. 또는 '요청을 처리할 수 없습니다' Chat UI에 오류 메시지가 표시되지 않지만 Chat 앱이나 카드에서 예기치 않은 결과가 발생하는 경우가 있습니다. 예를 들어 카드 메시지가 표시되지 않을 수 있습니다.

채팅 UI에 오류 메시지가 표시되지 않을 수도 있지만, 채팅 앱의 오류 로깅이 사용 설정된 경우 오류를 수정하는 데 도움이 되는 설명이 포함된 오류 메시지와 로그 데이터를 사용할 수 있습니다. 오류를 확인하고, 디버그하고, 수정하는 데 도움이 필요하면 Google Chat 오류 문제 해결 및 수정을 참고하세요.