메시지 보내 줘

이 가이드에서는 Google Chat 앱에서 메시지를 보내는 다양한 방법을 설명합니다.

  • 사용자 상호작용에 응답하여 실시간으로 문자 메시지 및 카드 메시지를 전송합니다.
  • Message 리소스에서 create 메서드를 호출하여 텍스트 및 카드 메시지를 비동기식으로 전송합니다.
  • 메시지 대화목록을 시작하거나 답장합니다.
  • 메시지를 보내고 이름을 지정합니다.

Message 리소스는 Google Chat의 텍스트 또는 카드 메시지를 나타냅니다. 상응하는 메서드를 호출하여 Google Chat API에서 메시지를 create, get, update 또는 delete할 수 있습니다. 문자 및 카드 메시지에 관한 자세한 내용은 Google Chat 메시지 개요를 참고하세요.

Google Chat API의 Message 리소스에서 create 메서드를 호출하여 문자 메시지나 카드 메시지를 비동기식으로 보내는 대신, Google Chat 앱은 메시지를 만들어 사용자 상호작용에 실시간으로 응답할 수도 있습니다. 사용자 상호작용에 대한 응답에는 인증이 필요하지 않으며 대화형 대화상자 및 링크 미리보기를 포함한 다른 유형의 메시지도 지원됩니다. 자세한 내용은 Google Chat 앱과의 상호작용 수신 및 응답을 참고하세요.

기본 요건

Node.js

  • Google Chat에 액세스할 수 있는 Google Workspace 계정
  • 게시된 채팅 앱. 채팅 앱을 빌드하려면 이 quickstart을 따르세요.
  • 채팅 앱이 비동기 메시지를 보낼 수 있도록 구성된 승인 실시간으로 메시지를 보내는 데 승인 구성이 필요하지 않습니다.
    • SMS 전송은 다음 두 가지 승인 방법을 모두 지원합니다.
      • chat.messages.create 또는 chat.messages 승인 범위를 사용한 사용자 인증
      • chat.bot 승인 범위를 사용한 앱 인증
    • 카드 메시지를 전송하려면 chat.bot 승인 범위의 앱 인증이 필요합니다.

Python

  • Python 3.6 이상
  • pip 패키지 관리 도구
  • Python용 최신 Google 클라이언트 라이브러리입니다. 설치하거나 업데이트하려면 명령줄 인터페이스에서 다음 명령어를 실행합니다.

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • 게시된 채팅 앱. 채팅 앱을 만들고 게시하려면 Google Chat 앱 빌드를 참고하세요.

  • 채팅 앱이 비동기 메시지를 보낼 수 있도록 구성된 승인 실시간으로 메시지를 보내는 데 승인 구성이 필요하지 않습니다.

    • SMS 전송은 다음 두 가지 승인 방법을 모두 지원합니다.
      • chat.messages.create 또는 chat.messages 승인 범위를 사용한 사용자 인증
      • chat.bot 승인 범위를 사용한 앱 인증
    • 카드 메시지를 전송하려면 chat.bot 승인 범위의 앱 인증이 필요합니다.

Apps Script

문자 메시지 보내기

이 섹션에서는 다음 두 가지 방법으로 문자 메시지를 보내는 방법을 설명합니다.

  • 사용자 상호작용에 응답하여 실시간으로 문자 메시지를 전송합니다.
  • Google Chat API를 비동기식으로 호출하여 문자 메시지를 보냅니다.

실시간으로 문자 메시지 보내기

이 예시에서 채팅 앱은 문자 메시지가 스페이스에 추가될 때마다 문자 메시지를 만들어 전송합니다. 사용자를 온보딩하기 위한 권장사항을 알아보려면 유용한 온보딩으로 사용자 및 스페이스 시작하기를 참고하세요.

사용자가 채팅 앱을 스페이스에 추가할 때 문자 메시지를 보내려면 채팅 앱이 ADDED_TO_SPACE 상호작용 이벤트에 응답합니다. ADDED_TO_SPACE 상호작용 이벤트에 SMS로 응답하려면 다음 코드를 사용하세요.

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if(req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

Apps Script

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

코드 샘플은 다음 문자 메시지를 반환합니다.

온보딩 메시지의 예

비동기식으로 문자 메시지 보내기

다음 섹션에서는 앱 인증 및 사용자 인증을 사용하여 비동기식으로 문자 메시지를 보내는 방법을 설명합니다.

문자 메시지를 보내려면 요청에 다음을 전달합니다.

  • 앱 인증을 사용하면 chat.bot 승인 범위를 지정합니다. 사용자 인증을 사용하여 chat.messages.create 승인 범위를 지정합니다.
  • Message 리소스에서 create 메서드를 호출합니다.

앱 인증이 포함된 문자 메시지 보내기

앱 인증을 사용하여 문자 메시지를 보내는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에 chat_create_text_message_app.py라는 파일을 만듭니다.
  2. chat_create_text_message_app.py에 다음 코드를 포함합니다.

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list() 메서드 또는 스페이스의 URL에서 얻을 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_create_text_message_app.py
    

Chat API는 전송된 메시지를 자세히 설명하는 Message의 인스턴스를 반환합니다.

사용자 인증이 포함된 문자 메시지 보내기

사용자 인증을 사용하여 문자 메시지를 보내는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에 chat_create_text_message_user.py라는 파일을 만듭니다.
  2. chat_create_text_message_user.py에 다음 코드를 포함합니다.

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list() 메서드 또는 스페이스의 URL에서 가져올 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_create_text_message_user.py
    

Chat API는 전송된 메시지를 자세히 설명하는 Message의 인스턴스를 반환합니다.

카드 메시지 전송

이 섹션에서는 다음 두 가지 방법으로 카드 메시지를 보내는 방법을 설명합니다.

  • 사용자 상호작용에 응답하여 실시간으로 카드 메시지를 전송합니다.
  • Google Chat API를 비동기식으로 호출하여 카드 메시지를 전송합니다.

실시간으로 카드 메시지 전송

채팅 앱은 카드 메시지를 만들어 사용자가 채팅 앱에 메시지를 보내거나 채팅 앱을 스페이스에 추가하는 경우와 같은 사용자 상호작용에 응답할 수 있습니다. 사용자 상호작용에 응답하는 방법에 대한 자세한 내용은 Chat 앱 상호작용 이벤트 수신 및 응답을 참조하세요.

이 예에서는 사용자가 채팅 앱에 메시지를 보내면 채팅 앱은 사용자의 이름과 아바타 이미지를 표시하는 카드 메시지를 전송하여 응답합니다.

보낸 사람의 표시 이름과 아바타 이미지가 포함된 카드로 응답하는 채팅 앱

Node.js

node/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @param {Object} res Response to send back
 */
exports.helloChat = function helloChat(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send('Hello! This function is meant to be used in a Google Chat ' +
      'Room.');
  }

  const sender = req.body.message.sender.displayName;
  const image = req.body.message.sender.avatarUrl;

  const data = createMessage(sender, image);

  res.send(data);
};

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} imageUrl the URL for the sender's avatar
 * @return {Object} a card with the user's avatar.
 */
function createMessage(displayName, imageUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`,
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '},
  };

  const avatarImageWidget = {
    image: {imageUrl},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-app/main.py
from typing import Any, Mapping

import flask
import functions_framework


# Google Cloud Function that responds to messages sent in
# Google Chat.
#
# @param {Object} req Request sent from Google Chat.
# @param {Object} res Response to send back.
@functions_framework.http
def hello_chat(req: flask.Request) -> Mapping[str, Any]:
  if req.method == "GET":
    return "Hello! This function must be called from Google Chat."

  request_json = req.get_json(silent=True)

  display_name = request_json["message"]["sender"]["displayName"]
  avatar = request_json["message"]["sender"]["avatarUrl"]

  response = create_message(name=display_name, image_url=avatar)

  return response


# Creates a card with two widgets.
# @param {string} name the sender's display name.
# @param {string} image_url the URL for the sender's avatar.
# @return {Object} a card with the user's avatar.
def create_message(name: str, image_url: str) -> Mapping[str, Any]:
  avatar_image_widget = {"image": {"imageUrl": image_url}}
  avatar_text_widget = {"textParagraph": {"text": "Your avatar picture:"}}
  avatar_section = {"widgets": [avatar_text_widget, avatar_image_widget]}

  header = {"title": f"Hello {name}!"}

  cards = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps Script

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

비동기식으로 카드 메시지 전송

카드 메시지를 보내려면 요청에 다음을 전달합니다.

  • 앱 인증을 사용하면 chat.bot 승인 범위를 지정합니다. 사용자 인증으로 카드 메시지를 보낼 수 없습니다.
  • Message 리소스에서 create 메서드를 호출합니다.

다음은 카드 메시지의 예입니다.

Chat API를 사용하여 전송된 카드 메시지

앱 인증으로 카드 메시지를 보내는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에 chat_create_card_message.py라는 파일을 만듭니다.
  2. chat_create_card_message.py에 다음 코드를 포함합니다.

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 얻을 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_create_card_message.py
    

메시지 대화목록 시작 또는 답장

메시지 대화목록을 시작하려면 메시지를 보내고 thread.name을 비워 두세요. Google Chat에서 대화목록을 만들 때 메시지를 채웁니다. 필요한 경우 스레드 이름을 맞춤설정하려면 thread.threadKey 필드를 지정합니다.

메시지 스레드에 응답하려면 스레드의 threadKey 또는 name 필드를 지정하는 메시지를 보냅니다. 스레드가 사람이나 다른 채팅 앱에서 생성된 경우 thread.name 필드를 사용해야 합니다.

일치하는 스레드가 없으면 messageReplyOption 필드를 설정하여 메시지를 새 스레드를 시작할지 아니면 게시할 수 없는지 지정할 수 있습니다.

threadKey 필드가 nameOfThread로 정의된 스레드를 시작하거나 대화목록에 답장하는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에 chat_create_message_thread.py라는 파일을 만듭니다.
  2. chat_create_message_thread.py에 다음 코드를 포함합니다.

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 얻을 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_create_message_thread.py
    

Chat API는 전송된 메시지를 자세히 설명하는 Message의 인스턴스를 반환합니다.

메시지 보내기 및 이름 지정

이 섹션에서는 맞춤 이름으로 메시지를 보내는 방법을 설명합니다. 메시지 이름을 사용하여 메시지를 가져오고 업데이트 또는 삭제할 수 있습니다. 또한 커스텀 이름을 할당하면 채팅 앱이 메시지를 보낼 때 반환된 응답 본문에서 메시지 name을 저장하지 않고 메시지를 회수할 수 있습니다.

커스텀 이름을 할당해도 생성된 name 필드(메시지의 리소스 이름)가 대체되지 않습니다. 대신 커스텀 이름을 clientAssignedMessageId 필드로 설정하며, 메시지 업데이트 또는 삭제와 같은 이후 작업을 처리하는 동안 참조할 수 있습니다.

맞춤 이름의 요구사항은 다음과 같습니다.

  • client-로 시작합니다. 예를 들어 client-custom-name은 유효한 맞춤 이름이지만 custom-name는 그렇지 않습니다.
  • 소문자, 숫자, 하이픈만 포함해야 합니다.
  • 63자(영문 기준) 이하여야 합니다.
  • 메시지를 전송하는 동안 사용된 커스텀 이름을 지정하면 오류가 반환되지만 updatedelete와 같은 다른 메서드는 예상대로 작동합니다.

메시지를 보내고 이름을 지정하는 방법은 다음과 같습니다.

Python

  1. 작업 디렉터리에 chat_create_named_message.py라는 파일을 만듭니다.
  2. chat_create_named_message.py에 다음 코드를 포함합니다.

    from httplib2 import Http
    from oauth2client.service_account import ServiceAccountCredentials
    from apiclient.discovery import build
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = ServiceAccountCredentials.from_json_keyfile_name(
        'credentials.json', SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', http=CREDENTIALS.authorize(Http()))
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-custom-name',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. 코드에서 SPACE을 스페이스 이름으로 바꿉니다. 이 이름은 Chat API의 spaces.list 메서드 또는 스페이스의 URL에서 얻을 수 있습니다.

  4. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python3 chat_create_named_message.py
    

Chat API는 전송된 메시지를 자세히 설명하는 Message의 인스턴스를 반환합니다.

문제 해결

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

Chat UI에 오류 메시지가 표시되지 않더라도 채팅 앱에 대한 오류 로깅을 사용 설정한 경우 오류에 대해 설명하는 오류 메시지 및 로그 데이터가 제공됩니다. 오류를 보고 디버깅하고 수정하는 데 도움이 필요하면 Google Chat 오류 문제 해결 및 수정하기를 참고하세요.