In this article, we will look at Google Chat Apps and go over some of the basics of developing a chat app with Google Apps Script.
Note that Chat Apps are currently only available to Google Workspace paid accounts and not standard ‘@gmail’ consumer accounts.
Table of Contents
What are Google Chat Apps?
Google Chat is a business-level messaging tool for Google Workspace that allows you to chat one-on-one and in groups called Spaces within your business and even with clients and contractors outside of your domain.
Its integrations with Google Workspace tools like Google sheets, docs and slides right inside chat along with a Google Task tab and a convenient file library tab make it a really handy business tool.
But one thing that is often overlooked is that you can add Chat Apps or Chat Bots to your Google Chat Spaces or DM a chat app directly to accomplish tasks conveniently.
There are hundreds of 3rd party Chat App integrations for you to choose from. Anything from project management to customer support and more.
Chat apps can:
- Respond to messages
- Respond to specific slash commands
- Carry out automations and execute scripts
Once called, they can generate:
- Messages
- Cards
- Preview links
Chat apps can also create private dialogues for users to complete forms.
Chat Apps can feel more seamless than using standalone applications and may be a better option for you and your teams and can even enhance your team’s workflow in chat.
Chat Apps for Apps Script Devs – Video
Setting up a Google Chat App for Apps Script
The Video Walkthrough
The chatbot avatar image accompanying the video:
https://lh3.googleusercontent.com/drive-viewer/AJc5JmQlYT9qF6VfSw-6G-78lKcPU9xytqz53vgQRWmkM1vyAQVl_jbxIChLRR4BnHaEUaj0YfnBEKg=w1920-h942
Copy this image and paste it into the Avatar URL section of Chat API configuration.
Apps Script Project
Setting up a Google Apps Script project for Google Chat is a little different to what you might be used to with web apps, bound and standalone projects.
Your project will require the addition of an extra property in your manifest file and a minimum of 3 pre-defined trigger functions.
There are two ways to set up your App Script project:
- Do it all yourself.
- Use Googles Chat App for Google Apps Script template.
Do it yourself
Update the appsscript.json manifest file
To access your manifest file click on the Project Settings Cog in the sidebar. Then select show "appsscript.json"
manifest file in the editor.
Head back to the editor and select the appsscript.json
file. Create new empty chat property. This will help the Chat App API recognise the project as a chat app project.
1 2 3 4 5 6 7 8 |
{ "timeZone": "Australia/Sydney", "exceptionLogging": "STACKDRIVER", "runtimeVersion": "V8", "chat": { "addToSpaceFallbackMessage": "Thank you for adding me!" } } |
Note that the “addToSpaceFallBackMessage” is optional and is used in the occurrence that the app is added before authorisation.
Add 3 Chat App Trigger Functions
Back in your Code.gs file, delete myFunction
. We will be replacing it with 3 mandatory trigger functions required to run the chat app:
onAddToSpace(event)
: Responds when your app is selected and added to a group space.onRemoveFromSpace(event)
: Responds when your app is manually removed from a group space.onMessage(event)
: Responds to a message in a direct message or group space, providing the message details as part of theevent
parameter.
Copy and paste the following into your Code.gs file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
/** * Responds to a MESSAGE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onMessage(event) { var name = ""; if (event.space.type == "DM") { name = "You"; } else { name = event.user.displayName; } var message = name + " said \"" + event.message.text + "\""; return { "text": message }; } /** * Responds to an ADDED_TO_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onAddToSpace(event) { var message = ""; if (event.space.singleUserBotDm) { message = "Thank you for adding me to a DM, " + event.user.displayName + "!"; } else { message = "Thank you for adding me to " + (event.space.displayName ? event.space.displayName : "this chat"); } if (event.message) { // Bot added through @mention. message = message + " and you said: \"" + event.message.text + "\""; } return { "text": message }; } /** * Responds to a REMOVED_FROM_SPACE event in Google Chat. * * @param {Object} event the event object from Google Chat */ function onRemoveFromSpace(event) { console.info("Bot removed from ", (event.space.name ? event.space.name : "this chat")); } |
While the functions are necessary, their contents can be modified to the needs of your project.
I recommend that you keep the script as it is for now while we run through the setup. Then you can start crafting your own app.
USE the CHAT template
The Apps Script team has provided a handy template sheet to get us started. To access it we head to your script.google.com homepage > click on the Getting Started sidebar item and then scroll down to the Chat Apps card and click to create your own prefilled project.
Or directly from this link: Chat App.gs Template
Connect a Google Cloud Project
You will need to connect to a Standard Google Cloud project to run your chat apps script.
In your Apps Script IDE select the ‘Project Settings‘ cog and scroll down to ‘Google Cloud Platform (GCP) Project’. Select Change project. Then under step 1 select the link to your cloud console.
Or… you know just click the link below.
Create a Google Cloud Project
In the GCP dashboard. Select the current project (Top left). A dialogue box will appear.
Select NEW PROJECT.
You’ll see another dialogue box appear.
Fill out the details and select create.
It will take a moment to build your new project.
You will be navigated to your new project’s dashboard.
Note! you will get an error if you try and add in your project ID at this stage. We’ve go one more step to do.
Set up OAuth for your project in the GCP
Our next task is to quickly set up our OAuth Consent screen.
In the side-bar menu select APIs and services > OAuth consent screen
Select the project to be Internal to work inside your own organisation. If you are planing on publishing your chat app for use in other organisations then you would select the External option.
Select Create.
In the OAuth builder, we only need to select 3 things to get things up and running at the bare minimum. We can always update this later.
Under App information add your app name (1) and user support email (2).
Then scroll down to the bottom and add your email address to the Developer contact information (3).
Finally select Save and continue. (4)
We can skip the Scopes sections for the time being. Scroll to the bottom of this section and select Save and continue again.
On the summary screen scroll to the bottom and select Back to dashboard.
Add the project number to the Apps Script project
In your GCP account, navigate back to your project dashboard. In the sidebar menu, select Cloud overview > Dashboard.
Select the Project Number from the Project Info box and paste it into your Apps Script project and select Set project.
Deploy Your Project
Save your Apps Script project and select Deploy > New deployment.
This will generate a deployment ID. We will use this in a moment.
Add and Configure the Chat App API
The last task we need to do in order to get things running is to add the ChatApp API to your project. Head back to your GCP project.
In the sidebar select APIs and Services > Library.
Search for ‘Google Chat API’.
You will be navigated to the Google Chat API homepage. Select Enable.
This will open the Google Chat API interface.
Select Configuration.
Then change the App status to LIVE.
Add your application details including:
- App name: This will be the displayed name for your app.
- Avatar URL: This is the avatar for your chatbot.
- Description: A brief description of what the chat app does.
Under Functionality check the first and 3rd buttons. If you want to add your app to spaces and groups click the middle one.
Next, under Connection settings, select Apps Scrip project.
Now head back to your Apps Script project and select Deploy > Manage Deployments. Then copy the deployment ID and paste it into the Chat App API field Deployment ID.
For now, ignore the Slash Commands and Link preview sections.
We don’t want to share our project with our entire organisation while we are testing. Under Permissions, select Specific people and groups in your domain and add your email to the list.
Then click Save.
Run your chat app for the first time
Head over to Google Chat. Select the Start a chat (+) button. Then select Find apps.
Use the search bar to search for the name of your app. Select Chat to add your app to a direct message.
With our current project, you will just need to type something in for it to respond.
On the first run, it will as you to configure or run through the authorisation process. After that, you are good to go.
Now when we create a new version of our deployment the chat app will be updated with any changes to our code.
It sounds like a bit of a chore, I know, but it really doesn’t take that long to get it all squared away and running.
Need help with Google Workspace development?
Go something to solve bigger than Chat GPT?
I can help you with all of your Google Workspace development needs, from custom app development to integrations and security. I have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.
Schedule a free consultation today to discuss your needs and get started or learn more about our services here.
Testing and Deployment (Update 04 Nov 2023)
Earlier in 2023 the Google Apps Script team created the ability to use head deployments with add-ons and chat apps for testing.
A head deployment is the current project’s code. This means that instead of needing to carry out the arduous process of redeploying each time that you make a change while testing you can replace the deployment ID with the testing head deployment. Now, each time that you make a change to your code and save, it will be reflected immediately in your chat app.
Just remember, when it is time to publish your chat app, you will need to swap out the test deployment iID with the managed deployment ID in your Google Chat Api Configuration in your Google Cloud Console.
So, how do we do this?
In your Apps Script project:
- Select the Deploy button.
- Test deployment.
- Click copy below the Head Deployment ID.
In your Google Cloud Console:
- Go to Apis and services > Enabled Apis and services.
- Scroll down to the list and select Google Chat Api.
- In the API, select CONFIGURATION from the top menu.
- Scroll down to Connection Settings.
- Replace the Deployment ID with your test deployment ID.
- Select Save.
Now go ahead and make a change in your script and then check it live in your Chat with your connected chat app.
Receiving data onMessage(event)
When you add a chat app to a direct message or Google Space, it basically listens for responses to conversations and returns a JSON Object of data about the most recent message usually stored as an ‘event’ parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
{ type: 'MESSAGE', eventTime: { seconds: 1663397630, nanos: 262143000 }, user: { domainId: '4h70h86', displayName: 'Yagisanatode', type: 'HUMAN', avatarUrl: 'https://lh3.googleusercontent.com/a-/AFdZucpRqqCuZSdyZpjEy3aBUgKqY6Ivu0m9wpTj1XtwtBv4GLcl6...oCBYZdL0=k', email: 'sample@yagisanatode.com', name: 'users/109972792157794923410' }, configCompleteRedirectUrl: 'https://chat.google.com/api/bot_config_complete?token=ADpEVQWiIMAAvKSMfS7cjDeUud-lKHu6R81Q...jeCBZ95O9r22zY0euKmt8DVa8MMfCUPQukUsZZW8onj5RA%3D%3D', message: { argumentText: ' 1050.99AUD:USD', space: { type: 'ROOM', displayName: 'Moneyzzz', spaceHistoryState: 'HISTORY_ON', spaceType: 'SPACE', externalUserAllowed: true, spaceThreadingState: 'UNTHREADED_MESSAGES', name: 'spaces/AAAA9Ix3EBc' }, sender: { avatarUrl: 'https://lh3.googleusercontent.com/a-/AFdZucpRqqCuZSdyZpjEy3aBUgKqY6Ivu0m9wpTj1XtwtBv4GLcl6-518vsAnfYx-sJ9HnoMT8XFvNnlVAVcjk1mV7wFy90yInBAd86Qsv77V6CCT3MX8_Nw7JEXce_4ZZjgB8sNVAW7oj6nKjZecvS7RAL8qeoL8...jrsliKt2r3MPPXQCdoCBYZdL0=k', type: 'HUMAN', name: 'users/109972792147794923210', displayName: 'Yagisanatode', email: 'sample@yagisanatode.com', domainId: '4h70l16' }, attachment: [ { externalContentType: "application/vnd.google-apps.presentation", messageMetadata: { sender: "109972792147794923210", name: "spaces/xhK40EAAAAE/messages/ExNdztk3xT8.ExNdztk3xT8", createTime: { nanos: 943839000, seconds: 1663991483 }, updateTime: { seconds: 1663991484, nanos: 53711000 } }, contentName: "An Intro Creating Chat Apps with Google Apps Script", contentType: "application/vnd.google-apps.punch", driveDataRef: { driveFileId: "1-kF-W4DcNxFeMgJ3ZHERPjMXyrDr9F5fiYt8OU7ngw4" }, source: "DRIVE_FILE", name: "spaces/xhK40EAAAAE/messages/ExNdztk3xT8.ExNdztk3xT8/attachments/AATUf-JizLeVjOxNU6_eTw25iZHq" } ], annotations: [[Object]], slashCommand: { commandId: 1 }, createTime: { nanos: 262143000, seconds: 1663397630 }, name: 'spaces/AAAA9Ix3EBc/messages/QGscqAms0DQ.QGscqAms0DQ', text: '/xe 1050.99AUD:USD', thread: { retentionSettings: [Object], name: 'spaces/AAAA9Ix3EBc/threads/QGscqAms0DQ' }, retentionSettings: { state: 'PERMANENT' } }, space: { spaceType: 'SPACE', externalUserAllowed: true, spaceThreadingState: 'UNTHREADED_MESSAGES', spaceHistoryState: 'HISTORY_ON', type: 'ROOM', name: 'spaces/AAAA9Ix3EBc', displayName: 'Moneyzzz' } } |
You can then use the data received from this object to read the message text or check, among other things, metadata like:
- The display name of the user sending the message.
- Their email
- Avatar URL
- The time the message event occurred
- Any annotations like images
- Or links added to the message
We can use the information in the returned JSON event to run a programmatic action when:
- A /slash command is issued.
- When a link matching a predefined pattern is added to a message with Preview Links
- When attachments are added to the message
- Or based on a set of predefined texts
Responding back to the chat
Once we have our event data, we utilise the full capabilities of Apps Script to run Google Classes and APIs, fetch and update external API data, store data and manipulate it.
- We can then return the data directly as a message through chat.
- As a stylised card message.
- Or As a popup dialogue box – that is private to the initiator of the dialogue action and can be used to fill out basic form data.
Returning a message
This is by far the easiest way to respond to a message. Here we can return an object with the text property back to the chat:
1 |
"text": "*some bold text*, some normal text" |
We can apply the same markdown styling here as a regular user can in Google chat.
1 2 3 4 5 6 7 8 |
function onMessage(event){ const name = event.user.displayName; const userMessage = event.message.text; if(userMessage){ return {"text": `*{name} said:* ${userMessage}`} } } |
Cards and Dialogues
Cards and dialogues can contain much more styling than regular messages. Returning cards to the chat can be an attractive alternative to messages to get information across to a team in a space.
Dialogue popups are predominantly used to complete tasks privately while still in a chat. Perhaps you need to fill out a private form for example. Not all users need to see you fill out all parts of a form or some of those elements of your form may need to be entered privately away from the rest of the team in the Chat Space. Chat Dialogues are ideal for this task.
Styling Cards and Dialogues
Cards and dialogues are built and styled by generating a JSON file. If you have ever worked in Card Services you may find the process similar here.
Cards and dialogues can display widgets like:
- Images
- Links
- Simple formatted text
- Decorated Text
- Headers
- Buttons
- Text inputs
- Separated Sections
- And Dividers
I’ll be covering more details about applying widgets in the Currency Converter Chat App Series.
Current limitations
Not all widgets are currently available at the time of writing this. For example, the grid layout is not available for cards and the date and time pickers are not available in the dialogue boxes yet. Further, for dialogues to return a text message or card, we currently need to use a Service Account in Apps Script and run it the same way you would a Node.js project, which is currently a little cumbersome.
However, it does seem that updates are on the way.
A Card and Dialogue Builder Tool
Building dialogues and buttons from scratch can be a little tricky. Fortunately, the apps script team have provided an interactive card builder for you.
Again at the time of writing this, the builder is using the depreciated version 1 of the card builder but the JSON syntax is similar and what you can’t build in the builder you might be able to build in the main card builder tool for card services and copy the JSON data across to your own project to build out your cards and dialogues.
Button Actions
Button clicks are probably going to be your primary action execution with cards and dialogues. When a button is clicked it can.
- Create more display cards
- Return a message
- Navigate to another dialogue to continue the completion of a form
- Open a link
- Run background processes with an action method.
Links and resources
Hand On
- Get hands-on and build a Currency Converter Chat App With me! This multi-media series guides you step-by-step through the process of building your very own Currency Converter Chat App with Google Apps Script.
- Creating Webhooks for Google Chat App with Apps Script Learn how to create a webhook URL for a Google Chat and send chat messages, replies and cards with Google Apps Script.
Oh, and it’s pirate-themed 🏴☠️! - Google Codelab – Build an Attendance Bot with Apps Script (At the time of writing this it is a little dated using the old IDE but still fun). You can see my notes on updating the Codelab to the modern IDE here.
Google Documentation
- Develop a Chat app with Apps Script
- Build a Chat App With Apps Script
- The Cards v2 API used to build dialogues and cards
- Main Documentation Page for Chat Apps API
- YouTube Anatomy of a Google Chat App – This one is not entirely specific to Apps Script but still a good intro.
- YouTube Building Google Chat Apps – More by Google on Chat App development.
Tools
- Card and Dialogue Builder Tool at the time of writing this the builder uses the depreciated card_v1 method, but it still has some similar syntax.
- Card Services Card Builder Tool
Conclusion
So that’s the basics of what you need to know to get started building Chat Apps with Google Apps Script.
So what sort of chat app do you think you would like to build? Do you have a particular project in mind? Do you think your company would benefit from chat apps?
I’d love to hear your thoughts and ideas in the comments below.
In the next tutorial, we will get hands-on and build our first chat app. You know, our ‘hello world’ equivalent. Then we will start our currency converter chat app project.
If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.
Changelog
2023-11-04
- Testing and Deployment – new chapter added. Thanks to fellow Google Developer Expert (GDE) Aryan Irani for the momentum in making this update.
YAGISAN!
What a excellent all-in-one guide for creating Google Workspace Chat apps in Apps Script! Thanks for sharing 🙂