カード メッセージを作成する

Google Chat アプリでは、テキスト メッセージに加えて、スペースとユーザーに対するカード メッセージを作成できます。カードでは、定義されたレイアウト、ボタンなどのインタラクティブな UI 要素、画像などのリッチメディアがサポートされます。

カード メッセージを使用すると、次のことができます。

  • 詳細情報を表示する
  • ユーザーから情報を収集する
  • ユーザーに次のステップについて案内する

このガイドでは、カード メッセージを同期的に作成する(ユーザーからのメッセージ受信やスペースへの追加など)Google Chat イベントへのリアルタイム レスポンスを作成する方法や、Google Chat API を使用してプロンプトを表示せずにアプリからスペースまたはユーザーにメッセージを送信する方法を紹介します。

Prerequisites

このガイドでカード メッセージを作成するには、次のものが必要です。

Node.js

注: このガイドの Node.js コードサンプルは、Google Cloud Functions の関数として実行するように作成されています。

Python

注: このガイドの Python コードサンプルは、Python 3.9 を使用して Google Cloud Functions の関数として実行するように作成されています。

Apps Script

カード メッセージの構造

各カードは、ダイアログであれメッセージであれ、Google Chat API の spaces.messages リソース上の JSON オブジェクトです。

カード JSON オブジェクトは次の要素で構成されます。

  1. 1 つ以上の CardWithId オブジェクトを含む cardsV2[] という配列。
  2. cardId。カードを識別し、指定されたメッセージの範囲を指定します。(異なるメッセージのカードには同じ ID を使用できます)。
  3. card オブジェクト。これは次の要素で構成されます。

    • タイトル、サブタイトル、アバター形式の画像などを指定する header オブジェクト
    • 少なくとも 1 つのウィジェットを含む 1 つ以上の section オブジェクト
    • 1 つ以上の widget オブジェクト。各ウィジェットは、テキスト、画像、ボタン、その他のオブジェクト タイプを表す複合オブジェクトです。

たとえば、次のカード メッセージ内の headersectionwidget オブジェクトを確認します。

カードメッセージを使用して 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 アプリがユーザーと対話するために開く、ウィンドウ付きのカードベースのインターフェースです。ユーザーがマルチステップ プロセスを完了できるように、アプリで連続したダイアログを開くことができます。アプリは、カード メッセージでのボタンのクリックまたはスラッシュ コマンドに応じてダイアログを開くことができます。

ダイアログは、次のようなさまざまな種類のユーザー操作に役立ちます。

  • ユーザーから情報を収集する
  • ウェブサービスを使用したユーザーの認証
  • 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. これが最初の行です。
これは新しい行です。

基本メッセージのテキスト本文は、人間のユーザー向けに最適化された別のマークアップ構文を使用して解析されます。詳細については、テキスト メッセージの作成をご覧ください。

組み込みのアイコン

DecoratedText ウィジェットと ButtonList ウィジェットは、Google Chat で利用可能な組み込みアイコンのいずれかを指定する icon 要素をサポートしています。

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

次の表に、カード メッセージに使用できる組み込みアイコンを示します。

飛行機 ブックマーク
バス
時計 CONFIRMATION_NUMBER_ICON
DESCRIPTION ドル
メールアドレス EVENT_SEAT
フライトの到着日 フライトの出発
ホテル ホテルの種類
招待 MAP_PIN
メンバーシップ 複数人
人物 スマートフォン
RESTAURANT_ICON ショッピング カート
スター ストア
チケット トレーニング
VIDEO_CAMERA 動画再生

カスタム アイコン

DecoratedText ウィジェットと ButtonList ウィジェットでは、組み込みのアイコンを使用することも、独自のカスタム アイコンを定義することもできます。カスタム アイコンを指定するには、次に示すように iconUrl 要素を使用します。

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