Google Chat アプリのコマンドに応答する

このページでは、Google Chat アプリとしてコマンドを設定して応答する方法について説明します。

コマンドを使用すると、ユーザーは Chat アプリの主な機能を見つけて使用できます。コマンドの内容を表示できるのは Chat アプリのみです。たとえば、ユーザーがスラッシュ コマンドを含むメッセージを送信した場合、そのメッセージはユーザーと Chat アプリにのみ表示されます。

コマンドを構築する必要があるかどうかを判断し、ユーザー インタラクションの設計方法を理解するには、すべてのユーザー ジャーニーを定義するをご覧ください。

Chat 用アプリのコマンドの種類

Chat アプリのコマンドは、スラッシュ コマンド、クイック コマンド、メッセージ アクションとして作成できます。各タイプのコマンドを使用するには、ユーザーは次の操作を行います。
  1. スラッシュ コマンド: ユーザーは、メニューからスラッシュ コマンドを選択するか、スラッシュ(/)を入力してから、/about などの事前定義されたテキストを入力できます。通常、Chat 用アプリでは、スラッシュ コマンドの引数テキストが必要です。

    Chat アプリでユーザーからの追加の入力が必要な場合は、スラッシュ コマンドを作成します。たとえば、ユーザーが検索するフレーズ(/search receipts など)を入力した後に実行される /search というスラッシュ コマンドを作成できます。

  2. クイック コマンド: ユーザーは、チャット メッセージの返信エリアからメニューを開いてコマンドを使用します。コマンドを使用するには、[追加] をクリックし、メニューからコマンドを選択します。

    Chat 用アプリが追加の入力を待たずにユーザーにすぐに返信できる場合は、クイック コマンドを作成します。たとえば、ランダムな画像というクイック コマンドを作成して、画像ですぐに応答できます。

  3. メッセージ アクション: ユーザーは、メッセージにカーソルを合わせてその他メニューをクリックすることで、メッセージ アクションを使用します。コマンドを使用するには、その他メニューを開き、メニューからコマンドを選択します。

    Chat 用アプリがメッセージのコンテキストに基づいてアクションを実行できる場合は、メッセージ アクションを作成します。

次の画像は、ユーザーがスラッシュ コマンド、クイック コマンド、メッセージ アクションのメニューを見つける方法を示しています。

前提条件

HTTP

ユーザー インタラクションを受信して応答する Google Chat アプリ。作成するには、HTTP クイックスタートを完了してください。

Apps Script

ユーザー インタラクションを受信して応答する Google Chat アプリ。作成するには、Apps Script のクイックスタートを完了してください。

コマンドを設定する

このセクションでは、次の手順でコマンドを設定する方法について説明します。

  1. コマンドの名前と説明を作成します。
  2. Google Cloud コンソールでコマンドを構成します。
  3. 省略可: コマンドをスターター プロンプトにマッピングする。

コマンドの名前と説明を入力します

コマンドの名前は、ユーザーが Chat アプリを呼び出すために入力または選択するものです。名前の下には簡単な説明も表示され、コマンドの使用方法をユーザーにさらに促します。

スラッシュ コマンドの名前と説明
スラッシュ コマンドの名前と説明。

コマンドの名前と説明を選択する際は、次の推奨事項を考慮してください。

コマンドに名前を付けるには:

  • 短く、わかりやすく、操作しやすい単語やフレーズを使用して、コマンドをユーザーにわかりやすくします。たとえば、Create a reminder という名前ではなく Remind me を使用します。
  • コマンドには、一意の名前または一般的な名前を使用することを検討してください。コマンドが一般的な操作や機能を表す場合は、Settings や Feedback など、ユーザーが認識して期待する一般的な名前を使用できます。それ以外の場合は、一意のコマンド名を使用するようにしてください。コマンド名が他の Chat 用アプリと同じである場合、ユーザーは類似したコマンドをフィルタして、目的のコマンドを見つけて使用する必要があります。

コマンドの説明を取得するには:

  • 説明は短くわかりやすいものにして、コマンドを使用すると何が起こるかをユーザーが把握できるようにします。
  • コマンドに書式設定の要件がある場合は、ユーザーに知らせます。たとえば、引数テキストを必要とするスラッシュ コマンドを作成する場合は、説明を Remind me to do [something] at [time] のように設定します。
  • Chat 用アプリがスペース内の全員に返信するのか、コマンドを呼び出したユーザーに非公開で返信するのかをユーザーに知らせます。たとえば、クイック コマンド About の場合、Learn about this app (Only visible to you) と記述できます。

Google Cloud コンソールでコマンドを構成する

スラッシュ コマンド、クイック コマンド、メッセージ アクションを作成するには、Google Chat API の Chat アプリの構成で、コマンドまたはアクションに関する情報を指定します。

Google Chat API でコマンドを構成する手順は次のとおりです。

  1. Google Cloud コンソールで、メニュー アイコン > [API とサービス] > [有効な API とサービス] > [Google Chat API] をクリックします。

    [Google Chat API] ページに移動

  2. [構成] をクリックします。

  3. [接続設定] の [トリガー] に移動し、エンドポイントの詳細を指定します。コマンドに応答するには、次のセクションでこのトリガーを使用する必要があります。

    1. HTTP エンドポイント URL: ここで 1 つの共通 HTTP エンドポイント URL を指定できます。または、トリガーごとに異なる HTTP エンドポイントを使用するには、[App command] フィールドにエンドポイントを直接指定します。
    2. Apps Script: Apps Script のデプロイ ID を入力します。デフォルトでは、onAppCommand 関数が呼び出されます。別の Apps Script 関数を使用するには、[アプリコマンド] フィールドにカスタム関数名を指定します。
  4. [コマンド] で、[コマンドを追加] をクリックします。

  5. コマンドに関する次の情報を入力します。

    1. コマンド ID: Chat アプリがコマンドを認識してレスポンスを返すために使用する 1 ~ 1,000 の数値。
    2. 説明: コマンドの使用方法と形式を説明するテキスト。説明文は半角 50 文字(全角 25 文字)以内で指定できます。
    3. コマンドタイプ: [クイック コマンド]、[スラッシュ コマンド]、[メッセージ アクション] のいずれかを選択します。
    4. コマンドの名前を指定します。
      • クイック コマンド名: ユーザーがメニューから選択してコマンドを呼び出す表示名。50 文字以内で、特殊文字を使用できます。例: Remind me
      • スラッシュ コマンド名: ユーザーがメッセージでコマンドを呼び出すために入力するテキスト。先頭はスラッシュにする必要があります。使用できるのはテキストのみで、最大 50 文字です。例: /remindMe
      • メッセージ アクション名: ユーザーがメニューから選択してメッセージ アクションを呼び出す表示名。半角 50 文字以内で指定できます。特殊文字を使用できます。例: Remind me
  6. 省略可: 読み込み通知メッセージ: メッセージ操作の実行中にユーザーに表示するトースト通知メッセージ。ダイアログを開かないメッセージ アクションでのみ使用できます。

  7. 省略可: Chat アプリがダイアログでコマンドに応答するようにする場合は、[ダイアログを開く] チェックボックスをオンにします。

  8. [保存] をクリックします。

これで、Chat アプリにコマンドが構成されました。

コマンドをスターター プロンプトにマッピングする

コマンドをスターター プロンプトとして表示すると、ユーザーが Chat アプリで空の 1 対 1 のダイレクト メッセージを開始したときに、インタラクティブなチップとして表示されます。

コマンドをスターター プロンプトにマッピングするには:

  1. コマンドに追加のカスタム引数が必要ないことを確認します(スターター プロンプトとしてサポートされているのは、引数なしまたは基本引数のコマンドのみです)。
  2. Google Cloud コンソールで、Chat API の [構成] ページに移動します。
  3. [インタラクティブ機能] > [スターター プロンプト] で、[プロンプトを追加] をクリックします。
  4. 表示順位の [Rank (1-3)] を設定します。
  5. [タイプを選択] で [コマンド プロンプト] を選択し、プルダウンからコマンドを選択します。
  6. [完了]、[保存] の順にクリックします。

コマンドに応答する

ユーザーがコマンドを使用すると、Chat 用アプリはイベント オブジェクトを受け取ります。イベント ペイロード(event.chat.appCommandPayload)には、呼び出されたコマンドの詳細(コマンド ID やコマンドタイプなど)を含む appCommandPayload オブジェクトが含まれているため、適切なレスポンスを返すことができます。イベント オブジェクトは、アプリコマンド トリガーを構成したときに指定した HTTP エンドポイントまたは Apps Script 関数に送信されます。

Cymbal Labs Chat アプリのプライベート メッセージ。このメッセージには、Chat アプリが Cymbal Labs によって作成されたことが記載されており、ドキュメントへのリンクとサポートチームへの連絡先リンクが共有されています。
Chat 用アプリがスラッシュ コマンド /help に非公開で応答し、サポートを受ける方法を説明します。

スラッシュ コマンドまたはクイック コマンドに応答する

次のコードは、スラッシュ コマンド /about にテキスト メッセージで返信する Chat 用アプリの例を示しています。スラッシュ コマンドまたはクイック コマンドに応答するために、Chat アプリはアプリコマンド トリガーからのイベント オブジェクト(event.chat.appCommandPayload)を処理します。イベント オブジェクトのペイロードに一致するコマンド ID が含まれている場合、Chat 用アプリは createMessageAction(hostAppDataAction.chatDataAction.createMessageAction)オブジェクトを含むアクション DataActions を返します。

Node.js

node/chat/avatar-app/index.js
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Handle requests from Google Workspace add on
 *
 * @param {Object} req Request sent by Google Chat
 * @param {Object} res Response to be sent back to Google Chat
 */
http('avatarApp', (req, res) => {
  const chatEvent = req.body.chat;
  let message;
  if (chatEvent.appCommandPayload) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: {
    message: message
  }}}});
});

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 * @return the response message object.
 */
function handleAppCommand(event) {
  switch (event.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return {
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/chat/avatar-app/main.py
# The ID of the slash command "/about".
# You must use the same ID in the Google Chat API configuration.
ABOUT_COMMAND_ID = 1

@functions_framework.http
def avatar_app(req: flask.Request) -> Mapping[str, Any]:
  """Handle requests from Google Workspace add on

  Args:
    flask.Request req: the request sent by Google Chat

  Returns:
    Mapping[str, Any]: the response to be sent back to Google Chat
  """
  chat_event = req.get_json(silent=True)["chat"]
  if chat_event and "appCommandPayload" in chat_event:
    message = handle_app_command(chat_event)
  else:
    message = handle_message(chat_event)
  return { "hostAppDataAction": { "chatDataAction": { "createMessageAction": {
      "message": message
  }}}}

def handle_app_command(event: Mapping[str, Any]) -> Mapping[str, Any]:
  """Responds to an APP_COMMAND event in Google Chat.

  Args:
    Mapping[str, Any] event: the event object from Google Chat

  Returns:
    Mapping[str, Any]: the response message object.
  """
  if event["appCommandPayload"]["appCommandMetadata"]["appCommandId"] == ABOUT_COMMAND_ID:
    return {
      "text": "The Avatar app replies to Google Chat messages.",
    }
  return {}

Java

java/chat/avatar-app/src/main/java/com/google/chat/avatar/App.java
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
private static final int ABOUT_COMMAND_ID = 1;

private static final Gson gson = new Gson();

/**
 * Handle requests from Google Workspace add on
 * 
 * @param request the request sent by Google Chat
 * @param response the response to be sent back to Google Chat
 */
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
  JsonObject event = gson.fromJson(request.getReader(), JsonObject.class);
  JsonObject chatEvent = event.getAsJsonObject("chat");
  Message message;
  if (chatEvent.has("appCommandPayload")) {
    message = handleAppCommand(chatEvent);
  } else {
    message = handleMessage(chatEvent);
  }
  JsonObject createMessageAction = new JsonObject();
  createMessageAction.add("message", gson.fromJson(gson.toJson(message), JsonObject.class));
  JsonObject chatDataAction = new JsonObject();
  chatDataAction.add("createMessageAction", createMessageAction);
  JsonObject hostAppDataAction = new JsonObject();
  hostAppDataAction.add("chatDataAction", chatDataAction);
  JsonObject dataActions = new JsonObject();
  dataActions.add("hostAppDataAction", hostAppDataAction);
  response.getWriter().write(gson.toJson(dataActions));
}

/**
 * Handles an APP_COMMAND event in Google Chat.
 *
 * @param event the event object from Google Chat
 * @return the response message object.
 */
private Message handleAppCommand(JsonObject event) throws Exception {
  switch (event.getAsJsonObject("appCommandPayload")
    .getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt()) {
    case ABOUT_COMMAND_ID:
      return new Message()
        .setText("The Avatar app replies to Google Chat messages.");
    default:
      return null;
  }
}

Apps Script

apps-script/chat/avatar-app/Code.gs
// The ID of the slash command "/about".
// You must use the same ID in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 1;

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onAppCommand(event) {
  // Executes the app command logic based on ID.
  switch (event.chat.appCommandPayload.appCommandMetadata.appCommandId) {
    case ABOUT_COMMAND_ID:
      return { hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
        text: 'The Avatar app replies to Google Chat messages.'
      }}}}};
  }
}

このコードサンプルを使用するには、ABOUT_COMMAND_ID を、Chat API でコマンドを構成したときに指定したコマンド ID に置き換えます。

メッセージ アクションに応答する

次のコードは、メッセージ アクション うっかりアラート にテキスト メッセージで返信する Chat 用アプリの例を示しています。メッセージ アクションに応答するために、Chat 用アプリはアプリコマンド トリガーからのイベント オブジェクトを処理します。イベント オブジェクトのペイロードにメッセージ アクション コマンド ID が含まれている場合、Chat 用アプリは createMessageAction オブジェクトを含むアクション DataActions を返します。

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return res.json({
      "hostAppDataAction": {
        "chatDataAction": {
          "createMessageAction": {
            "message": {
              "text": `Setting a reminder for message: "${messageText}"`
            }
          }
        }
      }
    });
  }
}

Python

def on_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    payload = event.get('chat', {}).get('appCommandPayload', {})
    metadata = payload.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = payload.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "hostAppDataAction": {
                "chatDataAction": {
                    "createMessageAction": {
                        "message": {
                            "text": f'Setting a reminder for message: "{message_text}"'
                        }
                    }
                }
            }
        }

Java

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void onAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject payload = event.getAsJsonObject("chat").getAsJsonObject("appCommandPayload");
  JsonObject metadata = payload.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = payload.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);

      JsonObject createMessageAction = new JsonObject();
      createMessageAction.add("message", responseMessage);

      JsonObject chatDataAction = new JsonObject();
      chatDataAction.add("createMessageAction", createMessageAction);

      JsonObject hostAppDataAction = new JsonObject();
      hostAppDataAction.add("chatDataAction", chatDataAction);

      JsonObject finalResponse = new JsonObject();
      finalResponse.add("hostAppDataAction", hostAppDataAction);

      response.getWriter().write(finalResponse.toString());
    }
  }
}

Apps Script

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} =
    event.chat.appCommandPayload.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.chat.appCommandPayload.message.text;

    // Return a response that includes details from the original message.
    return CardService.newChatResponseBuilder()
        .setText("Setting a reminder for message: " + messageText)
        .build();
  }
}

このコードサンプルを使用するには、REMIND_ME_COMMAND_ID を、Chat API でコマンドを構成したときに指定したコマンド ID に置き換えます。

コマンドをテストする

コマンドとコードをテストするには、Google Chat アプリのインタラクティブ機能をテストするをご覧ください。

Chat UI でコマンドをテストして使用する方法については、Google Chat のヘルプ ドキュメントの Google Chat でアプリを使用するをご覧ください。

アドオンではない Chat 用アプリ: コマンドに応答する

以下のドキュメントは、Google Workspace アドオンではない Chat アプリに適用されます。アドオンではない Chat アプリを移行するには、Google Chat アプリを Google Workspace アドオンに変換するをご覧ください。

ユーザーがコマンドを使用すると、アドオンではない Chat アプリはインタラクション イベントを受信し、Message オブジェクトを直接返すことで応答できます。イベント ペイロードには、呼び出されたコマンドの詳細(コマンド ID やコマンドタイプなど)を含むメタデータが含まれているため、適切なレスポンスを返すことができます。

アドオンではない Chat アプリで各タイプのコマンドに応答するには、イベント ペイロード内のさまざまなイベントタイプとメタデータ オブジェクトを処理する必要があります。

コマンドタイプ イベントの種類 コマンド メタデータ
スラッシュ コマンド MESSAGE message.slashCommand または message.annotation.slashCommand
クイック コマンド APP_COMMAND appCommandMetadata
メッセージ操作 APP_COMMAND appCommandMetadata

スラッシュ コマンドに応答する

次のコードは、スラッシュ コマンド /about に返信する、アドオンではない Chat 用アプリの例を示しています。Chat 用アプリは、MESSAGE インタラクション イベントを処理し、インタラクション イベントに一致するコマンド ID が含まれているかどうかを検出して、非公開の Message オブジェクトを返します。

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

Apps Script

apps-script/avatar-app/avatar-app.gs
// Checks for the presence of a slash command in the message.
if (event.message.slashCommand) {
  // Executes the slash command logic based on its ID.
  // Slash command IDs are set in the Google Chat API configuration.
  switch (event.message.slashCommand.commandId) {
    case ABOUT_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

Java

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

ABOUT_COMMAND_ID は、Google Cloud コンソールでコマンドを構成したときに指定したコマンド ID に置き換えます。

クイック コマンドに応答する

次のコードは、クイック コマンド Help に返信するアドオンではない Chat 用アプリの例を示しています。Chat 用アプリは、APP_COMMAND インタラクション イベントを処理し、インタラクション イベントに一致するコマンド ID が含まれているかどうかを検出して、非公開の Message オブジェクトを返します。

Node.js

node/avatar-app/index.js
/**
 * Handles slash and quick commands.
 *
 * @param {Object} event - The Google Chat event.
 * @param {Object} res - The HTTP response object.
 */
function handleAppCommands(event, res) {
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
    case HELP_COMMAND_ID:
      return res.send({
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      });
  }
}

Apps Script

apps-script/avatar-app/avatar-app.gs
/**
 * Handles the APP_COMMAND event type. This function is triggered when a user
 * interacts with a quick command within the Google Chat app.  It responds
 * based on the command ID.
 *
 * @param {Object} event The event object from Google Chat, containing details
 *     about the app command interaction.  It includes information like the
 *     command ID and the user who triggered it.
 */
function onAppCommand(event) {
  // Executes the quick command logic based on its ID.
  // Command IDs are set in the Google Chat API configuration.
  switch (event.appCommandMetadata.appCommandId) {
    case HELP_COMMAND_ID:
      return {
        privateMessageViewer: event.user,
        text: 'The Avatar app replies to Google Chat messages.'
      };
  }
}

Python

python/avatar-app/main.py
def handle_app_commands(event: Mapping[str, Any]) -> Mapping[str, Any]:
    """Handles slash and quick commands.

    Args:
        Mapping[str, Any] event: The Google Chat event.

    Returns:
        Mapping[str, Any]: the response
    """
    app_command_id = event["appCommandMetadata"]["appCommandId"]

    if app_command_id == ABOUT_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    elif app_command_id == HELP_COMMAND_ID:
        return {
            "privateMessageViewer": event["user"],
            "text": "The Avatar app replies to Google Chat messages.",
        }
    return {}

Java

java/avatar-app/src/main/java/AvatarApp.java
/**
 * Handles slash and quick commands.
 *
 * @param event    The Google Chat event.
 * @param response The HTTP response object.
 */
private void handleAppCommands(JsonObject event, HttpResponse response) throws Exception {
  int appCommandId = event.getAsJsonObject("appCommandMetadata").get("appCommandId").getAsInt();

  switch (appCommandId) {
    case ABOUT_COMMAND_ID:
      Message aboutMessage = new Message();
      aboutMessage.setText("The Avatar app replies to Google Chat messages.");
      aboutMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(aboutMessage));
      return;
    case HELP_COMMAND_ID:
      Message helpMessage = new Message();
      helpMessage.setText("The Avatar app replies to Google Chat messages.");
      helpMessage.setPrivateMessageViewer(new User()
          .setName(event.getAsJsonObject("user").get("name").getAsString()));
      response.getWriter().write(gson.toJson(helpMessage));
      return;
  }
}

HELP_COMMAND_ID は、Google Cloud コンソールでコマンドを構成したときに指定したコマンド ID に置き換えます。

メッセージ アクションに応答する

次のコードは、メッセージ アクション「うっかりアラート」に返信する、アドオンではない Chat 用アプリの例を示しています。Chat 用アプリは、APP_COMMAND インタラクション イベントを処理し、インタラクション イベントに一致するコマンド ID が含まれているかどうかを検出して、非公開の Message オブジェクトを返します。

Node.js

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @param {Object} res The HTTP response object.
 * @return {Object} The JSON response message with a confirmation.
 */
function handleAppCommand(event, res) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  // Use appCommandType to detect message actions.
  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return res.send({
      text: `Setting a reminder for this message: "${messageText}"`
    });
  }
}

Apps Script

/**
 * Responds to an APP_COMMAND interaction event in Google Chat.
 *
 * @param {Object} event The interaction event from Google Chat.
 * @return {Object} The JSON response message with a confirmation.
 */
function onAppCommand(event) {
  // Collect the command ID and type from the event metadata.
  const {appCommandId, appCommandType} = event.appCommandMetadata;

  if (appCommandType === 'MESSAGE_ACTION' &&
      appCommandId === REMIND_ME_COMMAND_ID) {

    // Message actions can access the context of the message they were
    // invoked on, such as the text or sender of that message.
    const messageText = event.message.text;

    // Return a response that includes details from the original message.
    return { "text": "Setting a reminder for message: " + messageText };
  }
}

Python

def handle_app_command(event):
    """Responds to an APP_COMMAND interaction event from Google Chat.

    Args:
        event (dict): The interaction event from Google Chat.

    Returns:
        dict: The JSON response message with a confirmation.
    """
    # Collect the command ID and type from the event metadata.
    metadata = event.get('appCommandMetadata', {})
    if metadata.get('appCommandType') == 'MESSAGE_ACTION' and \
       metadata.get('appCommandId') == REMIND_ME_COMMAND_ID:

        # Message actions can access the context of the message they were
        # invoked on, such as the text or sender of that message.
        message_text = event.get('message', {}).get('text')

        # Return a response that includes details from the original message.
        return {
            "text": f'Setting a reminder for message: "{message_text}"'
        }

Java

/**
 * Responds to an APP_COMMAND interaction event from Google Chat.
 *
 * @param event The interaction event from Google Chat.
 * @param response The HTTP response object.
 */
void handleAppCommand(JsonObject event, HttpResponse response) throws Exception {
  // Collect the command ID and type from the event metadata.
  JsonObject metadata = event.getAsJsonObject("appCommandMetadata");
  String appCommandType = metadata.get("appCommandType").getAsString();

  if (appCommandType.equals("MESSAGE_ACTION")) {
    int commandId = metadata.get("appCommandId").getAsInt();
    if (commandId == REMIND_ME_COMMAND_ID) {
      // Message actions can access the context of the message they were
      // invoked on, such as the text or sender of that message.
      String messageText = event.getAsJsonObject("message").get("text").getAsString();

      // Return a response that includes details from the original message.
      JsonObject responseMessage = new JsonObject();
      responseMessage.addProperty("text", "Setting a reminder for message: " + messageText);
      response.getWriter().write(responseMessage.toString());
    }
  }
}

REMIND_ME_COMMAND_ID は、Google Cloud コンソールでコマンドを構成したときに指定したコマンド ID に置き換えます。