Send a message

This guide explains the different ways that Google Chat apps can send messages:

  • Send text and card messages in real time by responding to a user interaction.
  • Send text and card messages asynchronously by calling the create method on the Message resource.
  • Start or reply to a message thread.
  • Send and name a message.

The Message resource represents a text or card message in Google Chat. You can create, get, update, or delete a message in the Google Chat API by calling corresponding methods. To learn more about text and card messages, see Google Chat messages overview.

Instead of calling the create method on the Message resource of the Google Chat API to send a text or card message asynchronously, Google Chat apps can also create messages to respond to user interactions in real time. Responses to user interactions don't require authentication and support other types of messages, including interactive dialogs and link previews. For details, see Receive and respond to interactions with your Google Chat app.

Prerequisites

Node.js

Python

  • A Google Workspace account with access to Google Chat.
  • Python 3.6 or greater
  • The pip package management tool
  • The latest Google client libraries for Python. To install or update them, run the following command in your command-line interface:

    pip3 install --upgrade google-api-python-client google-auth
    
  • A Google Cloud project with the Google Chat API enabled and configured. For steps, see Build a Google Chat app.
  • Authorization configured for the Chat app to send asynchronous messages. No authorization configuration is required to send messages in real time.

Apps Script

  • A Google Workspace account with access to Google Chat.
  • A published Chat app. To build a Chat app, follow this quickstart.
  • Authorization configured for the Chat app to send asynchronous messages. No authorization configuration is required to send messages in real time.

Send text messages

This section describes how to send text messages in the following two ways:

  • Send a text message in real time by responding to a user interaction.
  • Send a text message by calling the Google Chat API asynchronously.

Send a text message in real time

In this example, your Chat app creates and sends a text message whenever it's added to a space. To learn about best practices for onboarding users, see Get people and spaces started with helpful onboarding.

To send a text message when a user adds your Chat app to a space, your Chat app responds to an ADDED_TO_SPACE interaction event. To respond to ADDED_TO_SPACE interaction events with a text message, use the following code:

Node.js

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
exports.onMessage = function onMessage(req, res) {
  if (req.method === 'GET' || !req.body.message) {
    res.send(
      'Hello! This function is meant to be used in a Google Chat space.');
  }

  // Send an onboarding message when added to a Chat space
  if (req.body.type === 'ADDED_TO_SPACE') {
    res.json({
      'text': 'Hi, Cymbal at your service. I help you manage your calendar
      from Google Chat. Take a look at your schedule today by typing
      `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To
      learn what else I can do, type `/help`.'
    });
  }
};

Apps Script

/**
 * Sends an onboarding message when the Chat app is added to a space.
 *
 * @param {Object} event The event object from Chat API.
 * @return {Object} Response from the Chat app. An onboarding message that
 * introduces the app and helps people get started with it.
 */
function onAddToSpace(event) {

  return {
    'text': 'Hi, Cymbal at your service. I help you manage your calendar
    from Google Chat. Take a look at your schedule today by typing
    `/checkCalendar`, or schedule a meeting with `/scheduleMeeting`. To learn
    what else I can do, type `/help`.'
  }
}

The code sample returns the following text message:

Example onboarding message.

Send a text message asynchronously

The following section explains how to send a text message asynchronously with app authentication and user authentication.

To send a text message, pass the following in your request:

  • With app authentication, specify the chat.bot authorization scope. With user authentication, specify the chat.messages.create authorization scope.
  • Call the create method on the Message resource.

Send a text message with app authentication

Here's how to send a text message with app authentication:

Python

  1. In your working directory, create a file named chat_create_text_message_app.py.
  2. Include the following code in chat_create_text_message_app.py:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. In the code, replace SPACE with a space name, which you can obtain from the spaces.list() method in the Chat API, or from a space's URL.

  4. In your working directory, build and run the sample:

    python3 chat_create_text_message_app.py
    

The Chat API returns an instance of Message that details the message that's sent.

Send a text message with user authentication

Here's how to send a text message with user authentication:

Python

  1. In your working directory, create a file named chat_create_text_message_user.py.
  2. Include the following code in chat_create_text_message_user.py:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # Define your app's authorization scopes.
    # When modifying these scopes, delete the file token.json, if it exists.
    SCOPES = ["https://www.googleapis.com/auth/chat.messages.create"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then creates a text message in a Chat space.
        '''
    
        # Start with no credentials.
        creds = None
    
        # Authenticate with Google Workspace
        # and get user authorization.
        flow = InstalledAppFlow.from_client_secrets_file(
                        'client_secrets.json', SCOPES)
        creds = flow.run_local_server()
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds)
    
        # Use the service endpoint to call Chat API.
        result = chat.spaces().messages().create(
    
            # The space to create the message in.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            parent='spaces/SPACE',
    
            # The message to create.
            body={'text': 'Hello, world!'}
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. In the code, replace SPACE with a space name, which you can obtain from the spaces.list() method in the Chat API, or from a space's URL.

  4. In your working directory, build and run the sample:

    python3 chat_create_text_message_user.py
    

The Chat API returns an instance of Message that details the message that's sent.

Send card messages

This section describes how to send card messages in the following two ways:

  • Send a card message in real time by responding to a user interaction.
  • Send a card message by calling the Google Chat API asynchronously.


Design and preview cards with the Card Builder.

Open the Card Builder

Send a card message in real time

Chat apps can create card messages to respond to a user interaction, such as when a user sends the Chat app a message or adds the Chat app to a space. To learn more about responding to user interactions, see Receive and respond to Chat app interaction events.

In this example, a user sends a message to a Chat app and the Chat app responds by sending a card message that displays the user's name and avatar image:

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

Node.js

node/avatar-app/index.js
/**
 * Google Cloud Function that responds to messages sent from a
 * Google Chat room.
 *
 * @param {Object} req Request sent from Google Chat room
 * @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 ' +
      'Room.');
  }

  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},
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget,
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Python

python/avatar-app/main.py
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) -> Mapping[str, Any]:
  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 = {
      "text": "Here's your avatar",
      "cardsV2": [
          {
              "cardId": "avatarCard",
              "card": {
                  "name": "Avatar Card",
                  "header": header,
                  "sections": [avatar_section],
              },
          }
      ]
  }

  return cards

Apps Script

apps-script/avatar-app/hello-chat.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  const displayName = event.message.sender.displayName;
  const avatarUrl = event.message.sender.avatarUrl;

  return createMessage(displayName, avatarUrl);
}

/**
 * Creates a card with two widgets.
 * @param {string} displayName the sender's display name
 * @param {string} avatarUrl the URL for the sender's avatar
 * @return {Object} a card with the sender's avatar.
 */
function createMessage(displayName, avatarUrl) {
  const cardHeader = {
    title: `Hello ${displayName}!`
  };

  const avatarWidget = {
    textParagraph: {text: 'Your avatar picture: '}
  };

  const avatarImageWidget = {
    image: {imageUrl: avatarUrl}
  };

  const avatarSection = {
    widgets: [
      avatarWidget,
      avatarImageWidget
    ],
  };

  return {
    text: 'Here\'s your avatar',
    cardsV2: [{
      cardId: 'avatarCard',
      card: {
        name: 'Avatar Card',
        header: cardHeader,
        sections: [avatarSection],
      }
    }],
  };
}

Send a card message asynchronously

To send a card message, pass the following in your request:

  • With app authentication, specify the chat.bot authorization scope. You can't send a card message with user authentication.
  • Call the create method on the Message resource.

The following is an example of a card message:

A card message sent with the Chat API.

Here's how to send a card message with app authentication:

Python

  1. In your working directory, create a file named chat_create_card_message.py.
  2. Include the following code in chat_create_card_message.py:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # The message to create.
        body=
        {
          'cardsV2': [{
            'cardId': 'createCardMessage',
            'card': {
              'header': {
                'title': 'A card message!',
                'subtitle': 'Created with the Chat API',
                'imageUrl': 'https://developers.google.com/chat/images/chat-product-icon.png',
                'imageType': 'CIRCLE'
              },
              'sections': [
                {
                  'widgets': [
                    {
                      'buttonList': {
                        'buttons': [
                          {
                            'text': 'Read the docs!',
                            'onClick': {
                              'openLink': {
                                'url': 'https://developers.google.com/chat'
                              }
                            }
                          }
                        ]
                      }
                    }
                  ]
                }
              ]
            }
          }]
        }
    
    ).execute()
    
    print(result)
    
  3. In the code, replace SPACE with a space name, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.

  4. In your working directory, build and run the sample:

    python3 chat_create_card_message.py
    

Start or reply to a message thread

To start a message thread, send a message and leave thread.name empty; Google Chat populates it when creating the thread. Optionally, to customize the name of the thread, specify the thread.threadKey field.

To reply to a message thread, send a message that specifies the thread's threadKey or name field. If the thread was created by a person or another Chat app, you must use the thread.name field.

If no matching thread is found, you can specify whether a message should start a new thread or fail to post by setting messageReplyOption field.

If messageReplyOption is set, you must also set either thread.name or thread.threadKey.

Here's how to start or reply to a thread with the threadKey field defined as nameOfThread:

Python

  1. In your working directory, create a file named chat_create_message_thread.py.
  2. Include the following code in chat_create_message_thread.py:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Whether to start a thread or reply to an existing one.
        #
        # Required when threading is enabled in a space unless starting a
        # thread.  Ignored in other space types. Threading is enabled when
        # space.spaceThreadingState is THREADED_MESSAGES.
        #
        # REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD replies to an existing thread
        # if one exists, otherwise it starts a new one.
        messageReplyOption='REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD',
    
        # The message body.
        body={
    
            # The message to create.
            'text': 'Start or reply to another message in a thread!',
    
            # The thread to start or reply to.
            'thread': {
                'threadKey': 'nameOfThread'
            }
        }
    
    ).execute()
    
    print(result)
    
  3. In the code, replace SPACE with a space name, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.

  4. In your working directory, build and run the sample:

    python3 chat_create_message_thread.py
    

The Chat API returns an instance of Message that details the message that's sent.

Name a message

This section explains how to name a message by setting a custom ID for the message. You can use custom IDs to get, update, or delete messages. Custom IDs let you specify a message without needing to store the system-assigned ID from the resource name of the message (represented in the name field). The resource name is generated in the response body when you create the message.

For example, to retrieve a message using the get() method, you use the resource name to specify which message to retrieve. The resource name is formatted as spaces/{space}/messages/{message}, where {message} represents the system-assigned ID. If you've named the message, you can replace the value of {message} with the custom ID.

To name a message, specify a custom ID in the messageId field when you create the message. The messageId field sets the value for the clientAssignedMessageId field of the Message resource.

You can only name a message when you create the message. You can't name or modify a custom ID for existing messages. The custom ID must meet the following requirements:

  • Begins with client-. For example, client-custom-name is a valid custom ID, but custom-name is not.
  • Contains up to 63 characters and only lowercase letters, numbers, and hyphens.
  • Is unique within a space. A Chat app can't use the same custom ID for different messages.

Here's how to send a message with a custom ID:

Python

  1. In your working directory, create a file named chat_create_named_message.py.
  2. Include the following code in chat_create_named_message.py:

    from apiclient.discovery import build
    from google.oauth2 import service_account
    
    # Specify required scopes.
    SCOPES = ['https://www.googleapis.com/auth/chat.bot']
    
    # Specify service account details.
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        'credentials.json', scopes=SCOPES)
    
    # Build the URI and authenticate with the service account.
    chat = build('chat', 'v1', credentials=CREDENTIALS)
    
    # Create a Chat message with a custom name.
    result = chat.spaces().messages().create(
    
        # The space to create the message in.
        #
        # Replace SPACE with a space name.
        # Obtain the space name from the spaces resource of Chat API,
        # or from a space's URL.
        parent='spaces/SPACE',
    
        # Custom name for the message used to facilitate later operations.
        messageId='client-NAME',
    
        # The message to create.
        body={'text': 'Hello, world!'}
    
    ).execute()
    
    print(result)
    
  3. In the code, replace the following:

    • SPACE: The ID for the space where you want to post the message, which you can obtain from the spaces.list method in the Chat API, or from a space's URL.
    • NAME: The custom name for the message.
  4. In your working directory, build and run the sample:

    python3 chat_create_named_message.py
    

The Chat API returns an instance of Message.

Add interactive widgets at the bottom of a message

Optionally, you can append messages with accessory widgets. Accessory widgets appear after any text or cards in a message. You can use these widgets to prompt users to interact with your message in many ways, including the following:

  • Rate the accuracy or satisfaction of a message.
  • Report an issue with the message or Chat app.
  • Open a link to related content, such as documentation.
  • Dismiss or snooze similar messages from the Chat app for a specific period of time.

To add accessory widgets, include the accessoryWidgets[] object in the message and specify one or more AccessoryWidgets that you want to include. The message must be visible to everyone in the space (You can't add accessory widgets to private messages).

The following image shows a Chat app that appends a text message with accessory widgets so that users can rate their experience with the Chat app.

Example accessory widgets

The following code sample shows the JSON for this message. When a user clicks one of the buttons, the interaction triggers the corresponding function (such as doUpvote) that processes the rating.


 "text": "Rate your experience with this Chat app.",
 "accessoryWidgets": [
   {
     "buttonList": {
       "buttons": [
         {
           "icon": {
             "material_icon": {
               "name": "thumb_up"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doUpvote",
             }
           }
         },
         {
           "icon": {
             "material_icon": {
               "name": "thumb_down"
             }
           },
           "color": {
             "red": 0,
             "blue": 255,
             "green": 0
           },
           "onClick": {
             "action": {
               "function": "doDownvote",
             }
           }
         }
       ]
     }
   }
 ]

Send messages privately

Chat apps can send text and card messages privately so that the message is only visible to one user in the space. To send a message privately, you specify the privateMessageViewer field in the message. Only Chat apps can send private messages. To send a private message asynchronously, you must use app authentication.

For details, see Send private messages to Google Chat users.

Troubleshoot

When a Google Chat app or card returns an error, the Chat interface surfaces a message saying "Something went wrong." or "Unable to process your request." Sometimes the Chat UI doesn't display any error message, but the Chat app or card produces an unexpected result; for example, a card message might not appear.

Although an error message might not display in the Chat UI, descriptive error messages and log data are available to help you fix errors when error logging for Chat apps is turned on. For help viewing, debugging, and fixing errors, see Troubleshoot and fix Google Chat errors.