Respond to Google Chat app commands

This page explains how to set up and respond to commands as a Google Chat app.

Commands help users discover and use key features of a Chat app. Only Chat apps can see the content of a command. For example, if a user sends a message with a slash command, the message is only visible to the user and the Chat app.

To decide whether you should build commands, and to understand how to design user interactions, see Define all user journeys.

Types of Chat app commands

You can build Chat app commands as slash commands or quick commands. To discover and use each type of command, users do the following:
  1. Slash commands: Users send commands as messages by typing a slash (/) and then a predefined text, such as /about. Chat apps can also require argument text for the slash command. For example, the slash command /search can require argument text that's used for a search query.
  2. Quick commands: Users use commands by opening the menu from the reply area of a Chat message. To use a command, they click Add and select a command from the menu.
The following images show how users discover a menu of slash commands and quick commands:
  • A user discovers slash commands.
    Figure 1. Users discover and use slash commands by typing a slash / in the reply area followed by the name of the command.
  • A user views quick commands from the menu.
    Figure 2. Users discover and use quick commands from the menu in the reply area of a Chat message.

Prerequisites

Set up the command

This section explains how to complete the following steps to set up a command:

  1. Create a name and description for the command.
  2. Configure the command in the Google Cloud console.

Name and describe the command

The name of a command is what users type or select to invoke the Chat app. A short description also appears below the name, to prompt users further about how to use the command:

Slash command name and description
Figure 3: The name and description for a slash command.

When choosing a name and description for your command, consider the following recommendations:

To name a command:

  • Use short, descriptive, and actionable words or phrases to make the commands clear to the user. For example, instead of the name Create a reminder, use Remind me.
  • Consider using a unique or common name for your command. If your command describes a typical interaction or feature, you can use a common name that users recognize and expect, such as Settings or Feedback. Otherwise, try to use unique command names, because if your command name is the same for other Chat apps, the user must filter through similar commands to find and use yours.

To describe a command:

  • Keep the description short and clear so that users know what to expect when they use the command.
  • Let users know if there are any formatting requirements for the command. For example, if you create a slash command that requires argument text, set the description to something like Remind me to do [something] at [time].
  • Let users know if the Chat app replies to everyone in the space, or privately to the user who invokes the command. For example, for the quick command About, you could describe it as Learn about this app (Only visible to you).

Configure the command in the Google Cloud console

To create a slash or quick command, you specify information about the command in your Chat app's configuration for the Google Chat API.

To configure a command in the Google Chat API, complete the following steps: o configure a slash command in the Google Chat API, complete the following steps:

  1. In the Google Cloud console, click Menu > APIs & Services > Enabled APIs & Services > Google Chat API

    Go to the Google Chat API page

  2. Click Configuration.

  3. Under Advanced settings, go to Triggers and check that the App command field contains a trigger, such as an HTTP endpoint or Apps Script function. You must use this trigger in the following section to respond to the command.

  4. Under Commands, click Add a command.

  5. Enter the following information about the command:

    1. Command ID: a number from 1 to 1000 that your Chat app uses to recognize the command and return a response.
    2. Command type: select either Quick command or Slash command.
    3. If you're configuring a slash command, enter a value for the Slash command name field to specify what users type to invoke the command. Must start with a slash, contain only text, and can be up to 50 characters. For example, /remindMe.
    4. Name: the user-friendly name for the command. Names can be up to 50 characters and can include special characters.
    5. Description: the text that describes how to use and format the command. Descriptions can be up to 50 characters.
  6. Optional: If you want your Chat app to respond to the command with a dialog, select the Open a dialog checkbox.

  7. Click Save.

The command is now configured for the Chat app.

Respond to a command

When users use a command, your Chat app receives an event object. The event payload contains an appCommandPayload object with details about the command that was invoked (including the command ID and the command type), so that you can return an appropriate response. The event object is sent to the HTTP endpoint or Apps Script function that you specified when you configured the App command trigger.

Private message for the
  Cymbal Labs Chat app. The message says that the
  Chat app was created by Cymbal Labs and shares a link
  to documentation and a link to contact the support team.
A Chat app responds privately to the slash command /help to explain how to get support.

The following code shows an example of a Chat app that replies to the slash command /about with a text message. To respond to slash commands, the Chat app handles event objects from an App command trigger. When the payload of an event object contains a slash command ID, Chat app returns the action DataActions with a createMessageAction object:

// The ID of the slash command "/about".
// It's not enabled by default, set to the actual ID to enable it. You must
// use the same ID as set in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 0;

/**
 * Google Cloud Function that responds to events sent from a
 * Google Chat space.
 *
 * @param {Object} req Request sent from Google Chat space
 * @param {Object} res Response to send back
 */
exports.avatarApp = function avatarApp(req, res) {
    if (req.method === 'GET' || !req.body.chat) {
        return res.send('Hello! This function is meant to be used ' +
            'in a Google Chat Space.');
    }
    // Stores the Google Chat event as a variable.
    const chatEvent = req.body.chat;

    // Handles events that contain payloads about commands
    if (chatEvent.appCommandPayload) {

      // Stores the Google Chat app command metadata as a variable.
      const appCommandMetadata = chatEvent.appCommandPayload.appCommandMetadata;

      // Executes the slash command logic based on its ID.
      // Slash command IDs are set in the Google Chat API configuration.
      switch (appCommandMetadata.appCommandId) {
          case ABOUT_COMMAND_ID:
              return res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
                  text: 'The Avatar app replies to Google Chat messages.'
              }}}}});
      }
    // Handles MESSAGE events
    } else if (chatEvent.messagePayload) {

        // Stores the Google Chat event as a variable.
        const chatMessage = chatEvent.messagePayload.message;

        // Replies with the sender's avatar in a card otherwise.
        const displayName = chatMessage.sender.displayName;
        const avatarUrl = chatMessage.sender.avatarUrl;
        res.send({ hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
            text: 'Here\'s your avatar',
            cardsV2: [{
                cardId: 'avatarCard',
                card: {
                    name: 'Avatar Card',
                    header: {
                        title: `Hello ${displayName}!`,
                    },
                    sections: [{
                        widgets: [{
                            textParagraph: { text: 'Your avatar picture: ' }
                        }, {
                            image: { imageUrl: avatarUrl }
                        }]
                    }]
                }
            }]
        }}}}});
    }
};
// The ID of the slash command "/about".
// It's not enabled by default, set to the actual ID to enable it. You must
// use the same ID as set in the Google Chat API configuration.
const ABOUT_COMMAND_ID = 0;

/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {

    // Stores the Google Chat event as a variable.
    const chatMessage = event.chat.messagePayload.message;

    // Replies with the sender's avatar in a card otherwise.
    const displayName = chatMessage.sender.displayName;
    const avatarUrl = chatMessage.sender.avatarUrl;
    return { hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
        text: 'Here\'s your avatar',
        cardsV2: [{
            cardId: 'avatarCard',
            card: {
                name: 'Avatar Card',
                header: {
                    title: `Hello ${displayName}!`,
                },
                sections: [{
                    widgets: [{
                        textParagraph: { text: 'Your avatar picture: ' }
                    }, {
                        image: { imageUrl: avatarUrl }
                    }]
                }]
            }
        }]
    }}}}};
}

/**
 * Responds to an APP_COMMAND event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onAppCommand(event) {

  // Stores the Google Chat app command metadata as a variable.
  const appCommandMetadata = event.chat.appCommandPayload.appCommandMetadata;

  // Executes the slash command logic based on its ID.
  // Slash command IDs are set in the Google Chat API configuration.
  switch (appCommandMetadata.appCommandId) {
      case ABOUT_COMMAND_ID:
          return { hostAppDataAction: { chatDataAction: { createMessageAction: { message: {
              text: 'The Avatar app replies to Google Chat messages.'
          }}}}};
  }
}

To use this code sample, replace ABOUT_COMMAND_ID with the command ID that you specified when you configured the command in the Chat API.

Test the command

To test the command and code, see Test interactive features for Google Chat apps.

To learn how to test and use the command in the Chat UI, see Use apps in Google Chat in the Google Chat Help documentation.