本指南介绍了 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 应用通过发送显示用户名称和头像图片的卡片消息进行响应:
异步发送卡片消息
如需发送卡片消息,请在请求中传递以下内容:
- 使用应用身份验证时,请指定
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
。
下面展示了如何使用定义为 nameOfThread
的 threadKey
字段发起或回复会话:
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
不是。 - 最多包含 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
方法或聊天室的网址获取该 ID。NAME
:消息的自定义名称。
在您的工作目录中,构建并运行该示例:
python3 chat_create_named_message.py
Chat API 会返回一个 Message
实例。
在邮件底部添加互动微件
您也可以选择为消息附加配件微件。 配件微件会显示在消息中的任何文本或卡片后面。您可以使用这些微件以多种方式提示用户与您的消息互动,包括:
- 对消息的准确性或满意度进行评分。
- 报告消息或 Chat 应用存在的问题。
- 打开指向相关内容(例如文档)的链接。
- 将 Chat 应用中的类似消息关闭或延后一段时间
如需添加配件 widget,请在消息中添加 accessoryWidgets[]
对象,并指定要包含的一个或多个 AccessoryWidgets
。消息必须对聊天室中的所有人都可见(您无法将配件微件添加到私信中)。
下图显示了一个 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",
}
}
}
]
}
}
]
以私密方式发送消息
Chat 应用可以私下发送文本和卡片消息,以便消息仅对聊天室中的一位用户可见。如需以私密方式发送消息,请在消息中指定 privateMessageViewer
字段。只有 Chat 扩展应用可以发送私信。如需异步发送私信,您必须使用应用身份验证。
有关详情,请参阅向 Google Chat 用户发送私信。
排查问题
当 Google Chat 应用或卡片返回错误时,Chat 界面会显示一条消息,提示“出了点问题”。或“无法处理您的请求”。有时,Chat 界面不显示任何错误消息,但 Chat 应用或卡片会产生意外结果;例如,卡片消息可能不会显示。
虽然 Chat 界面中可能未显示错误消息,但当为 Chat 应用启用错误日志记录时,系统会提供描述性错误消息和日志数据来帮助您修复错误。如需查看、调试和修正错误方面的帮助,请参阅排查和修正 Google Chat 错误。