Build a Google Chat app with Google Cloud Functions

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

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

Chat app 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 app receives a message, it runs this function and responds with the card.

Choose a language below for specific instructions about how to create the Chat app Cloud Function:

Node.js

  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:
  5. In Function name, enter "QuickStartChatApp".
  6. In Trigger type, select HTTP.
  7. Under Authentication, select Allow unauthenticated invocations.

  8. Click Save.

  9. Click Next.

  10. In Runtime, select Node.js 10.

  11. In Source code, select Inline Editor

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

  13. 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],
        }],
      };
    }
    
  14. Click Deploy.

Python

  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:
  5. In Function name, enter "QuickStartChatApp".
  6. In Trigger type, select HTTP.
  7. Under Authentication, select Allow unauthenticated invocations.

  8. Click Save.

  9. Click Next.

  10. In Runtime, select Python 3.10.

  11. In Source code, select Inline Editor

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

  13. 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
    
  14. 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 app to Google Chat

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

  1. On the Cloud Functions Overview page, click QuickStartChatApp.
  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 app:

    1. In App name, enter Quickstart App.
    2. In Avatar URL, enter https://developers.google.com/chat/images/chat-product-icon.png.
    3. In Description, enter Quickstart app.
    4. Under Functionality, select Receive 1:1 messages, Join spaces and group conversations, Receive @mentions, 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.

Step 3: Run the sample

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

  1. Open Google Chat.
  2. Send a new direct message to the app by clicking Start a chat > Find apps.
  3. On the Find apps page, search for "Quickstart App".
  4. Next to Quickstart App, click Chat.
  5. In the new direct message with the app, 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 the sample

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:

  • 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, 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.

Further reading

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