Send push message to Hangouts Chat with Apps Script

Hangouts Chat is the new Chat messagerie made by Google that will compete with all modern Chat app and mainly with Slack.

Implementation of Hangouts Chat with Apps Script, for building conversational chat bot, is really great. You can, in few lines of code, build your first chatbot. Check this codelab to build your first bot : Hangouts Chat Apps Script Codelab.

Introduction

This codelab will help you to build a chatbot that react to user messages, but what about sending message to users ? For that we have to setup a service account in order to be able to send message to users even if they don’t contact us.

Let’s do that by enabling us to send message to users to inform them for example when there is a new version of the bot or new functionalities.

Pre requisite

You are using a G Suite Account.

We will assume you have your own Chat Bot or you made the one from codelab we shared above.

Setup needed

1.We will need to setup a service account in order to be able to send our message, ref. Go to “Step 1. Create service account and private key” and follow instruction. In the Service account creation at step 3 click “Create Key”.

2.Install the Oauth2 Apps Script library to use the service account.

ID of library 1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF or source page for more details, link.

We are now ready !!!!

We will send our first message

Enable service account and get access token

First create the service :

Now test it by getting the access token.

If all works fine you have an access token in the Log (CTRL+ALT+Enter).

Send push message to all Direct Message the bot is installed

The process is simple you have to list all Spaces, select DMs and then send the message to each one.

You can get the code in the OAuth2 library samples on GitHub or get a script file with all required code, up to you.

Script file : link

GitHub OAuth2 library : link

Some thoughts on this code

As you can see in the Chat Spaces API response we can’t identify the owner of a space, so if you want to send a message to a specific person you will have to maintain a Spaces/Users directory in order to address the good one.

In the example we send a simple text message, you can of course send rich message.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store