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 theMessage
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.
The maximum message size (including any text or cards) is 32,000 bytes. If a message exceeds this size, your Chat app can send multiple messages instead.
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
- A Google Workspace account with access to Google Chat.
- 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.
- Sending a
text message
supports both of the following authorization methods:
- User authentication
with the
chat.messages.create
orchat.messages
authorization scope. - App authentication
with the
chat.bot
authorization scope.
- User authentication
with the
- Sending a
card message
requires
app authentication
with the
chat.bot
authorization scope.
- Sending a
text message
supports both of the following authorization methods:
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.
- Sending a
text message
supports both of the following authorization methods:
- User authentication
with the
chat.messages.create
orchat.messages
authorization scope. - App authentication
with the
chat.bot
authorization scope.
- User authentication
with the
- Sendinging a
card message
requires
app authentication
with the
chat.bot
authorization scope.
- Sending a
text message
supports both of the following authorization methods:
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.
- Sending a
text message
supports both of the following authorization methods:
- User authentication
with the
chat.messages.create
orchat.messages
authorization scope. - App authentication
with the
chat.bot
authorization scope.
- User authentication
with the
- Sendinging a
card message
requires
app authentication
with the
chat.bot
authorization scope.
- Sending a
text message
supports both of the following authorization methods:
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:
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 thechat.messages.create
authorization scope. - Call the
create
method on theMessage
resource.
Send a text message with app authentication
Here's how to send a text message with app authentication:
Python
- In your working directory, create a file named
chat_create_text_message_app.py
. 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)
In the code, replace
SPACE
with a space name, which you can obtain from thespaces.list()
method in the Chat API, or from a space's URL.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
- In your working directory, create a file named
chat_create_text_message_user.py
. 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 message. print(result) if __name__ == '__main__': main()
In the code, replace
SPACE
with a space name, which you can obtain from thespaces.list()
method in the Chat API, or from a space's URL.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.
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:
Node.js
Python
Apps Script
This example sends a card message by returning card JSON. You can also use the Apps Script card service.
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 theMessage
resource.
The following is an example of a card message:
Here's how to send a card message with app authentication:
Python
- In your working directory, create a file named
chat_create_card_message.py
. 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)
In the code, replace
SPACE
with a space name, which you can obtain from thespaces.list
method in the Chat API, or from a space's URL.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
- In your working directory, create a file named
chat_create_message_thread.py
. 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)
In the code, replace
SPACE
with a space name, which you can obtain from thespaces.list
method in the Chat API, or from a space's URL.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, butcustom-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
- In your working directory, create a file named
chat_create_named_message.py
. 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)
In the code, replace the following:
SPACE
: The ID for the space where you want to post the message, which you can obtain from thespaces.list
method in the Chat API, or from a space's URL.NAME
: The custom name for the message.
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.
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.
Related topics
- Format a message.
- Get details about a message.
- List messages in a space.
- Update a message.
- Delete a message.
- Identify users in Google Chat messages.
- Send messages to Google Chat with incoming webhooks.