メッセージを送信する

このガイドでは、Google Chat アプリがメッセージを送信するさまざまな方法について説明します。

  • ユーザーの操作に応答して、テキスト メッセージやカード メッセージをリアルタイムで送信する。
  • Message リソースの create メソッドを呼び出して、テキスト メッセージとカード メッセージを非同期で送信します。
  • メッセージ スレッドを開始する、またはスレッドに返信する。
  • メッセージを送信して名前を付ける。

Message リソースは、Google Chat のテキスト メッセージまたはカード メッセージを表します。Google Chat API でメッセージを creategetupdatedelete のいずれかにするには、対応するメソッドを呼び出します。テキスト メッセージとカード メッセージの詳細については、Google Chat メッセージの概要をご覧ください。

Google Chat アプリでは、Google Chat API の Message リソースの create メソッドを呼び出してテキスト メッセージやカード メッセージを非同期で送信する代わりに、ユーザーの操作にリアルタイムで応答するメッセージを作成することもできます。ユーザー操作に対するレスポンスに認証は不要です。インタラクティブなダイアログやリンク プレビューなど、他の種類のメッセージがサポートされています。詳しくは、Google Chat アプリでのやり取りを受信して対応するをご覧ください。

前提条件

Node.js

  • Google Chat へのアクセス権を持つ Google Workspace アカウント。
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリに非同期メッセージを送信するために構成された認可。メッセージをリアルタイムで送信する場合、認可構成は必要ありません。

Python

  • Google Chat へのアクセス権を持つ Google Workspace アカウント。
  • Python 3.6 以降
  • pip パッケージ管理ツール
  • Python 用の最新の Google クライアント ライブラリ。これらをインストールまたは更新するには、コマンドライン インターフェースで次のコマンドを実行します。

    pip3 install --upgrade google-api-python-client google-auth
    
  • Google Chat API が有効で構成された Google Cloud プロジェクト。手順については、Google Chat アプリを作成するをご覧ください。
  • Chat アプリに非同期メッセージを送信するために構成された認可。メッセージをリアルタイムで送信する場合、認可構成は必要ありません。

Apps Script

  • Google Chat へのアクセス権を持つ Google Workspace アカウント。
  • 公開されている Chat アプリ。Chat アプリを作成するには、このquickstartの手順に沿ってください。
  • Chat アプリに非同期メッセージを送信するために構成された認可。メッセージをリアルタイムで送信する場合、認可構成は必要ありません。

テキスト メッセージを送信する

このセクションでは、次の 2 つの方法でテキスト メッセージを送信する方法について説明します。

  • ユーザーの操作に応答して、テキスト メッセージをリアルタイムで送信します。
  • Google Chat API を非同期で呼び出して、テキスト メッセージを送信します。

テキスト メッセージをリアルタイムで送信する

この例では、Chat アプリがスペースに追加されるたびにテキスト メッセージを作成して送信します。ユーザーのオンボーディングに関するベスト プラクティスについては、有用なオンボーディングでユーザーとスペースの利用を開始するをご覧ください。

ユーザーが Chat アプリをスペースに追加したときにテキスト メッセージを送信するために、Chat アプリは ADDED_TO_SPACE インタラクション イベントに応答します。ADDED_TO_SPACE インタラクション イベントにテキスト メッセージで応答するには、次のコードを使用します。

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 apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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 のインスタンスを返します。

カード メッセージを送信する

このセクションでは、次の 2 つの方法でカード メッセージを送信する方法について説明します。

  • ユーザーの操作に応答して、カード メッセージをリアルタイムで送信します。
  • Google Chat API を非同期で呼び出して、カード メッセージを送信します。


カードビルダーでカードをデザインしてプレビューする。

カードビルダーを開く

カード メッセージをリアルタイムで送信する

Chat アプリでは、ユーザーが Chat アプリにメッセージを送信したり、Chat アプリをスペースに追加したりしたときなど、ユーザー インタラクションに応答するカード メッセージを作成できます。ユーザー操作に応答する方法について詳しくは、Chat アプリ操作イベントの受信と応答をご覧ください。

この例では、ユーザーが Chat アプリにメッセージを送信し、Chat アプリがユーザーの名前とアバター画像を表示するカード メッセージを送信して応答します。

送信者の表示名とアバター画像を含むカードで応答する 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 apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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 フィールドを指定するメッセージを送信します。スレッドがユーザーまたは別の Chat アプリによって作成された場合は、thread.name フィールドを使用する必要があります。

一致するスレッドが見つからない場合は、messageReplyOption フィールドを設定して、メッセージで新しいスレッドを開始するか、投稿に失敗するかを指定できます。

messageReplyOption が設定されている場合は、thread.name または thread.threadKey も設定する必要があります。

threadKey フィールドが nameOfThread として定義されたスレッドを開始または返信する方法は次のとおりです。

Python

  1. 作業ディレクトリに chat_create_message_thread.py という名前のファイルを作成します。
  2. chat_create_message_thread.py に次のコードを追加します。

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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 のインスタンスを返します。

メッセージに名前を付ける

このセクションでは、メッセージにカスタム ID を設定して名前を付ける方法について説明します。カスタム ID を使用すると、メッセージを取得、更新、削除できます。カスタム ID を使用すると、メッセージのリソース名(name フィールドで表されます)からシステム割り当ての ID を保存しなくても、メッセージを指定できます。リソース名は、メッセージの作成時にレスポンスの本文で生成されます。

たとえば、get() メソッドを使用してメッセージを取得するには、リソース名を使用して、取得するメッセージを指定します。リソース名の形式は spaces/{space}/messages/{message} です。ここで、{message} はシステム割り当ての ID を表します。メッセージに名前を付けた場合は、{message} の値をカスタム ID に置き換えることができます。

メッセージに名前を付けるには、メッセージの作成時に messageId フィールドにカスタム ID を指定します。messageId フィールドには、Message リソースの clientAssignedMessageId フィールドの値を設定します。

メッセージに名前を付けることができるのは、メッセージの作成時のみです。既存のメッセージにカスタム ID の名前やカスタム ID を変更することはできません。カスタム ID は次の要件を満たす必要があります。

  • client- で始まります。たとえば、client-custom-name は有効なカスタム ID ですが、custom-name は異なります。
  • 最大 63 文字で、英小文字、数字、ハイフンのみを使用できます。
  • スペース内で一意である。Chat アプリでは、異なるメッセージに同じカスタム ID を使用できません。

カスタム ID を使ってメッセージを送信する方法は次のとおりです。

Python

  1. 作業ディレクトリに chat_create_named_message.py という名前のファイルを作成します。
  2. chat_create_named_message.py に次のコードを追加します。

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # 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-NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. コードで、次のように置き換えます。

    • SPACE: メッセージを送信するスペースの ID。Chat API の spaces.list メソッドまたはスペースの URL から取得できます。
    • NAME: メッセージのカスタム名。
  4. 作業ディレクトリで、サンプルをビルドして実行します。

    python3 chat_create_named_message.py
    

Chat API は Message のインスタンスを返します。

メッセージの下部にインタラクティブなウィジェットを追加する

必要に応じて、アクセサリ ウィジェットを使用してメッセージを追加できます。 アクセサリ ウィジェットは、メッセージ内のテキストやカードの後に表示されます。これらのウィジェットを使用すると、次のようなさまざまな方法でユーザーにメッセージの操作を促すことができます。

  • メッセージの正確さまたは満足度を評価します。
  • メッセージまたは Chat アプリに関する問題を報告します。
  • ドキュメントなどの関連コンテンツへのリンクを開きます。
  • Chat アプリからの同様のメッセージを、一定期間閉じるかスヌーズします。

アクセサリ ウィジェットを追加するには、メッセージに accessoryWidgets[] オブジェクトを含めて、1 つ以上の AccessoryWidgets を指定します。メッセージはスペース内のすべてのユーザーに表示される必要があります(プライベート メッセージにアクセサリ ウィジェットを追加することはできません)。

次の画像は、ユーザーが Chat アプリの利便性を評価できるように、アクセサリ ウィジェットを含むテキスト メッセージを追加する Chat アプリを示しています。

アクセサリ ウィジェットの例

次のコードサンプルは、このメッセージの JSON を示しています。ユーザーがいずれかのボタンをクリックすると、その操作により、評価を処理する対応する関数(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 アプリでは、テキスト メッセージやカード メッセージを非公開で送信できるため、スペース内の 1 人のユーザーにのみメッセージを表示できます。非公開でメッセージを送信するには、メッセージの privateMessageViewer フィールドを指定します。プライベート メッセージを送信できるのは Chat アプリのみです。プライベート メッセージを非同期で送信するには、アプリ認証を使用する必要があります。

詳しくは、Google Chat ユーザーにプライベート メッセージを送信するをご覧ください。

トラブルシューティング

Google Chat アプリまたはカードからエラーが返されると、Chat インターフェースに「エラーが発生しました」または「リクエストを処理できません」というメッセージが表示されます。Chat UI にエラー メッセージが表示されないにもかかわらず、Chat アプリまたはカードから予期しない結果(カード メッセージが表示されないなど)が発生することがあります。

Chat の UI にエラー メッセージが表示されない場合もありますが、Chat アプリのエラーロギングがオンになっている場合は、エラー メッセージとログデータを使用してエラーを修正できます。エラーの表示、デバッグ、修正については、Google Chat のエラーのトラブルシューティングと修正をご覧ください。