카드 메시지 만들기

앱 인증을 사용하면 문자 메시지 외에도 카드 메시지를 만들 수 있습니다. 카드는 정의된 레이아웃, 버튼과 같은 대화형 UI 요소 및 이미지와 같은 리치 미디어를 지원합니다.

카드 메시지를 사용하여 다음을 수행합니다.

  • 자세한 정보 표시
  • 사용자로부터 정보 수집하기
  • 사용자에게 다음 단계를 안내

이 가이드에서는 동기식으로(사용자에게 메시지를 받거나 스페이스에 추가하는 것과 같은 Google Chat 이벤트에 관한 실시간 응답) 동기식으로 카드 메시지를 만드는 방법 및 Google Chat API를 사용하여 메시지가 표시되지 않고 앱에서 스페이스 또는 사용자에게 메시지를 보내는 방법을 설명합니다.

기본 요건

이 가이드에서 카드 메시지를 만들려면 다음이 필요합니다.

Node.js

참고: 이 가이드의 Node.js 코드 샘플은 Google Cloud 함수로 실행되도록 작성되었습니다.

Python

참고: 이 가이드의 Python 코드 샘플은 Python 3.9를 사용하여 Google Cloud 함수로 실행되도록 작성되었습니다.

Apps Script

카드 메시지 분석

각 카드는 대화상자이든 메시지든 Google Chat API의 spaces.messages 리소스에 있는 JSON 객체입니다.

카드 JSON 객체는 다음으로 구성됩니다.

  1. 하나 이상의 CardWithId 객체를 포함하는 cardsV2[]라는 배열입니다.
  2. cardId: 카드를 식별하고 지정된 메시지 내에서 범위를 지정합니다. 다른 메시지에 포함된 카드의 ID는 동일할 수 있습니다.
  3. card 객체로 구성되며 다음 요소로 구성됩니다.

    • 제목, 부제목, 아바타 스타일 이미지 등을 지정하는 header 객체.
    • 각각 하나 이상의 위젯이 포함된 section 객체 한 개 이상
    • 하나 이상의 widget 객체 각 위젯은 텍스트, 이미지, 버튼, 기타 객체 유형을 나타낼 수 있는 복합 객체입니다.

예를 들어 다음 카드 메시지에서 header, section, widget 객체를 관찰합니다.

카드 메시지를 사용하여 Chat 스페이스에서 설문조사를 실행하는 Chat 앱

다음 코드는 카드 메시지의 JSON을 나타냅니다.

JSON

{
  "cardsV2": [
    {
      "cardId": "unique-card-id",
      "card": {
        "header": {
          "title": "Sasha",
          "subtitle": "Software Engineer",
          "imageUrl":
          "https://developers.google.com/chat/images/quickstart-app-avatar.png",
          "imageType": "CIRCLE",
          "imageAltText": "Avatar for Sasha",
        },
        "sections": [
          {
            "header": "Contact Info",
            "collapsible": true,
            "uncollapsibleWidgetsCount": 1,
            "widgets": [
              {
                "decoratedText": {
                  "startIcon": {
                    "knownIcon": "EMAIL",
                  },
                  "text": "sasha@example.com",
                }
              },
              {
                "decoratedText": {
                  "startIcon": {
                    "knownIcon": "PERSON",
                  },
                  "text": "<font color=\"#80e27e\">Online</font>",
                },
              },
              {
                "decoratedText": {
                  "startIcon": {
                    "knownIcon": "PHONE",
                  },
                  "text": "+1 (555) 555-1234",
                }
              },
              {
                "buttonList": {
                  "buttons": [
                    {
                      "text": "Share",
                      "onClick": {
                        "openLink": {
                          "url": "https://example.com/share",
                        }
                      }
                    },
                    {
                      "text": "Edit",
                      "onClick": {
                        "action": {
                          "function": "goToView",
                          "parameters": [
                            {
                              "key": "viewType",
                              "value": "EDIT",
                            }
                          ],
                        }
                      }
                    },
                  ],
                }
              },
            ],
          },
        ],
      },
    }
  ],
}

동기식 카드 메시지 만들기

이 예에서는 사용자가 Chat에서 Chat 앱을 만들고 앱이 발신자의 이름과 아바타 이미지를 보여주는 간단한 동기식 카드 메시지를 보내는 방식으로 응답합니다.

발신자의 표시 이름과 아바타 이미지가 표시된 카드로 응답하는 채팅 앱

다음 코드 샘플에서 Node.js 및 Python 앱은 Google Cloud Functions에 호스팅됩니다. Apps Script 예는 Google Apps Script에 호스팅됩니다.

Chat 앱을 빌드하고 배포하는 방법에 관한 자세한 안내는 Chat 앱 빌드를 참고하세요.

Node.js

node/avatar-bot/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Hangouts Chat room.
 *
 * @param {Object} req Request sent from Hangouts 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 Hangouts 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 {
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-bot/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 = {
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps Script

apps-script/avatar-bot/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 {
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Chat API로 비동기 카드 메시지 만들기

이 예에서는 Chat API를 사용하여 비동기식으로 메시지를 만들고 Chat 앱이 추가된 스페이스로 전송합니다.

Google Chat API로 만든 카드 메시지
그림 1: 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(
        'service_account.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 Chat REST 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
    

Chat API에서 메시지를 사용하는 방법을 자세히 알아보려면 다음을 참고하세요.

대화상자 열기

대화상자는 채팅 앱이 사용자와 상호작용하기 위해 여는 카드 기반 인터페이스입니다. 사용자가 순차적 프로세스를 완료할 수 있도록 앱에서 순차적 대화상자를 열 수 있습니다. 앱은 카드 메시지의 버튼 클릭 또는 슬래시 명령어에 대한 응답으로 대화상자를 열 수 있습니다.

대화상자는 다음과 같은 여러 유형의 사용자 상호작용에 유용합니다.

  • 사용자로부터 정보 수집하기
  • 웹 서비스로 사용자 인증
  • Chat 앱 설정 구성하기

이 예에서 채팅 앱은 대화상자를 열어 사용자가 주소록에 새 연락처를 만들 수 있도록 도와줍니다.

다양한 위젯이 있는 대화상자

대화상자를 구현하려면 대화상자 열기를 참고하세요.

카드 형식 지정

카드의 모양을 지정하는 방법에는 여러 가지가 있습니다.

카드 텍스트 형식 지정

카드 내부에서는 대부분의 텍스트 필드가 작은 HTML 태그 하위 집합을 사용하여 기본 텍스트 형식을 지원합니다.

다음 표에는 지원되는 태그와 그 용도가 나와 있습니다.

형식 렌더링된 결과
굵게 "This is <b>bold</b>." 굵은 글꼴입니다.
기울임꼴 "This is <i>italics</i>." 기울임꼴입니다.
밑줄 "This is <u>underline</u>." 밑줄입니다.
취소선 "This is <s>strikethrough</s>." 이 경우 취소선을 사용합니다.
글꼴 색상 "This is <font color=\"#FF0000\">red font</text>." 이는 빨간색 글꼴입니다.
하이퍼링크 "This is a <a href=\"https://www.google.com\">hyperlink</a>." 하이퍼링크입니다.
시간 "This is a time format: <time>2023-02-16 15:00</time>." 시간 형식은 입니다.
줄바꿈 "This is the first line. <br> This is a new line." 첫 번째 줄입니다.
새 줄입니다.

기본 메시지의 텍스트 본문은 실제 사용자에게 최적화된 다른 마크업 구문을 사용하여 파싱됩니다. 자세한 내용은 문자 메시지 만들기를 참고하세요.

기본 제공 아이콘

DecoratedTextButtonList 위젯은 Google Chat에서 사용할 수 있는 내장 아이콘 중 하나를 지정하는 데 사용되는 icon 요소를 지원합니다.

{
  .
  .
  .
      "knownIcon": "TRAIN",
  .
  .
  .
}

다음 표에는 카드 메시지에 사용할 수 있는 내장 아이콘이 나와 있습니다.

비행기 북마크
버스 CAR
시계 확인_번호_아이콘
DESCRIPTION 달러
이메일 EVENT_SEAT
항공편 항공편
호텔 HOTEL_ROOM_TYPE
초대 MAP_PIN
멤버십 다중 사용자
사용자 휴대전화
레스토랑_아이콘 장바구니
별표 스토어
티켓 학습
동영상 카메라 동영상 재생

맞춤 아이콘

DecoratedTextButtonList 위젯을 사용하면 내장된 아이콘을 사용하거나 맞춤 아이콘을 직접 정의할 수 있습니다. 맞춤 아이콘을 지정하려면 다음과 같이 iconUrl 요소를 사용합니다.

{ . . "iconUrl": "https://developers.google.com/chat/images/quickstart-app-avatar.png" . . }