Send push message to Hangouts Chat with Apps Script

Stéphane Giron
4 min readApr 18, 2019

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 :

var PRIVATE_KEY = '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n';
var CLIENT_EMAIL = '...';
/**
* Configures the Chatbot service.
*/
function getChatbotService() {
return OAuth2.createService(‘MyChatBot’)
// Set the endpoint URL.
.setTokenUrl(‘https://accounts.google.com/o/oauth2/token')
// Set the private key and issuer.
.setPrivateKey(PRIVATE_KEY)
.setIssuer(CLIENT_EMAIL)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope.
.setScope(‘https://www.googleapis.com/auth/chat.bot');
}

Now test it by getting the access token.

/**
* Test for getting access token
*/
function getAccessTokenTest() {
var service = getChatbotService();
if (service.hasAccess()) {
Logger.log(service.getAccessToken());
} else {
Logger.log(service.getLastError());
}
}

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.

/**
* Authorizes and makes a request to the Hangouts Chat API for :
* - Getting all spaces the bot is installed
* - Sending message when space is a Direct Message space
*/
function sendPushMessage() {
var service = getChatbotService();
if (service.hasAccess()) {
//WE retrieve all the spaces bot has been added
var url = 'https://chat.googleapis.com/v1/spaces';
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
}
});
var rep = JSON.parse(response.getContentText());
if(rep.spaces && rep.spaces.length > 0){
for(var i = 0; i < rep.spaces.length; i++) {
var space = rep.spaces[i];
if(space.type == "DM"){
//We send message only to Direct Message room.
var url = 'https://chat.googleapis.com/v1/'+space.name+'/messages';

var options = {
method : 'POST',
contentType: 'application/json',
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
payload : JSON.stringify({ text: "Hello world !" })
}

//We send message to the DM room
UrlFetchApp.fetch(url, options);
}else{
//If Type is 'ROOM' or 'TYPE_UNSPECIFIED' we don't send notification.
}
}
}else{
Logger.log('Bot is not added to any spaces');
}
} else {
Logger.log(service.getLastError());
}
}

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.

--

--