メッセージを送信する

このガイドでは、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 アカウント。
  • 公開 Chat アプリ。Chat アプリを作成するには、このquickstartに沿って操作します。
  • Chat アプリが非同期メッセージを送信するために構成されている認可。リアルタイムでメッセージを送信するために認可構成は必要ありません。

Python

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

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • 公開済みの Chat アプリ。Chat アプリを作成して公開するには、Google Chat アプリを作成するをご覧ください。

  • Chat アプリが非同期メッセージを送信するために構成されている認可。リアルタイムでメッセージを送信するために認可構成は必要ありません。

Apps Script

  • Google Chat へのアクセス権を持つ Google Workspace アカウント。
  • 公開 Chat アプリ。Chat アプリを作成するには、このquickstartに沿って操作します。

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

このセクションでは、次の 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 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 のインスタンスを返します。

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

このセクションでは、次の 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 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 フィールドを指定するメッセージを送信します。スレッドがユーザーまたは別の Chat アプリによって作成された場合は、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 のインスタンスを返します。

メッセージを送信して名前を付ける

このセクションでは、カスタム名でメッセージを送信する方法について説明します。メッセージ名は、メッセージの取得更新削除に使用します。また、カスタム名を割り当てると、Chat アプリは、メッセージの送信時に返されたレスポンスの本文にあるメッセージ 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 のインターフェースに「エラーが発生しました」または「リクエストを処理できませんでした」というメッセージが表示されます。Chat の UI にエラー メッセージが表示されなくても、Chat アプリやチャットカードで予期しない結果(カード メッセージが表示されないなど)が生成される場合があります。

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