Build a Google Chat app with Google Cloud Functions

Stay organized with collections Save and categorize content based on your preferences.

This page explains how to create and interact with a Google Chat app using Google Cloud Functions.

In this quickstart, you build a Chat app that responds to messages with a card. The card displays the sender's name and avatar image, as demonstrated in the following image:

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

To build the app, you write and deploy a Cloud Function that the app uses to process a response to a message event from Google Chat.

Prerequisites

To run this quickstart, you need the following:

Create and deploy a Google Cloud Function

Create and deploy a Google Cloud Function that generates a Chat card with the sender's display name and avatar image. When the Chat app receives a message, it runs the function and responds with the card.

To create and deploy the function for your Chat app, complete the following steps:

Node.js

  1. In the Google Cloud Console, go to the Cloud Functions page:

    Go to the Cloud Functions page

    Make sure that the project for your Chat app is selected.

  2. Click Create Function.

  3. On the Create function page, set up your function:

  4. In Function name, enter "QuickStartChatApp".

  5. In Trigger type, select HTTP.

  6. Under Authentication, select Allow unauthenticated invocations.

  7. Click Save.

  8. Click Next.

  9. In Runtime, select Node.js 10.

  10. In Source code, select Inline Editor

  11. In Entry point, delete the default text and enter helloChat.

  12. 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 must be called from Google Chat.');
      }
    
      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],
        }],
      };
    }
    
  13. Click Deploy.

Python

  1. In the Google Cloud Console, go to the Cloud Functions page:

    Go to the Cloud Functions page

    Make sure that the project for your Chat app is selected.

  2. Click Create Function.

  3. On the Create function page, set up your function:

  4. In Function name, enter "QuickStartChatApp".

  5. In Trigger type, select HTTP.

  6. Under Authentication, select Allow unauthenticated invocations.

  7. Click Save.

  8. Click Next.

  9. In Runtime, select Python 3.10.

  10. In Source code, select Inline Editor

  11. In Entry point, delete the default text and enter hello_chat.

  12. Replace the contents of main.py with the following code:

    from typing import Any, Mapping
    
    import flask
    import functions_framework
    
    # 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.
    @functions_framework.http
    def hello_chat(req: flask.Request):
      if req.method == 'GET':
        return 'Hello! This function must be called from Google Chat.'
    
      request_json = req.get_json(silent=True)
    
      display_name = request_json['message']['sender']['displayName']
      avatar = request_json['message']['sender']['avatarUrl']
    
      response = create_message(name=display_name, image_url=avatar)
    
      return response
    
    # Creates a card with two widgets.
    # @param {string} name the sender's display name.
    # @param {string} image_url the URL for the sender's avatar.
    # @return {Object} a card with the user's avatar.
    def create_message(name: str, image_url: str) -> Mapping[str, Any]:
      avatar_image_widget = {'image': {'imageUrl': image_url}}
      avatar_text_widget = {'textParagraph': {'text': 'Your avatar picture:'}}
      avatar_section = {'widgets': [avatar_text_widget, avatar_image_widget]}
    
      header = {'title': f'Hello {name}!'}
    
      cards = {'cards': [{'name': 'Avatar Card',
                          'header': header, 'sections': [avatar_section]}]}
    
      return cards
    
  13. Click Deploy.

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

Publish the app to Google Chat

After the Cloud Function is deployed, follow these steps to turn it into a Google Chat app:

  1. Open the Functions Overview page in the Google Cloud Console:

    Go to the Cloud Functions Overview page

    Make sure that the project for which you enabled Cloud Functions is selected.

  2. In the list of functions, click QuickStartChatApp.

  3. On the Function details page, click Trigger.

  4. Under "Trigger URL," copy the URL.

  5. Search for "Google Chat API" and click Google Chat API.

  6. Click Manage.

  7. Click Configuration and set up the Google Chat app:

    1. In App name, enter Quickstart App.
    2. In Avatar URL, enter https://developers.google.com/chat/images/quickstart-app-avatar.png.
    3. In Description, enter Quickstart app.
    4. Under Functionality, select Receive 1:1 messages, Join spaces and group conversations, and Log errors to Cloud Logging.
    5. Under Connection settings, select App 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 app is ready to receive and respond to messages on Google Chat.

Test your Chat app

To test your Chat app, send the app a direct message:

  1. Open Google Chat.
  2. Send a new direct message to the app by clicking Start a chat, and in the window that appears, click Find apps.
  3. In the Find apps dialog, search for "Quickstart App".
  4. Find the Quickstart App and click Add>Chat to open a direct message with the app.
  5. In the direct message, type Hello and press enter.

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

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

Debug your Chat app

As you build the Chat app, you might need to debug it by reading the app's error logs. To read the logs, visit the Logs Explorer on Google Cloud Console.

Troubleshoot the sample

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

Quickstart App is not responding

If you message the Chat app and it responds "Quickstart App is not responding", try the following:

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

Google Chat API is only available to Google Workspace users

When configuring the Chat app 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 apps are currently only available in Workspace domains, so a Google Workspace account is a prerequisite of this quickstart.

Function QuickStartChatApp in region us-central1 in project chatappproject already exists.

When deploying the Cloud Function, you might receive the error "Function QuickStartChatApp in region us-central1 in project chatappproject 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 "QuickStartChatApp2", and deploy the function again. Verify that the Chat app 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 app is publicly available and accessible without authentication. If you get this error and then message the Chat app, you get an error saying that the app 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.

Next steps

To add more functionality to your Chat app, refer to these guides:

  • Create interactive cards — Card messages support a defined layout, interactive UI elements like buttons, and rich media like images. Use card messages to present detailed information, gather information from users, and guide users to take a next step.
  • Support slash commands — Slash commands let you register and advertise specific commands that users can give your app by typing a command that begins with a forward slash (/), like /help.
  • Launch dialogs — Dialogs are windowed, card-based interfaces that your app can open to interact with a user. Multiple cards can be strung together sequentially, which helps users complete multi-step processes, like filling in form data.

To learn more about the Google Chat API, view the reference documentation.