本页介绍如何为 Google Chat 应用设置斜杠命令。
斜杠命令是用户调用 Chat 应用并与之互动的一种常用方式。斜杠命令还有助于用户发现和使用 Chat 应用的关键功能。
如需使用斜杠命令,用户需要依次输入斜杠 (/
) 和简短的文本命令(例如 /about
),以获取有关 Chat 应用的信息。用户可以通过在 Google Chat 中输入斜杠来发现可用的斜杠命令,该窗口会显示一个窗口,其中列出了 Chat 应用的可用命令:

如需决定是否应设置斜杠命令,以及了解如何设计用户互动,请参阅 Google Chat 设计原则。
前提条件
Node.js
- 有权访问 Google Chat 的 Google Workspace 帐号。
- 一个 Chat 应用。如需构建 Chat 应用,请按照此quickstart操作。
Apps 脚本
- 有权访问 Google Chat 的 Google Workspace 帐号。
- 一个 Chat 应用。如需构建 Chat 应用,请按照此quickstart操作。
Python
- 有权访问 Google Chat 的 Google Workspace 帐号。
- 一个 Chat 应用。如需构建 Chat 应用,请按照此quickstart操作。
设置斜杠命令
如需设置斜杠命令,请完成以下步骤:
本部分介绍了设置斜杠命令的步骤。
为斜杠命令命名
斜杠命令的名称是用户在 Chat 消息中输入的名称以调用 Chat 应用。名称下方还会显示一条简短说明,用于进一步提示用户如何使用该命令:

为斜杠命令选择名称和说明时,请考虑以下建议:
要为斜杠命令命名,请执行以下操作:
- 使用简短、描述性且可操作的字词或短语,使命令对用户来说简单明了。例如,不要使用
/createAReminder
,而应使用/remindMe
。 - 如果您的命令包含多个单词,请将第一个单词的首字母大写,并将其他单词的首字母大写,以此帮助用户阅读命令。例如,使用
/updateContact
,而不要使用/updatecontact
。 - 考虑为您的命令使用唯一名称还是通用名称。如果您的命令描述的是典型的互动或功能,您可以使用用户可识别和期待的通用名称,例如
/settings
或/feedback
。否则,请尝试使用独一无二的命令名称,因为如果您的命令名称与其他聊天应用相同,则用户必须通过类似的命令进行过滤,才能找到并使用您的命令。
- 使用简短、描述性且可操作的字词或短语,使命令对用户来说简单明了。例如,不要使用
如需描述您的斜杠命令,请执行以下操作:
- 请保证说明简洁明了,以便用户知道在调用命令时会看到什么内容。
- 告知用户该命令是否有任何格式设置要求。
例如,如果您创建需要参数文本的
/remindMe
命令,请将说明设置为类似Remind me to do [something] at [time]
的内容。
在 Google Chat API 中配置斜杠命令
如需创建斜杠命令,您需要在 Chat 应用的 Google Chat API 配置中指定有关该命令的信息。
如需在 Google Chat API 中配置斜杠命令,请完成以下步骤:
在 Google Cloud 控制台中,点击“菜单”图标 > API 和服务 > 已启用的 API 和服务 > Google Chat API
点击配置。
在斜杠命令下,点击添加斜杠命令。
为命令输入名称、命令 ID 和说明:
- 名称:命令的显示名称以及用户输入的内容以调用您的应用。名称必须以斜杠开头,只能包含文本,并且最多可以包含 50 个字符。
- 说明:说明如何使用命令以及设置命令格式的文本。广告内容描述最多可包含 50 个字符。
- 命令 ID:您的 Chat 应用用于识别斜杠命令并返回响应的数字(介于 1 到 1000 之间)。
可选:如果您希望 Chat 应用通过对话框响应命令,请选中 Open a dialog 复选框。
点击保存。
现已为 Chat 应用配置了斜杠命令。
响应斜杠命令
当用户创建包含斜杠命令的 Chat 消息时,您的 Chat 应用会收到 MESSAGE
互动事件。事件载荷包含斜杠命令的相关信息,其中包括 slashCommand
和 slashCommandMetadata
字段。您可以使用这些字段来识别命令 ID 并返回自定义响应。
以下示例展示了包含斜杠命令 /vote
的 MESSAGE
互动事件的 JSON 载荷:
{
...
"message": {
...
"text": "/vote yes",
"argumentText": " yes",
"slashCommand": {
"commandId": 2
},
"annotations": [
{
"length": 5,
"startIndex": 0,
"type": "SLASH_COMMAND",
"slashCommand": {
"commandName":"/vote",
"commandId":1,
"type": "INVOKE",
"bot": {
"avatarUrl": "https://www.example.com/images/vote-app-icon.png",
"displayName": "Voter Chat App",
"name": "users/1234567890987654321",
"type": "BOT"
}
}
}
]
}
}
如需响应斜杠命令,您可以检测事件载荷中是否存在 slashCommand
字段,如果有,则向命令返回响应。以下代码示例展示了如何响应包含斜杠命令的 MESSAGE
互动事件:
Node.js
/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} function in response to a slash command.
*/
exports.onMessage = function onMessage(req, res) {
// Stores the Google Chat event as a variable.
var event = req.body;
// Checks for the presence of event.message.slashCommand.
if (event.message.slashCommand) {
switch (event.message.slashCommand.commandId) {
case ID: // The ID for your slash command
res.runFunction; // The response to the slash command.
}
}
Apps 脚本
/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} function in response to a slash command.
*/
function onMessage(event) {
// Checks for the presence of event.message.slashCommand
if (event.message.slashCommand) {
switch (event.message.slashCommand.commandId) {
case ID: // The ID for your slash command
return runFunction; // The response to the slash command.
}
}
}
Python
from typing import Any, Mapping
import flask
import functions_framework
@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
"""Responds to a MESSAGE event in Google Chat that includes a slash command.
Args:
req (flask.Request): the event object from Chat API.
Returns:
Mapping[str, Any]: function in response to a slash command.
"""
if req.method == 'GET':
return 'Sorry, this function must be called from a Google Chat.'
request = req.get_json(silent=True)
if slash_command := request.get('message', dict()).get('slashCommand'):
command_id = slash_command['commandId']
if command_id == ID:
return runFunction
如需使用代码,请替换以下内容:
ID
:您在在 Google Chat API 中配置斜杠命令时指定的命令 ID。runFunction
:一个函数,用于创建对斜杠命令的响应。
完整示例:使用 Rolodex Chat 应用设置联系人
以下示例展示了会响应以下斜杠命令的 Chat 应用:
/help
命令会返回一条文本消息,说明如何获取 Chat 应用的支持。命令 ID 设置为1
。/createContact
命令会打开一个对话框,用户可以在其中输入联系人的详细信息。命令 ID 设置为2
。
在运行此示例之前,请按照在 Google Chat API 中配置斜杠命令中的步骤操作。
Node.js
/**
* Responds to messages that have links whose URLs
* match URL patterns configured for link previews.
*
* @param {Object} event The event object from Chat
* API.
*
* @return {Object} Response from the Chat app
* attached to the message with the previewed link.
*/
exports.onMessage = function onMessage(req, res) {
// Store the Google Chat event as a variable.
const event = req.body;
if (req.method === "GET" || !event.message) {
res.send("Hello! This function is meant to be used in a Google Chat " +
"Space.");
}
// Checks for the presence of event.message.slashCommand.
// If the slash command is "/help", responds with a text message.
// If the slash command is "/createContact", opens a dialog.
if (event.message.slashCommand) {
switch (event.message.slashCommand.commandId) {
case 1: // /help
res.json({"text": "Contact bot helps you update your address book!"});
case 2: // /createContact
res.openDialog(event);
}
}
// If the Chat app doesn"t detect a slash command, it responds
// with a card that prompts the user to add a contact
else {
res.json({
"cardsV2": [{
"cardId": "addContact",
"card": {
"header": {
"title": "Rolodex",
"subtitle": "Manage your contacts!",
"imageUrl": "https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png",
"imageType": "CIRCLE"
},
"sections": [
{
"widgets": [
{
"buttonList": {
"buttons": [
{
"text": "Add Contact",
"onClick": {
"action": {
"function": "openDialog",
"interaction": "OPEN_DIALOG"
}
}
}
]
}
}
]
}
]
}
}]
});
}
// Respond to button clicks on attached cards
if (event.type === "CARD_CLICKED") {
if (event.common.invokedFunction === "openDialog") {
res.openDialog(event);
}
if (event.common.invokedFunction === "openSequentialDialog") {
res.openSequentialDialog(event);
}
if (event.common.invokedFunction === "confirmDialogSuccess") {
res.confirmDialogSuccess(event);
}
}
};
/**
* Opens and starts a dialog that lets users add details about a contact.
*
* @param {object} event the event object from Google Chat.
*
* @return {object} open a dialog.
*/
function openDialog(event) {
res.json({
"action_response": {
"type": "DIALOG",
"dialog_action": {
"dialog": {
"body": {
"sections": [
{
"header": "Add new contact",
"widgets": [
{
"textInput": {
"label": "Name",
"type": "SINGLE_LINE",
"name": "name"
}
},
{
"textInput": {
"label": "Address",
"type": "MULTIPLE_LINE",
"name": "address"
}
},
{
"decoratedText": {
"text": "Add to favorites",
"switchControl": {
"controlType": "SWITCH",
"name": "saveFavorite"
}
}
},
{
"decoratedText": {
"text": "Merge with existing contacts",
"switchControl": {
"controlType": "SWITCH",
"name": "mergeContact",
"selected": true
}
}
},
{
"buttonList": {
"buttons": [
{
"text": "Next",
"onClick": {
"action": {
"function": "openSequentialDialog"
}
}
}
]
}
}
]
}
]
}
}
}
}
});
};
/**
* Opens a second dialog that lets users add more contact details.
*
* @param {object} event the event object from Google Chat.
*
* @return {object} open a dialog.
*/
function openSequentialDialog(event) {
res.json({
"action_response": {
"type": "DIALOG",
"dialog_action": {
"dialog": {
"body": {
"sections": [
{
"header": "Add new contact",
"widgets": [
{
"textInput": {
"label": "Notes",
"type": "MULTIPLE_LINE",
"name": "notes"
}
},
{
"selectionInput": {
"type": "RADIO_BUTTON",
"label": "Contact type",
"name": "contactType",
"items": [
{
"text": "Work",
"value": "Work",
"selected": false
},
{
"text": "Personal",
"value": "Personal",
"selected": false
}
]
}
},
{
"buttonList": {
"buttons": [
{
"text": "Submit",
"onClick": {
"action": {
"function": "confirmDialogSuccess",
"parameters": [
{
"key": "confirmDialogSuccess",
"value": "confirmDialogSuccess"
}
]
}
}
}
]
},
"horizontalAlignment": "END"
}
]
}
]
}
}
}
}
});
}
/**
* Checks for a form input error, the absence of
* a "name" value, and returns an error if absent.
* Otherwise, confirms successful receipt of a dialog.
*
* Confirms successful receipt of a dialog.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} open a Dialog in Google Chat.
*/
function receiveDialog(event) {
// Checks to make sure the user entered a name
// in a dialog. If no name value detected, returns
// an error message.
if (event.common.formInputs.contactName.stringInputs.value[0] === "") {
return {
"actionResponse": {
"type": "DIALOG",
"dialogAction": {
"actionStatus": {
"statusCode": "OK",
"userFacingMessage": "Don't forget to name your new contact!"
}
}
}
};
// Otherwise the app indicates that it received
// form data from the dialog. Any value other than "OK"
// gets returned as an error. "OK" is interpreted as
// code 200, and the dialog closes.
} else {
res.json({
"actionResponse": {
"type": "DIALOG",
"dialogAction": {
"actionStatus": "OK"
}
}
});
}
}
Apps 脚本
Python
from typing import Any, Mapping
import flask
import functions_framework
@functions_framework.http
def main(req: flask.Request) -> Mapping[str, Any]:
"""Responds to a MESSAGE event in Google Chat that includes the /createContact
slash command by opening a dialog.
Args:
req (flask.Request): the event object from Chat API.
Returns:
Mapping[str, Any]: open a Dialog in response to a card's button click.
"""
if req.method == 'GET':
return 'Sorry, this function must be called from a Google Chat.'
request = req.get_json(silent=True)
if request.get('type') == 'CARD_CLICKED':
invoked_function = request.get('common', dict()).get('invokedFunction')
if invoked_function == 'open_dialog':
return open_dialog(request)
elif invoked_function == 'open_sequential_dialog':
return open_dialog(request)
elif invoked_function == "receive_dialog":
return receive_dialog(request)
else:
return {
'cardsV2': [{
'cardId': 'addContact',
'card': {
'header': {
'title': 'Rolodex',
'subtitle': 'Manage your contacts!',
'imageUrl': 'https://www.gstatic.com/images/branding/product/2x/contacts_48dp.png',
'imageType': 'CIRCLE'
},
'sections': [
{
'widgets': [
{
'buttonList': {
'buttons': [
{
'text': 'Add Contact',
'onClick': {
'action': {
'function': 'open_dialog',
'interaction': 'OPEN_DIALOG'
}
}
}
]
}
}
]
}
]
}
}]
}
def open_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
"""Opens a dialog in Google Chat.
Args:
request (Mapping[str, Any]): the event object from Chat API.
Returns:
Mapping[str, Any]: open a Dialog in response to a card's button click.
"""
return {
'action_response': {
'type': 'DIALOG',
'dialog_action': {
'dialog': {
'body': {
'sections': [
{
'header': 'Add new contact',
'widgets': [
{
'textInput': {
'label': 'Name',
'type': 'SINGLE_LINE',
'name': 'name'
}
},
{
'textInput': {
'label': 'Address',
'type': 'MULTIPLE_LINE',
'name': 'address'
}
},
{
'decoratedText': {
'text': 'Add to favorites',
'switchControl': {
'controlType': 'SWITCH',
'name': 'saveFavorite'
}
}
},
{
'decoratedText': {
'text': 'Merge with existing contacts',
'switchControl': {
'controlType': 'SWITCH',
'name': 'mergeContact',
'selected': True
}
}
},
{
'buttonList': {
'buttons': [
{
'text': 'Next',
'onClick': {
'action': {
'function': 'open_sequential_dialog'
}
}
}
]
}
}
]
}
]
}
}
}
}
}
def open_sequential_dialog(request: Mapping[str, Any]) -> Mapping[str, Any]:
"""Opens a second dialog that lets users add more contact details.
Args:
request (Mapping[str, Any]): the event object from Chat API.
Returns:
Mapping[str, Any]: open a Dialog in response to a card's button click.
"""
return {
'action_response': {
'type': 'DIALOG',
'dialog_action': {
'dialog': {
'body': {
'sections': [
{
'header': 'Add new contact',
'widgets': [
{
'textInput': {
'label': 'Notes',
'type': 'MULTIPLE_LINE',
'name': 'notes'
}
},
{
'selectionInput': {
'type': 'RADIO_BUTTON',
'label': 'Contact type',
'name': 'contactType',
'items': [
{
'text': 'Work',
'value': 'Work',
'selected': False
},
{
'text': 'Personal',
'value': 'Personal',
'selected': False
}
]
}
},
{
'buttonList': {
'buttons': [
{
'text': 'Submit',
'onClick': {
'action': {
'function': 'receive_dialog',
'parameters': [
{
'key': 'receiveDialog',
'value': 'receiveDialog'
}
]
}
}
}
]
},
'horizontalAlignment': 'END'
}
]
}
]
}
}
}
}
}
def receive_dialog(event: Mapping[str, Any]) -> Mapping[str, Any]:
"""Checks for a form input error, the absence of a "name" value, and returns
an error if absent. Otherwise, confirms successful receipt of a dialog.
Args:
event (Mapping[str, Any]): the event object from Chat API.
Returns:
Mapping[str, Any]: the response.
"""
if event.get('common', dict()) \
.get('formInputs', dict()).get('contactName', dict()) \
.get('stringInputs').get('value', list()):
return {
'actionResponse': {
'type': 'DIALOG',
'dialogAction': {
'actionStatus': 'OK'
}
}
}
else:
return {
'actionResponse': {
'type': 'DIALOG',
'dialogAction': {
'actionStatus': "Don't forget to name your new contact!"
}
}
}