メッセージを送信する

このガイドでは、Google Chat アプリから送信される メッセージ:

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

Message リソース は、 テキスト または カード Google Chat で管理できます。Google Chat では Google Chat API でメッセージを creategetupdatedelete のいずれかに 対応するメソッドがあります。テキスト メッセージとカード メッセージについて詳しくは、以下をご覧ください。 Google Chat メッセージの概要

メッセージの最大サイズ(テキストやカードを含む)は 32,000 バイトです。 メッセージがこのサイズを超える場合、Chat アプリは 複数のメッセージを送信できます

次の Message リソースで create メソッドを呼び出す代わりに、 Google Chat API を使用して、テキスト メッセージやカード メッセージを非同期で送信し、 Google Chat アプリでは、Google Chat でのユーザー操作に応答するメッセージも できます。ユーザー操作に対するレスポンスには認証は必要なく、 対話型ダイアログやリンクを含む、他の種類のメッセージをサポートします。 プレビューします。詳しくは、 Google Chat アプリとのやり取りを受信して応答する

前提条件

Node.js

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

Python

  • Google Workspace アクセス権があるアカウント Google Chat
  • 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 Workspace アクセス権があるアカウント Google Chat
  • 公開されている Chat アプリ。独自の Chat アプリについては、 クイックスタート
  • 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`.'
  }
}

このコードサンプルは、次のテキスト メッセージを返します。

オンボーディング メッセージの例。

テキスト メッセージを非同期で送信する

次のセクションでは、テキスト メッセージを非同期で送信する方法について説明します。 アプリ認証とユーザー認証の 2 つがあります

テキスト メッセージを送信するには、リクエストに次のものを渡します。

  • アプリ認証では、chat.bot 承認スコープを指定します。あり ユーザー認証には、chat.messages.create 承認スコープを指定します。
  • 呼び出し create メソッド 日付 Message リソース

アプリの認証を使用してテキスト メッセージを送信する

Google Chat でテキスト メッセージを送信する方法は次のとおりです。 アプリの認証:

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 をスペース名に置き換えます。スペースには こちらの spaces.list() メソッド スペースの URL から取得できます。

  4. 作業ディレクトリでサンプルをビルドして実行します。

    python3 chat_create_text_message_app.py
    

Chat API は、メッセージに対して Message 送信されるメッセージの詳細を作成します

ユーザー認証を使用してテキスト メッセージを送信する

Google Chat でテキスト メッセージを送信する方法は次のとおりです。 ユーザー認証:

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 message.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. コードで SPACE をスペース名に置き換えます。スペースには こちらの 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

この例では、メッセージにカード メッセージを送信する際に、 カード JSON。 また、 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 承認スコープを指定します。できないこと ユーザー認証付きのカード メッセージを送信します。
  • 呼び出し create メソッド 日付 Message リソース

カード メッセージの例を次に示します。

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 をスペース名に置き換えます。スペースには こちらの spaces.list メソッド スペースの URL から取得できます。

  4. 作業ディレクトリでサンプルをビルドして実行します。

    python3 chat_create_card_message.py
    

メッセージ スレッドを開始または返信する

メッセージ スレッドを開始するには、メッセージを送信してから退出してください thread.name empty;このメッセージは、スレッドの作成時に Google Chat によって入力されます。必要に応じて、 スレッド名をカスタマイズする場合は、 thread.threadKey 表示されます。

メッセージ スレッドに返信するには、そのスレッドのスレッド名 threadKey または name フィールド。スレッドの作成者が他のユーザーであるか 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 をスペース名に置き換えます。スペースには こちらの spaces.list メソッド スペースの URL から取得できます。

  4. 作業ディレクトリでサンプルをビルドして実行します。

    python3 chat_create_message_thread.py
    

Chat API は、メッセージに対して Message 送信されるメッセージの詳細を作成します

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

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

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

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

メッセージに名前を付けることができるのは、メッセージの作成時のみです。名前やメールアドレスを 既存のメッセージのカスタム 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 メッセージを投稿します。この情報は spaces.list メソッド スペースの URL から取得できます。
    • NAME: メッセージのカスタム名。
  4. 作業ディレクトリでサンプルをビルドして実行します。

    python3 chat_create_named_message.py
    

Chat API は、メッセージに対して Message

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

<ph type="x-smartling-placeholder">

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

  • メッセージの正確性または満足度を評価してください。
  • メッセージまたは Chat アプリに関する問題を報告します。
  • ドキュメントなどの関連コンテンツへのリンクを開きます。
  • Chat アプリから類似のメッセージを閉じる、またはスヌーズする 表示されなくなります。

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

次の図に、メッセージに ユーザーがエクスペリエンスを評価できるアクセサリ ウィジェットを含むテキスト メッセージ やり取りできます。

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

次のコードサンプルは、このメッセージの 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 アプリまたは card がエラーを返した場合、 Chat のインターフェースに「エラーが発生しました」というメッセージが表示されている。 または「リクエストを処理できません」が表示されます。場合によっては、Chat の UI が エラー メッセージは表示されませんが、Chat 用アプリまたは 予期しない結果が生じた場合たとえば、カード メッセージに 表示されます。

Chat UI にエラー メッセージが表示されない場合がありますが、 エラーの修正に役立つ、わかりやすいエラー メッセージとログデータ Chat 用アプリのエラーロギングが有効になっている場合。表示のヘルプについては、 エラーの修正について詳しくは、このモジュールの Google Chat のエラーのトラブルシューティングと修正