arrow_back

Google Chat bot - Apps Script

Join Sign in

Google Chat bot - Apps Script

1 hour 5 Credits

GSP250

Google Cloud self-paced labs logo

Overview

Google Chat bots provide easy-to-use access points to your organization's data and services. Users can interact with bots conversationally within a chat experience.

Among other implementation options, you can create a Google Chat bot using Google Apps Script. By building your bot in Apps Script, you can easily access other Google services like Drive, Gmail, Calendar, Docs, Sheets, and much more.

In this lab, you learn how to create a simple Google Chat bot—"Attendance Bot"—using Google Apps Script. The bot integrates with Gmail to set a user's vacation responder and integrates with Calendar to put a meeting on the user's calendar.

d4429c7b61211b8f.png

What you'll learn

  • How to add handlers in events raised in Google Chat

  • How to parse event objects sent from Google Chat

  • How to respond back to Google Chat with card-formatted responses

  • How to define and react to custom actions for button clicks in cards

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud Console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Console. The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username from the Lab Details panel and paste it into the Sign in dialog. Click Next.

  4. Copy the Password from the Lab Details panel and paste it into the Welcome dialog. Click Next.

    Important: You must use the credentials from the left panel. Do not use your Google Cloud Skills Boost credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  5. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Cloud Console opens in this tab.

Note: You can view the menu with a list of Google Cloud Products and Services by clicking the Navigation menu at the top-left. Navigation menu icon

Create the handlers for Google Chat events

To implement your bot, create a new Google Apps Script project:

  1. Click this Google Apps Script editor link to open Google Apps Script online editor.

  2. Click Untitled project (the current name). In the Edit project name dialog, rename the project to Attendance Bot, and then click Rename.

Events in Google Chat

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

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

Google Chat raises four events that your Apps Script bot can listen for:

  • ADDED_TO_SPACE: This event occurs when a human user adds a bot to a room or a DM. In Apps Script, you define an onAddToSpace() function to handle this event.
  • REMOVED_FROM_SPACE: This event occurs when a user removes the bot from a room or DM. This event does not post a response back to Google Chat. In Apps Script, you define an onRemoveFromSpace() function to handle this event.
  • MESSAGE: This event occurs when a user messages the bot, either directly in a DM or as an @mention in a room. 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.

To define the handlers for the ADDED_TO_SPACE and REMOVE_FROM_SPACE events, replace the contents of the Code.gs file with the following code. (You add handlers for the MESSAGE and CARD_CLICKED events later in this lab.)

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/chat/reference/message-formats/events */ 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; } console.log('Attendance Bot added in ', event.space.name); 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/chat/reference/message-formats/events */ function onRemoveFromSpace(event) { console.info(event); console.log('Bot removed from ', event.space.name); }

Save save_icon.png Code.gs.

Publish the bot

Before you can run and test the bot, you must configure your Google Cloud project by enabling (if necessary) the Google Chat API, and publish your bot to Google Chat. To do this, you:

  • Update the manifest file

  • Enable the and configure the Google Chat bot

Update the script manifest

The Apps Script editor hides manifest files by default to protect Apps Script project settings. To make the manifest files visible:

  1. In the left panel, click Project Settings project_icon.png.
  2. Check Show "appsscript.json" manifest file in editor in the General settings section.

Go back to the Editor editor_icon.png, the appsscript.json file should now be available.

Edit the appsscript.json file:

  1. Add a comma after the line: "exceptionLogging": "STACKDRIVER".
  2. Add a new line "chat": {} to your manifest file.

Your manifest file should look similar to the following example.

appsscript.json

{ "timeZone": "Asia/Kolkata", "dependencies": { }, "exceptionLogging": "STACKDRIVER", "chat": {}, "runtimeVersion": "V8" }

Save save_icon.png appsscript.json.

Configure Google Cloud project and update the script to use it.

  1. Go to the Google Cloud Console, click Navigation Menu Navigation Menu in the upper left and navigate to APIs & Services > OAuth consent screen.
  • Set User Type to Internal and click Create.
  • In the next page, (OAuth consent screen), enter the following;
Field Value
App name Attendance Bot
User support email Select the email ID from the drop-down. This is also your User Email in the left panel of the lab instructions.
Developer contact information
  • Click Save and Continue.
  • On the next page (Scopes), leave all the fields empty, and then click Save and Continue.
  • As shown in the next page (Summary), the OAuth Consent Screen is now created for your app. Click Back to Dasboard at the bottom of the page.
  • Click the three dots icon Menu button in the upper-right to expand the menu and select Project settings.
  • Record the Project number to use in the next step to configure your project.
  1. In the App Script editor, navigate to the Project Settings project_icon.
  • Under Google Cloud Platform (GCP) Project, click Change project.
  • When prompted, enter the value of Project number, copied earlier, in the GCP Project number field. Then click Set project.

Configuring Google CLoud Console Project

Configure and publish the Chat bot

  1. Go to the Apps Script editor, get the deployment ID, by clicking on Deploy > New Deployment on top-right of the screen.
  2. In the Descrption field, enter "App Script lab bot", and click Deploy.
  3. Note down the Deployment ID to use later, and click Done.
  4. Go to the Cloud Console, navigate to Navigation Menu Navigation Menu > APIs & Services > Library.
  5. In the Library, search for ‘Google Chat API'. Select the API from the list of results.
  6. The Google Chat API is already enabled for you. If it is not, click Enable.
  7. Click Manage, and then click Configuration in the left panel.
  8. In the Configuration dialog, set the fields with the following values:
Field Value
App name Attendance Bot
Avatar URL https://goo.gl/kv2ENA
Description Apps Script lab bot
Functionality Bot can be messaged directly
Connection settings check Apps Script project, and then paste your script's Deployment ID into the Deployment ID field
Permissions select Specific people and group in your domain, then in the text box, enter .
  1. Click SAVE.

  2. After the changes are saved, scroll to the top to update the App Status to LIVE – available to users. Click SAVE again.

bot-status-live.png

Test the bot

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

  1. Click this Google Chat link to open Google Chat.
  2. Click Start a chat Start a chat > Find apps in Chat section.
  3. From the list, select the "Attendance Bot, Apps Script lab bot" that you created, and click Chat.

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

Attendance bot output

Click Check my progress to verify the objective.

Publish and test the bot

Define a card-formatted response

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

Card responses

Google Chat supports the use of cards for responses. Cards are visual containers that allow you to group sets of user interface widgets together. Cards can display headers, text paragraphs, sets of buttons, images, and key/value text. Your bot 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.

fdf1aa874f03f551.png

To respond to user messages with a card response, in Apps Script > Editor editor_icon, add the following code to your bot's Code.gs file.

Code.gs

var DEFAULT_IMAGE_URL = 'https://goo.gl/bMqzYS'; var HEADER = { header: { title : 'Attendance Bot', 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) { var userMessage = event.message.text; var widgets = [{ "textParagraph": { "text": "You said: " + userMessage } }]; console.log('You said:', userMessage); return createCardResponse(widgets); }

Save save_icon Code.gs.

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 bot returns the JavaScript object constructed with the card response back to Google Chat.

To save this version of script:

  1. Click Deploy > Manage deployments on top-right corner of the screen.

  2. Click on the edit icon Edit icon of your deployment, and select New version from the Version drop-down.

  3. Click Deploy to save the version. This updates the deployment to use the new version of the script.

  4. Click Done.

Test the bot

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

Attendance bot output

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 room 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.

Click Check my progress to verify the objective.

Test the bot in card-formatted response

React to button clicks in cards

In the previous step, your bot responded to a message from a user—a MESSAGE event—with a simple card that contained a TextParagragh widget. In this step, you will 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: TextButton 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, however, 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 bot that sent the original message. The bot then needs to handle the event raised from Google Chat and return a response back to the space.

  1. Return to the Apps Script > Editor editor_icon.

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

Code.gs

var 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); var reason = REASON.OTHER; var name = event.user.displayName; var 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'; } var widgets = [{ textParagraph: { text: 'Hello, ' + name + '.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); }
  1. To handle the CARD_CLICKED event, add the onCardClick() function to your bot'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/chat/reference/message-formats/events */ function onCardClick(event) { console.info(event); var message = ''; var 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 bot 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 bot calls the Gmail advanced service and the Calendar Apps Script API.

  1. Add the following code to your script to integrate the bot with Gmail and Calendar.

Code.gs

var 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) { var 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.Created by Attendance Bot!", 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)); }
  1. Save save_icon Code.gs.
  2. Click Add a service Add a service icon in Services tab and select Gmail API from the list. Click Add.

To update your project with this version of script:

  1. Click Deploy > Manage deployments in the top-right corner.
  2. Click the edit icon Edit icon of our deployment, and select New version from the Version drop-down menu.
  3. Click Deploy to save the version. This updates the deployment to use the new version of the script.
  4. Click Done.

Finally, you need to check to be sure the Gmail Advanced Service is enabled in this project. To enable the Gmail API, do the following:

  1. In the Google Cloud Console, navigate to Navigation Menu Navigation Menu > APIs & Services > Library.

  2. In the Library, search for ‘Gmail API'. Select the API from the list of results.

  3. The Gmail API is already enabled for you. If it is not, click Enable.

Test the bot

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

Attendance bot outout

  1. To configure the Attendance Bot, click Configure, choose your user account, click ALLOW, and then close the page when you see the message "You may close this page now".

  2. Now the bot displays the available options.

  3. Click SET VACATION IN GMAIL. You should see the message "Turned on vacation settings."

  4. Click BLOCK OUT DAY IN CALENDAR. You should see the message "Blocked out your calendar for the day."

d4429c7b61211b8f.png

  1. Click the Google Apps icon to access then check the Gmail and Calendar associated with this account.

Google Apps

You should see the Vacation Setting in Gmail:

bad9a9eebf8f089e.png

You should also see a day blocked out in the Calendar.

20411858f0f562b0.png

Click Check my progress to verify the objective.

Test the bot by button clicking in cards

Congratulations!

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

Completion Badge

Finish your Quest

This self-paced lab is part of the Workspace Integrations Quest. A Quest is a series of related labs that form a learning path. Completing this Quest earns you the badge above, to recognize your achievement. You can make your badge (or badges) public and link to them in your online resume or social media account. Enroll in this Quest and get immediate completion credit if you've taken this lab. See other available Quests.

Take your next lab

Check out what else you can do with Workspace:

Learn more

Manual Last Updated May 24, 2022
Lab Last Tested May 24, 2022

Copyright 2022 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.