Build a Google Chat bot with Google Cloud Functions

Complete the following steps to create a Google Chat bot that responds to messages it receives with a card. The card shows the sender's display name and avatar image. The bot uses Google Cloud Functions to process and respond to a textual trigger event (a message) from Google Chat.

After completing these steps, here's how the bot responds to messages:

Chat bot responding with a card featuring the sender's display name and avatar image

Prerequisites

To run this quickstart, you need:

Step 1: Create and deploy the Google Cloud Function

Write and deploy a function that creates a Chat card with the sender's display name and avatar image. When the Chat bot receives a message, it runs this function and responds with the card.

  1. Open the Google Cloud Console.
  2. Search for "Cloud Functions" and click Cloud Functions.
  3. Click Create Function.
  4. On the Create function page, set up your function:

    1. In Function name, enter "QuickStartChatBot".
    2. In Trigger type, select HTTP.
    3. Under Authentication, select Allow unauthenticated invocations.
    1. Click Save.
    2. Click Next.
    3. In Runtime, select Node.js 10.
    4. In Source code, select Inline Editor
    5. In Entry point, delete the default text and enter helloChat.
    6. Replace the contents of index.js with the following code:
    /**
     * Google Cloud Function that responds to messages sent in
     * Google Chat.
     *
     * @param {Object} req Request sent from Google Chat.
     * @param {Object} res Response to send back.
     */
    exports.helloChat = function helloChat(req, res) {
      if (req.method === 'GET' || !req.body.message) {
        res.send('Hello! This function is meant to be used in a Google Chat ' +
          'Space.');
      }
    
      const sender = req.body.message.sender.displayName;
      const image = req.body.message.sender.avatarUrl;
    
      const data = createMessage(sender, image);
    
      res.send(data);
    };
    
    /**
     * Creates a card with two widgets.
     * @param {string} displayName the sender's display name.
     * @param {string} imageURL the URL for the sender's avatar.
     * @return {Object} a card with the user's avatar.
     */
    function createMessage(displayName, imageURL) {
      const cardHeader = {
        'title': 'Hello ' + displayName + '!',
      };
    
      const avatarWidget = {
        'textParagraph': {'text': 'Your avatar picture: '},
      };
    
      const avatarImageWidget = {
        image: {'imageUrl': imageURL},
      };
    
      const avatarSection = {
        'widgets': [
          avatarWidget,
          avatarImageWidget,
        ],
      };
    
      return {
        'cards': [{
          'name': 'Avatar Card',
          'header': cardHeader,
          'sections': [avatarSection],
        }],
      };
    }
    
  5. Click Deploy.

The Cloud Functions page opens and your Cloud Function begins deployment. Your function appears with a deployment progress indicator next to it. When the progress indicator disappears and a checkmark appears, your function is deployed.

Step 2: Publish the bot to Google Chat

After the Cloud Function finishes deploying, follow these steps to turn it into a Google Chat bot.

  1. On the Cloud Functions Overview page, click QuickStartChatBot.
  2. On the Function details page, click Trigger.
  3. Under "Trigger URL," copy the URL.
  4. Search for "Google Chat API" and click Google Chat API.
  5. Click Manage.
  6. Click Configuration and set up the Google Chat bot:

    1. In Bot name, enter "Quickstart bot".
    2. In Avatar URL, enter https://goo.gl/yKKjbw.
    3. In Description, enter "Quickstart bot".
    4. Under Functionality, select Bot works in direct messages and Bot works in spaces and direct messages with multiple users.
    5. Under Connection settings, select Bot URL and paste the URL for the Cloud Function trigger into the box.
    6. Under Permissions, select Specific people and groups in your domain and enter your email address.

    7. Click Save.

The bot is ready to receive and respond to messages on Google Chat.

Step 3: Run the sample

To run the sample, send a message to the Google Chat bot:

  1. Open Google Chat.
  2. Send a new direct message to the bot by clicking Start a chat > Find a bot.
  3. On the Find a bot page, search for "Quickstart Bot".
  4. Select Quickstart Bot and click Message.
  5. In the new direct message with the bot, type "Hello" and press enter.

The bot returns a card with your display name and avatar picture.

If you have problems, refer to the Troubleshoot the sample section.

Troubleshoot the sample

This section describes common issues that you can encounter while attempting to run this quickstart.

Quickstart Bot is not responding

If you message the Chat bot and it responds "Quickstart Bot is not responding", try:

  • Verify the Chat bot's configuration:
    • Under Connection Settings, ensure Bot URL is selected. Also ensure the Bot URL matches the Trigger URL of your Cloud Function.
    • Under Functionality, ensure Bot works in direct messages is selected.
  • Verify that all prerequisite APIs (Cloud Build API, Cloud Functions API, and Google Chat API) are still enabled in your Google Cloud Project. If one or more is disabled, then the Chat bot stops responding. If the Cloud Functions API is disabled, then the Cloud Function that the bot uses to respond is deleted, and must be recreated.

Google Chat API is only available to Google Workspace users

When configuring the Chat bot for publication, you might receive the error "Google Chat API is only available to Google Workspace users." This message means that your Google account is not part of a Workspace domain. Chat bots are currently only available in Workspace domains, so a Google Workspace account is a prerequisite of this quickstart.

Function QuickStartChatBot in region us-central1 in project chatbotproject already exists.

When deploying the Cloud Function, you might receive the error "Function QuickStartChatBot in region us-central1 in project chatbotproject already exists." This message means that another Cloud Function has the same name as the one you're deploying. Change the name, for example, to "QuickStartChatBot2", and deploy the function again. Verify that the Chat bot uses the Trigger URL for your Cloud Function, not the Trigger URL of the preexisting Cloud Function.

One or more users named in the policy do not belong to a permitted customer.

When deploying the Cloud Function, you might receive the error The operation cannot be completed on the function: "One or more users named in the policy do not belong to a permitted customer." This message means that a user named "allUsers" does not have permission to invoke the Cloud Function. Giving "allUsers" the "Cloud Functions Invoker" role means that the Cloud Function that powers the bot is publicly available and accessible without authentication. If you get this error and then message the Chat bot, you get an error saying that the bot is not responding because Google Chat can't reach the server hosting the Cloud Function.

This error might mean that the Google Cloud project is domain restricted. For more information about domain restriction constraints, refer to Restricting identities by domain.

To resolve this issue, verify that your Cloud Function allows unauthenticated invocations. To learn how to allow unauthenticated invocations for an existing Cloud Function, refer to Allowing public (unauthenticated) access.

Further reading

For further information on the APIs used in this quickstart, refer to the following: