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

이 가이드에서는 Google Chat API의 messages.create() 드림 메서드를 사용하여 다음 중 하나를 수행할 수 있습니다.

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

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

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

채팅 앱은 messages.create() 메서드 호출 외에도 메시지를 작성하고 전송하여 사용자 상호작용에 응답하기(예: 사용자가 채팅 앱을 추가한 후 있습니다. 채팅 앱은 상호작용에 응답할 때 메시지 기능 유형(대화형 대화상자, 링크 미리보기 등) 인터페이스에 추가되었습니다. 사용자에게 답장하기 위해 채팅 앱이 반환됩니다. Chat API를 호출하지 않고 동기식으로 메시지를 보냅니다. 배우기 위해 상호작용에 응답하기 위해 메시지를 보내는 방법은 Google Chat 앱과의 상호작용을 수신하고 응답하세요.

Chat API로 생성된 메시지를 Chat에서 표시하고 기여도를 부여하는 방법

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

채팅 앱으로 인증하면 채팅 앱에서 메시지를 보냅니다.

<ph type="x-smartling-placeholder">
</ph> 앱 인증으로 messages.create() 메서드 호출
그림 1: 앱 인증을 통해 채팅 앱은 확인할 수 있습니다. 발신자가 사람이 아니라는 사실을 알기 위해 Chat에서는 이름 옆에 App라고 표시됩니다.

사용자로 인증하면 채팅 앱에서 메시지가 표시됩니다. Chat은 또한 채팅 앱에서 이름을 표시하여 메시지에 연결합니다.

<ph type="x-smartling-placeholder">
</ph> 사용자 인증을 통해 messages.create() 메서드 호출
그림 2: 사용자 인증을 사용하면 사용자가 메시지를 보내고 Chat에는 사용자 이름 옆의 채팅 앱 이름

인증 유형에 따라 어떤 메시징 기능과 인터페이스가 사용되는지도 결정됩니다. 포함할 수 있습니다. 앱 인증을 사용하면 채팅 앱에서 서식 있는 텍스트, 카드 기반 인터페이스, 대화형 위젯 등이 있습니다. Chat 사용자는 자신의 메시지에 문자 메시지만 보낼 수 있으므로 다음 작업을 할 수 있습니다. 사용자 인증을 사용하여 메일을 작성할 때만 텍스트를 포함합니다. 메시지 기능 자세히 알아보기 Chat API에서 사용할 수 있는 기능에 대한 자세한 내용은 Google Chat 메시지 개요

이 가이드에서는 인증 유형 중 하나를 사용하여 메시지를 보내는 방법을 설명합니다. 채팅 API와 함께 사용할 수 있습니다.

기본 요건

Node.js

Python

자바

Apps Script

Chat 앱으로 메시지 보내기

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

앱 인증과 함께 메시지 전송됨
그림 4. Chat 앱이 텍스트, 카드, 액세서리 버튼이 있습니다.

앱 인증을 사용하여 messages.create()를 호출하려면 요청에 다음 필드를 포함합니다.

  • chat.bot 승인 범위입니다.
  • Space 리소스 선택합니다. 채팅 앱이 다음 조건을 충족해야 합니다. 스페이스의 참여자입니다.
  • 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는 spaces.list() 메서드 삭제할 수 있습니다.

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

이 가이드의 첫 번째 코드 샘플에서는 채팅 앱 메시지는 액세서리 위젯이라고 합니다. 액세서리 위젯 문자 또는 카드 뒤에 표시됩니다. 이 위젯을 사용하여 다음과 같은 다양한 방법으로 메시지와 상호작용할 수 있습니다.

  • 메시지의 정확성 또는 만족도를 평가합니다.
  • 메시지 또는 채팅 앱 문제 신고
  • 문서와 같은 관련 콘텐츠의 링크를 엽니다.
  • Chat 앱에서 비슷한 메시지 닫기 또는 다시 알림 확인할 수 있습니다.

액세서리 위젯을 추가하려면 accessoryWidgets[] 드림 필드를 하나 이상 지정하고 포함할 수 있습니다.

다음 이미지는 다음을 추가하는 채팅 앱을 보여줍니다. 액세서리 위젯이 포함된 문자 메시지로 사용자가 사용 환경을 평가할 수 있음 채팅 앱

<ph type="x-smartling-placeholder">
</ph> 액세서리 위젯
그림 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 API를 사용하여 비공개로 메시지를 보내려면 privateMessageViewer 드림 필드를 확인하시기 바랍니다. 사용자를 지정하려면 값을 User 리소스 Chat 사용자를 나타냅니다. 또한 name 필드 User 리소스에 사용해야 합니다.

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

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

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

사용자를 대신하여 문자 메시지를 보냅니다.

이 섹션에서는 다음을 사용하여 사용자를 대신하여 메일을 보내는 방법을 설명합니다. 사용자 인증 사용자 인증을 사용하면 메일 내용에 텍스트만 포함할 수 있습니다. , 수신자만 사용할 수 있는 메시지 기능은 카드 인터페이스 및 대화형 위젯을 포함한 채팅 앱

사용자 인증과 함께 메시지 전송됨
그림 3. 채팅 앱이 사용자를 대신하여 작성할 수 있습니다

사용자 인증을 사용하여 messages.create()를 호출하려면 요청에 다음 필드를 포함합니다.

  • 승인 범위 사용자 인증을 지원합니다. 다음 샘플에서는 chat.messages.create 범위
  • Space 리소스 선택합니다. 인증된 사용자는 있습니다.
  • Message 만들 수 있습니다 메시지의 콘텐츠를 정의하려면 text 드림 필드를 확인합니다.

원하는 경우 다음을 포함할 수 있습니다.

다음 코드는 채팅 앱이 실행되는 방식을 보여주는 예입니다. 인증된 사용자를 대신하여 지정된 스페이스에서 문자 메시지를 보낼 수 있습니다.

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는 spaces.list() 메서드 삭제할 수 있습니다.

대화목록에서 시작 또는 답장

스레드를 사용하는 스페이스의 경우 새 메시지가 대화목록을 시작할지 또는 삭제할 수 있습니다

기본적으로 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는 spaces.list() 메서드 삭제할 수 있습니다.

메시지 이름 지정

향후 API 호출에서 메시지를 검색하거나 지정하려면 메시지 이름을 지정하면 됩니다. messages.create() 요청에서 messageId 필드를 설정하면 됩니다. 메시지에 이름을 지정하면 해당 메시지를 저장하지 않고도 메시지를 지정할 수 있습니다. 메시지 리소스 이름에서 시스템 할당 ID( name 드림 필드에 포함되어야 합니다.

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

메일 이름을 지정하려면 맞춤 ID를 지정합니다. messageId 드림 필드를 설정할 수 없습니다. messageId 필드는 clientAssignedMessageId Message 리소스의 필드입니다.

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

  • client-로 시작합니다. 예를 들어 client-custom-name는 유효한 커스텀입니다. ID이지만 custom-name는 아닙니다.
  • 최대 63자(영문 기준)까지 소문자, 숫자, 하이픈이 있습니다.
  • 스페이스 내에서 고유합니다. 채팅 앱에서는 여러 메시지에 대해 동일한 맞춤 ID를 사용할 수 있습니다.

다음 코드는 채팅 앱이 실행되는 방식을 보여주는 예입니다. 님을 대신하여 지정된 스페이스에 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는 spaces.list() 메서드 삭제할 수 있습니다.
  • MESSAGE-ID: 시작하는 메시지의 이름입니다. custom-. API 호출로 생성된 다른 메시지 이름과 지정된 스페이스의 채팅 앱

문제 해결

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

채팅 UI에 오류 메시지가 표시되지 않을 수도 있지만 오류 해결에 도움이 되는 오류 메시지 및 로그 데이터를 사용할 수 있음 채팅 앱의 오류 로깅이 사용 설정된 경우 보는 데 도움이 필요한 경우 오류를 수정하는 방법에 대한 자세한 내용은 Google Chat 오류 문제 해결하기