Developing bots with Apps Script

Apps Script is one of the quickest ways to create a chat bot for Hangouts Chat.

  • You can get a bot up and running in just a few minutes directly in your browser.
  • You don't need to worry about running and managing servers, ongoing maintenance or operational costs, or even downloading and setting up a development environment.
  • It's very easy to call Google APIs—especially G Suite APIs—because with Apps Script there's no download or setup, auth is handled automatically, and Google API calls are just like native function calls.

This guide explains how to create and register a bot using Apps Script.

Getting started

This section shows you how to quickly create a chat bot using Apps Script.

Step 1: Copy the Apps Script template

The easiest way to get started creating an Apps Script bot is to use the Hangouts Chat bot template. This creates a new Apps Script project with the methods that you need. After that, populate the methods as required to implement your bot logic, or to integrate with a bot that you've built. The following code shows an example of the template populated for a simple bot.

 * Responds to a MESSAGE event in Hangouts Chat.
 * @param {Object} event the event object from Hangouts Chat
function onMessage(event) {
  var name = "";

  if ( == "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 Hangouts Chat.
 * @param {Object} event the event object from Hangouts Chat
function onAddToSpace(event) {
  var message = "";

  if ( == "DM") {
    message = "Thank you for adding me to a DM, " + event.user.displayName + "!";
  } else {
    message = "Thank you for adding me to " +;

  return { "text": message };

 * Responds to a REMOVED_FROM_SPACE event in Hangouts Chat.
 * @param {Object} event the event object from Hangouts Chat
function onRemoveFromSpace(event) {"Bot removed from ",;

Step 2: Edit the onMessage function

Right now, the onMessage function in that template will respond with a Message object that sends text and a simple card. You can edit this function to just return text or specific Card widgets.

function onMessage(e) {
  return { 'text': 'You said: \`' + e.message.text + '\`' };

Step 3: Get deployment ID

Before you can register your bot, you'll need to get the deploymentID for this specific bot. Choose Publish > Deploy from manifest..., then click on Get ID from a deployment:

See the Release Management guide to learn about recommended practices for using deployment IDs.

Step 4: Register the bot

You can register your bot from the Google Cloud developer console. On the bot registration screen, you will tell us the bot name, avatar URL and description. For testing, you can enable 'Bot works in DMs' and 'Bot works in Rooms'. Under connection settings, choose Apps Script and paste the deployment ID you copied in the previous step above.

Step 5: Test your bot

To test your bot, you can start a DM with it or @mention it into a Room. When you talk to it, it will respond to whatever the Message response is in Step 2. That's it!

Apps Script bot concepts


The onAddToSpace(e) functions in the template are executed when the user starts a DM with your bot or adds it to a Room. The argument e is an Event object.

When your bot is added, it should return a Message object similar to onMessage(e) in order to post a response. This function is very useful for sending a welcome message to tell end users about your bot.

Similarly, the onRemoveFromSpace(e) function is called when the user removes the bot from their DM list or from a room. The argument e is an Event.

Since the bot is being removed, it cannot respond to this event with another message; any returned value from this function is ignored.

The following example implements onAddToSpace and onRemoveFromSpace:

// onAddToSpace() is invoked when bot is added to a room or when
// a user initiates / re-initiates a direct message with the bot.
function onAddToSpace(e) {
  if ( === 'ROOM') {
    return { 'text': 'Thanks for adding me to "' + + '"!' };
  } else if ( === 'DM') {
    return { 'text': 'Thanks for adding me to a DM!' };
// onRemoveFromSpace() is invoked when bot is removed from a room
// or when a user removes a direct message with the bot.
function onRemoveFromSpace(e) {}

Interactive cards

Like other bots, Apps Script bots can display cards that are interactive. To learn about how to make cards interactive, check out that documentation on interactive cards. The main difference for Apps Script bots is that they can specify a specific method to call when the onClick event is fired by using action.actionMethodName and action.parameters key/value pairs as method parameters.


Apps Script bots that access protected resources need to ask users to authorize this access the first time it runs for each user. This doesn't require any work from you, but you should be aware that users may see an authorization dialog the first time they user your bot.

Async messages

Some bots might need to send messages into Hangouts Chat based on an external trigger, such as a Time-driven trigger in Apps Script. We plan to natively integrate the Hangouts Chat API into Apps Script for this use case. In the meantime, the only way to achieve this currently is via the external HTTP API (see documentation). This requires the use of a Cloud service account (see documentation) via the OAuth2 for Apps Script library. A full example bot which posts a message every minute to every room it's in (Example Clock Bot):

// Example bot for Hangouts Chat that demonstrates bot-initiated messages
// by spamming the user every minute.
// This bot makes use of the Apps Script OAuth2 library at:
// Follow the instructions there to add the library to your script.

// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
      .setProperty(, '');
  return {
    'text': 'Hi! I\'ll post a message here every minute. ' +
            'Please remove me after testing or I\'ll keep spamming you!'

// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {

// Add a trigger that invokes this function every minute via the
// "Edit > Current Project's Triggers" menu. When it runs, it will
// post in each space the bot was added to.
function onTrigger() {
  var spaceIds = PropertiesService.getScriptProperties()
  var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
  for (var i = 0; i < spaceIds.length; ++i) {
    postMessage(spaceIds[i], message);
var SCOPE = '';
// The values below are copied from the JSON file downloaded upon
// service account creation.

// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
  var service = OAuth2.createService('chat')
  if (!service.hasAccess()) {
    Logger.log('Authentication error: %s', service.getLastError());
  var url = '' + spaceId + '/messages';
  UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),

Manifest file

The following is an example of the Apps Script manifest file that must accompany your script. If you did not start your project from the Hangouts Chat bot template, then you need to edit the manifest file to add the "chat": {} object to it.

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

The manifest file is named appsscript.json and is part of your Apps Script project. To view the manifest file in the Apps Script editor, select View > Show manifest file.

Send feedback about...

Hangouts Chat
Hangouts Chat