Go on vacation with a Google Chat app

1. Introduction

Google Chat apps bring services and resources right into Chat where users get information and can take action without leaving the conversation.

In this codelab, you learn how to create a Chat app—"Attendance Chat app"—that sets vacation responders in Gmail and schedules meetings in Google Calendar. By building Attendance Chat app in Google Apps Script, you can easily access other Google services like Drive, Gmail, Calendar, Docs, Sheets, and much more.

What you'll learn

  • How to add handlers in events raised in Chat
  • How to parse event objects sent from Chat
  • How to respond back to Chat with card-formatted responses
  • How to define and react to custom actions for button clicks in cards

What you'll need

  • Access to the internet and a web browser.
  • A Google Workspace account with access to Google Chat.
  • Basic JavaScript skills—Google Apps Script only supports JavaScript.

2. Get the sample code

You can either download a ZIP file or clone the GitHub repository to see the code for each step in this sample.

The step-NN folders under solutions/attendance-chat-app contain the desired end state of each step of this codelab. They are there for reference.

Download the code

To download the code for this codelab, click the following button:

Unpack the downloaded ZIP file. This unpacks a root folder (apps-script-samples), which contains one folder for each step of this codelab under solutions/attendance-chat-app.

Clone the GitHub repository

To clone the GitHub repository for this codelab, run the following command:

git clone https://github.com/googleworkspace/apps-script-samples

3. Create the handlers for Google Chat events

Create an Apps Script project

To create an Apps Script project, take the following steps:

  1. Go to script.new.
  2. Click Untitled project.
  3. Rename the script Attendance Chat app and click Rename.

Events in Google Chat

Most Apps Script interactions with Chat are event-driven. The interaction between the user, the Chat app, and Chat typically follows this sequence:

  1. A user initiates an action, like adding a Chat app to a space, starting a direct message (DM) with a Chat app, or removing a Chat app from a space.
  2. The action raises an event aimed at the Chat app in Chat.
  3. Chat calls the corresponding event handler defined in the Chat app's script.

Chat raises 4 events that your app can listen for:

  • ADDED_TO_SPACE: This event occurs when a human user adds a Chat app to a space or a direct message (DM). In Apps Script, you define an onAddToSpace() function to handle this event.
  • REMOVED_FROM_SPACE: This event occurs when a user removes the Chat app from a space or DM. This event doesn't post a response back to Chat. In Apps Script, you define an onRemoveFromSpace() function to handle this event.
  • MESSAGE: This event occurs when a user messages the Chat app, either directly in a DM or as an @mention in a space. In Apps Script, you define an onMessage() function to respond to this event.
  • CARD_CLICKED: This event occurs when the user clicks a button with a custom action assigned to it. In Apps Script, you define an onCardClick() function to respond to this event.

Replace the contents of the Code.gs file with the following code that defines handlers for the ADDED_TO_SPACE and REMOVE_FROM_SPACE events. (You'll add handlers for the MESSAGE and CARD_CLICKED events later in this codelab.)

Code.gs

/**
 * Responds to an ADDED_TO_SPACE event in Google Chat.
 * @param {object} event the event object from Google Chat
 * @return {object} JSON-formatted response
 * @see https://developers.google.com/workspace/chat/receive-respond-interactions
 */
function onAddToSpace(event) {
  console.info(event);
  var message = 'Thank you for adding me to ';
  if (event.space.type === 'DM') {
    message += 'a DM, ' + event.user.displayName + '!';
  } else {
    message += event.space.displayName;
  }
  return { text: message };
}

/**
 * Responds to a REMOVED_FROM_SPACE event in Google Chat.
 * @param {object} event the event object from Google Chat
 * @see https://developers.google.com/workspace/chat/receive-respond-interactions
 */
function onRemoveFromSpace(event) {
  console.info(event);
  console.log('Chat app removed from ', event.space.name);
}

4. Publish & test the Chat app

Update your script manifest file

Before you can publish your app to Chat, you must update the script manifest.

  1. Click Project Settings outline_settings_black_24dp.png.
  2. Select the Show "appsscript.json" manifest file in editor checkbox.
  3. Click Editor outline_code_black_24dp.png.
  4. Click the appsscript.json file.
  5. Add the line "chat": {} to your manifest file.

Your manifest file should look similar to the following example.

appsscript.json

{
  "timeZone": "America/Los_Angeles",
  "dependencies": {
  },
  "chat": {}
}

Create a Google Cloud project

Before you can run and test the Chat app, you must create a Google Cloud project, enable and configure the Chat API, and publish your Chat app to your Google Workspace organization.

  1. In the Google Cloud Console go to Menu f5fbd278915eb7aa.png > IAM & Admin > Create a Project.

  2. For Project Name enter a descriptive name.
  3. If prompted, select the Organization and Billing Account.
  4. Click Create.
  5. When the project creation is complete a notification appears in the upper-right of the page. Click the Create Project: <Project name> entry to open the project.
  6. Click Menu f5fbd278915eb7aa.png > APIs & Services > Credentials.
  7. Click OAuth consent screen.
  8. For App name, enter Attendance Chat app.
  9. If prompted, enter the user support email and developer contact information.
  10. Click Save and Continue.
  11. Click Settings and utilities 50fa7e30ed2d1b1c.png > Project settings.
  12. Copy the Project number.
  13. Back in the App Script editor, click Project Settings outline_settings_black_24dp.png.
  14. Under Google Cloud Platform (GCP) Project, click Change project.
  15. Click GCP project number and enter the project number.
  16. Click Set project.

Publish the app to Chat

To publish your Chat app to Google Chat, do the following:

  1. In the Apps Script editor, click Deploy > New deployment.
  2. Next to Select type click Enable deployment types outline_settings_black_24dp.png.
  3. Select Add-on and click Deploy.
  4. Copy the Deployment ID and click Done.
  5. In Google Cloud console go to Menu f5fbd278915eb7aa.png > APIs & services > Library.

  6. Search for Google Chat API. Select the API from the list of results.
  7. On the Google Chat API page, click Enable.
  8. After you enable the API, click Configuration. Ignore any messages asking you to create credentials.
  9. On the Configuration page, do the following:
  • For App name, enter Attendance Chat app.
  • For Avatar URL, enter https://goo.gl/kv2ENA.
  • For Description, enter Apps Script codelab Chat app.
  • Under Functionality, select Receive one-to-one messages.
  • Under Connection settings, select Apps Script project and paste your script's Deployment ID into the text box.
  • Under Permissions, select Specific people and groups in your domain. In the text box under the drop-down menu, enter your email address associated with your Google Workspace organization.
  • Click Save.

After you save your changes, verify that the status on the Google Chat API page shows the App Status as LIVE – available to users.

Test the Chat app

To test your app in Google Chat, do the following:

  1. Open Google Chat.
  2. Send a new direct message to the Chat app by clicking Start a chat round_add_black_24dp.png > Find apps.
  3. On the Find apps page, search for Attendance Chat app.
  4. Next to Attendance Chat app, click Add > Chat.

When the direct message thread opens, you should see a message from the Chat app thanking you for adding it to a DM, as shown in the following image.

22ea6d660d72eeca.png

5. Define a card-formatted response

In the previous step, your app responded to Google Chat events with a simple text response. In this step, you update your app to respond with cards.

Card responses

Google Chat supports the use of cards for responses. Cards are visual containers that let you group sets of user interface widgets together. Cards can display headers, text paragraphs, sets of buttons, images, and key/value text. Your app can define one or many cards in its JSON response to Google Chat, which then translates your response into the corresponding UI elements.

The following image shows a card response with three sections, that includes a header, a key/value widget, an image widget, and a text button.

b5a194ed8d745ba9.png

To respond to user messages with a card response, add the following code to your Chat app's Code.gs file.

Code.gs

const DEFAULT_IMAGE_URL = 'https://goo.gl/bMqzYS';
const HEADER = {
  header: {
    title : 'Attendance Chat app',
    subtitle : 'Log your vacation time',
    imageUrl : DEFAULT_IMAGE_URL
  }
};

/**
 * Creates a card-formatted response.
 * @param {object} widgets the UI components to send
 * @return {object} JSON-formatted response
 */
function createCardResponse(widgets) {
  return {
    cards: [HEADER, {
      sections: [{
        widgets: widgets
      }]
    }]
  };
}

/**
 * Responds to a MESSAGE event triggered
 * in Google Chat.
 *
 * @param event the event object from Google Chat
 * @return JSON-formatted response
 */
function onMessage(event) {
  const userMessage = event.message.text;

  const widgets = [{
    "textParagraph": {
      "text": "You said: " + userMessage
    }
  }];

  return createCardResponse(widgets);
}

The onMessage() function, added in this step, reads the user's original message and constructs a response as a simple TextParagragh widget. The onMessage() function then calls createCardResponse(), which places the TextParagraph widget within a section of a single card. The Chat app returns the JavaScript object constructed with the card response back to Google Chat.

Test the Chat app

To test this app, go back to your direct message with the app in Google Chat and type a message (any message will do).

e12417d9aa7e177c.png

Note that the onMessage() event handler parses the event object passed to it by Google Chat to extract the user's original message. You can also get other types of information about the event, including the name of the user that initiated the event, their email address, the name of the space that the event occurred in, and much more.

For more information about the structure of the event objects sent by Google Chat, see the Event formats reference.

6. React to button clicks in cards

In the previous step, your Chat app responded to a message from a user—a MESSAGE event—with a simple card that contained a TextParagragh widget. In this step, you create a response that includes buttons, where each button has a custom action defined for it.

Interactive cards

Card responses can contain one of two types of buttons: text button widgets, which display text-only buttons; and ImageButton widgets, which display a button with a simple icon or image without text. Both TextButton and ImageButton widgets support one of two onClick behaviors (as defined in the JSON response sent back to Google Chat): either openLink or action. As the name implies, openLink opens a specified link in a new browser tab.

The action object specifies a custom action for the button to perform. You can specify several arbitrary values in the action object, including a unique actionMethodName and a set of key / value parameter pairs.

Specifying an action object for the button creates an interactive card. When the user clicks the button in the message, Google Chat raises a CARD_CLICKED event and sends a request back to the app that sent the original message. The app then needs to handle the event raised from Google Chat and return a response back to the space.

Replace the onMessage() function in Code.gs with the following code. This code creates 2 buttons, a Set vacation in Gmail and a Block out day in Calendar button in the card sent to Google Chat.

Code.gs

const REASON = {
  SICK: 'Out sick',
  OTHER: 'Out of office'
};
/**
 * Responds to a MESSAGE event triggered in Google Chat.
 * @param {object} event the event object from Google Chat
 * @return {object} JSON-formatted response
 */
function onMessage(event) {
  console.info(event);
  const reason = REASON.OTHER;
  const name = event.user.displayName;
  const userMessage = event.message.text;

  // If the user said that they were 'sick', adjust the image in the
  // header sent in response.
  if (userMessage.indexOf('sick') > -1) {
    // Hospital material icon
    HEADER.header.imageUrl = 'https://goo.gl/mnZ37b';
    reason = REASON.SICK;
  } else if (userMessage.indexOf('vacation') > -1) {
    // Spa material icon
    HEADER.header.imageUrl = 'https://goo.gl/EbgHuc';
  }

  const widgets = [{
    textParagraph: {
      text: 'Hello, ' + name + '.<br/>Are you taking time off today?'
    }
  }, {
    buttons: [{
      textButton: {
        text: 'Set vacation in Gmail',
        onClick: {
          action: {
            actionMethodName: 'turnOnAutoResponder',
            parameters: [{
              key: 'reason',
              value: reason
            }]
          }
        }
      }
    }, {
      textButton: {
        text: 'Block out day in Calendar',
        onClick: {
          action: {
            actionMethodName: 'blockOutCalendar',
            parameters: [{
              key: 'reason',
              value: reason
            }]
          }
        }
      }
    }]
  }];
  return createCardResponse(widgets);
}

To handle the CARD_CLICKED event, must add the onCardClick() function to your Chat app's script. Add the following code that defines the onCardClick() function Code.gs.

Code.gs

/**
 * Responds to a CARD_CLICKED event triggered in Google Chat.
 * @param {object} event the event object from Google Chat
 * @return {object} JSON-formatted response
 * @see https://developers.google.com/workspace/chat/receive-respond-interactions
 */
function onCardClick(event) {
  console.info(event);
  let message = '';
  const reason = event.action.parameters[0].value;
  if (event.action.actionMethodName == 'turnOnAutoResponder') {
    turnOnAutoResponder(reason);
    message = 'Turned on vacation settings.';
  } else if (event.action.actionMethodName == 'blockOutCalendar') {
    blockOutCalendar(reason);
    message = 'Blocked out your calendar for the day.';
  } else {
    message = "I'm sorry; I'm not sure which button you clicked.";
  }
  return { text: message };
}

In responding to user clicks, now the Chat app does one of two things: it sets the user's vacation responder in Gmail to an "out of office" message; or it schedules an all-day meeting on the user's Calendar. To accomplish these tasks, the app calls the Gmail advanced service and the Calendar service.

Add the following code to your script to integrate the Chat app with Gmail and Calendar.

Code.gs

const ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;
/**
 * Turns on the user's vacation response for today in Gmail.
 * @param {string} reason the reason for vacation, either REASON.SICK or REASON.OTHER
 */
function turnOnAutoResponder(reason) {
  let currentTime = (new Date()).getTime();
  Gmail.Users.Settings.updateVacation({
    enableAutoReply: true,
    responseSubject: reason,
    responseBodyHtml: "I'm out of the office today; will be back on the next business day.<br><br><i>Created by Attendance Chat app!</i>",
    restrictToContacts: true,
    restrictToDomain: true,
    startTime: currentTime,
    endTime: currentTime + ONE_DAY_MILLIS
  }, 'me');
}

/**
 * Places an all-day meeting on the user's Calendar.
 * @param {string} reason the reason for vacation, either REASON.SICK or REASON.OTHER
 */
function blockOutCalendar(reason) {
  CalendarApp.createAllDayEvent(reason, new Date(), new Date(Date.now() + ONE_DAY_MILLIS));
}

Finally, you must enable the Gmail advanced service in the project. To enable the Gmail API, do the following:

  1. In the Apps Script editor, next to Services, click Add a service round_add_black_24dp.png.
  2. Select Gmail API.
  3. Click Google Cloud Platform API Dashboard below that opens the Google Cloud Console.
  4. Click Enable APIs and Services.
  5. Search for Gmail API and click the Gmail API.
  6. On the Gmail API page, click Enable.

Test the Chat app

To test this version of your Chat app, open the DM that you started in previous steps in Google Chat and type I'm going on vacation. The app should respond with a card similar to the image below.

Note: If you are asked to provide access to the app, you may have to type your message a second time.

c0e8d9d0b5d0cf8b.png

7. Congratulations!

Your Chat app can now respond to user messages, set their vacation responder in Gmail, and put an all-day event on their Calendar.

What we've covered

  • Created and published a Google Chat app with Apps Script
  • Responded to user messages with a simple response
  • Interacted with other Google Workspace services on the user's behalf through the Chat App

Learn more