本指南介绍了 Google Chat 应用发送消息的不同方式:
- 通过响应用户互动实时发送文本和卡片消息。
- 通过对
Message
资源调用create
方法,异步发送文本和卡片消息。 - 发起或回复消息串。
- 发送消息并为其命名。
Message
资源表示 Google Chat 中的文本或卡片消息。您可以通过调用相应的方法,在 Google Chat API 中对消息执行 create
、get
、update
或 delete
操作。如需详细了解文本和卡片消息,请参阅 Google Chat 消息概览。
消息大小上限(包括所有文字或卡片)为 32,000 字节。 如果消息超过此大小,您的 Chat 应用可以改为发送多条消息。
Google Chat 应用也可以创建消息来实时响应用户互动,而不是在 Google Chat API 的 Message
资源上调用 create
方法来异步发送短信或卡片消息。对用户互动的响应不需要身份验证,并且支持其他类型的消息,包括交互式对话框和链接预览。如需了解详情,请参阅接收和回复用户与 Google Chat 应用的互动。
前提条件
Node.js
- 有权访问 Google Chat 的 Google Workspace 帐号。
- 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用。
- 为 Chat 应用配置发送异步消息的授权。无需授权配置即可实时发送消息。
Python
- 有权访问 Google Chat 的 Google Workspace 帐号。
- Python 3.6 或更高版本
- pip 软件包管理工具
适用于 Python 的最新 Google 客户端库。如需安装或更新它们,请在命令行界面中运行以下命令:
pip3 install --upgrade google-api-python-client google-auth
- 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用。
为 Chat 应用配置发送异步消息的授权。无需授权配置即可实时发送消息。
Apps 脚本
- 有权访问 Google Chat 的 Google Workspace 帐号。
- 一款已发布的 Chat 应用。如需构建 Chat 应用,请按照此quickstart操作。
- 为 Chat 应用配置发送异步消息的授权。无需授权配置即可实时发送消息。
发送短信
本节介绍如何通过以下两种方式发送短信:
- 通过响应用户互动实时发送短信。
- 异步调用 Google Chat API 来发送短信。
实时发送短信
在此示例中,只要将 Chat 应用添加到聊天室,该应用就会创建并发送短信。如需了解新手入门用户的最佳做法,请参阅通过实用的新手入门流程,让人员和聊天室开始使用。
为了在用户将您的 Chat 应用添加到聊天室时发送短信,您的 Chat 应用会响应 ADDED_TO_SPACE
互动事件。如需通过短信响应 ADDED_TO_SPACE
互动事件,请使用以下代码:
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 脚本
/**
* 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`.'
}
}
代码示例会返回以下文本消息:
异步发送短信
以下部分介绍了如何通过应用身份验证和用户身份验证异步发送短信。
如需发送短信,请在请求中传递以下内容:
- 使用应用身份验证时,请指定
chat.bot
授权范围。使用用户身份验证时,请指定chat.messages.create
授权范围。 - 对
Message
资源调用create
方法。
通过短信进行应用身份验证
使用应用身份验证发送短信的方法如下:
Python
- 在您的工作目录中,创建一个名为
chat_create_text_message_app.py
的文件。 在
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)
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list()
方法或聊天室网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_create_text_message_app.py
Chat API 会返回 Message
的实例,其中详细说明了发送的消息。
发送包含用户身份验证的短信
下面展示了如何发送短信进行用户身份验证:
Python
- 在您的工作目录中,创建一个名为
chat_create_text_message_user.py
的文件。 在
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()
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list()
方法或聊天室的网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_create_text_message_user.py
Chat API 会返回 Message
的实例,其中详细说明了发送的消息。
发送银行卡消息
本部分介绍了如何通过以下两种方式发送卡片消息:
- 通过响应用户互动实时发送卡片消息。
- 异步调用 Google Chat API 来发送卡片消息。
实时发送卡片消息
聊天应用可以创建卡片消息来响应用户互动,例如当用户向 Chat 应用发送消息或将 Chat 应用添加到聊天室时。如需详细了解如何响应用户互动,请参阅接收和响应 Chat 应用互动事件。
在此示例中,用户向 Chat 应用发送消息,Chat 应用通过发送一条卡片消息来响应,该消息显示用户的姓名和头像图片:
异步发送卡片消息
如需发送卡片消息,请在请求中传递以下内容:
- 使用应用身份验证时,请指定
chat.bot
授权范围。您无法发送进行用户身份验证的卡消息。 - 对
Message
资源调用create
方法。
以下是卡片消息示例:
通过应用身份验证发送银行卡消息的方法如下:
Python
- 在您的工作目录中,创建一个名为
chat_create_card_message.py
的文件。 在
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)
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或聊天室网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_create_card_message.py
发起或回复消息串
如需启动消息会话,请发送消息并将 thread.name
留空;Google Chat 会在创建该消息串时进行填充。(可选)如需自定义线程名称,请指定 thread.threadKey
字段。
如需回复某个消息会话,请发送一条消息,指定该会话的 threadKey
或 name
字段。如果会话是由用户或其他 Chat 应用创建的,您必须使用 thread.name
字段。
如果未找到匹配的会话,您可以通过设置 messageReplyOption
字段来指定消息是应该启动新会话,还是无法发布。
如果设置了 messageReplyOption
,则还必须设置 thread.name
或 thread.threadKey
。
下面展示了如何发起或回复将 threadKey
字段定义为 nameOfThread
的会话:
Python
- 在您的工作目录中,创建一个名为
chat_create_message_thread.py
的文件。 在
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)
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或聊天室网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_create_message_thread.py
Chat API 会返回 Message
的实例,其中详细说明了发送的消息。
为消息命名
本部分介绍了如何通过为消息设置自定义 ID 来为消息命名。您可以使用自定义 ID 获取、更新或删除邮件。借助自定义 ID,您可以指定消息,而无需存储消息资源名称(由 name
字段表示)中的系统分配的 ID。当您创建消息时,响应正文中会生成资源名称。
例如,如需使用 get()
方法检索消息,您可以使用资源名称指定要检索的消息。资源名称的格式为 spaces/{space}/messages/{message}
,其中 {message}
表示系统分配的 ID。如果您已为消息命名,可以将 {message}
的值替换为自定义 ID。
如需为消息命名,请在创建消息时在 messageId
字段中指定自定义 ID。messageId
字段用于设置 Message
资源的 clientAssignedMessageId
字段的值。
您只能在创建消息时为其命名。您无法命名或修改现有消息的自定义 ID。自定义 ID 必须满足以下要求:
- 以
client-
开头。例如,client-custom-name
是有效的自定义 ID,但custom-name
不是有效的自定义 ID。 - 最多包含 63 个字符,且只能包含小写字母、数字和连字符。
- 在聊天室中是唯一的。Chat 应用无法针对不同的消息使用相同的自定义 ID。
使用自定义 ID 发送消息的方法如下:
Python
- 在您的工作目录中,创建一个名为
chat_create_named_message.py
的文件。 在
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)
在代码中,替换以下内容:
SPACE
:您要在其中发布消息的聊天室的 ID,可通过 Chat API 中的spaces.list
方法或聊天室的网址获取。NAME
:消息的自定义名称。
在您的工作目录中,构建并运行示例:
python3 chat_create_named_message.py
Chat API 会返回 Message
的实例。
在邮件底部添加互动微件
您也可以选择使用配件微件附加消息。 配件微件会显示在消息中的任何文字或卡片后面。您可以使用这些 widget 以多种方式提示用户与您的消息互动,包括:
- 对消息的准确性或满意度进行评分。
- 报告与信息或 Chat 应用相关的问题。
- 打开指向相关内容(例如文档)的链接。
- 在特定时间段内忽略或延后 Chat 应用中的类似消息。
如需添加配件 widget,请在消息中包含 accessoryWidgets[]
对象,并指定要添加的一个或多个 AccessoryWidgets
。该消息必须对聊天室中的所有人可见(您无法将配件 widget 添加到私信中)。
下图显示的 Chat 应用会附加一条带有配件 widget 的短信,以便用户可以对 Chat 应用的使用体验进行评分。
以下代码示例展示了此消息的 JSON。当用户点击其中一个按钮时,互动会触发处理评分的相应函数(如 doUpvote
)。
"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",
}
}
}
]
}
}
]
以私密方式发送消息
聊天应用可以私密地发送短信和卡片消息,以确保消息仅对聊天室中的一位用户可见。如需以私密方式发送消息,请在消息中指定 privateMessageViewer
字段。只有 Chat 应用可以发送私信。如需异步发送私信,您必须使用应用身份验证。
如需了解详情,请参阅向 Google Chat 用户发送私信。
排查问题
当 Google Chat 应用或卡片返回错误时,Chat 界面会显示“出了点问题”的消息。或“无法处理您的请求”。有时,Chat 界面不会显示任何错误消息,但 Chat 应用或卡片会产生意外结果;例如,卡片消息可能不会显示。
虽然 Chat 界面中可能不会显示错误消息,但当为 Chat 应用启用错误日志记录功能时,描述性错误消息和日志数据可帮助您修复错误。如需查看、调试和修复错误方面的帮助,请参阅排查和修正 Google Chat 错误。