Na tej stronie dowiesz się, jak skonfigurować polecenia po ukośniku w aplikacji Google Chat.
Polecenie po ukośniku to typowy sposób wywoływania aplikacji do obsługi czatu i interakcji z nią. Polecenia po ukośniku ułatwiają też użytkownikom odkrywanie i używanie najważniejszych funkcji aplikacji do obsługi czatu.
Aby użyć polecenia po ukośniku, użytkownicy wpisują ukośnik (/
) i krótkie polecenie tekstowe, na przykład /about
, aby uzyskać informacje o aplikacji do obsługi czatu. Użytkownicy mogą znaleźć dostępne polecenia po ukośniku, wpisując ukośnik w Google Chat, co wyświetla okno z listą dostępnych poleceń aplikacji Google Chat:

Aby zdecydować, czy należy skonfigurować polecenia po ukośniku i dowiedzieć się, jak projektować interakcje użytkowników, przeczytaj zasady projektowania Google Chat.
Wymagania wstępne
Node.js
- konto Google Workspace z dostępem do Google Chat.
- Aplikacja do obsługi czatu. Aby utworzyć aplikację do obsługi czatu, zapoznaj się z tym krótkim wprowadzeniem.
Google Apps Script
- konto Google Workspace z dostępem do Google Chat.
- Aplikacja do obsługi czatu. Aby utworzyć aplikację do obsługi czatu, zapoznaj się z tym krótkim wprowadzeniem.
Python
- konto Google Workspace z dostępem do Google Chat.
- Aplikacja do obsługi czatu. Aby utworzyć aplikację do obsługi czatu, zapoznaj się z tym krótkim wprowadzeniem.
Konfigurowanie polecenia po ukośniku
Aby skonfigurować polecenie po ukośniku:
- Utwórz nazwę polecenia po ukośniku.
- Skonfiguruj polecenie po ukośniku w interfejsie Google Chat API.
- Utwórz odpowiedź na polecenie po ukośniku, np. tekst lub wiadomość na karcie.
W tej sekcji opisujemy, jak skonfigurować polecenie po ukośniku.
Nazwij polecenie po ukośniku
Nazwa polecenia po ukośniku to tekst, który użytkownicy wpisują w wiadomości w Google Chat, aby wywołać aplikację do obsługi czatu. Pod nazwą znajduje się też krótki opis, który informuje użytkowników, jak użyć tego polecenia:

Wybierając nazwę i opis polecenia po ukośniku, weź pod uwagę te zalecenia:
Aby nazwać polecenie po ukośniku:
- Używaj krótkich, opisowych i praktycznych słów lub wyrażeń, aby polecenia były zrozumiałe i proste dla użytkownika. Na przykład zamiast
/createAReminder
użyj/remindMe
. - Jeśli polecenie zawiera więcej niż 1 słowo, możesz ułatwić użytkownikom jego odczytanie. W tym celu użyj małych liter w pierwszym słowie, a następnie wielkich liter na początku kolejnych słów. Na przykład zamiast
/updatecontact
użyj/updateContact
. - Zastanów się, czy w poleceniu chcesz użyć unikalnej czy wspólnej nazwy. Jeśli polecenie opisuje typową interakcję lub funkcję, możesz użyć popularnej nazwy, która jest rozpoznawalna i oczekiwana przez użytkowników, np.
/settings
lub/feedback
. W przeciwnym razie używaj unikalnych nazw poleceń, ponieważ jeśli nazwa polecenia jest taka sama w innych aplikacjach do obsługi czatu, użytkownik musi użyć podobnych poleceń, aby znaleźć i użyć Twojego.
- Używaj krótkich, opisowych i praktycznych słów lub wyrażeń, aby polecenia były zrozumiałe i proste dla użytkownika. Na przykład zamiast
Aby opisać polecenie po ukośniku:
- Opis powinien być krótki i zrozumiały, aby użytkownicy wiedzieli, czego mogą się spodziewać po wywołaniu polecenia.
- Poinformuj użytkowników, czy są jakieś wymagania dotyczące formatowania polecenia.
Jeśli na przykład utworzysz polecenie
/remindMe
, które wymaga tekstu argumentu, ustaw opis na przykładRemind me to do [something] at [time]
.
Skonfiguruj polecenie po ukośniku w interfejsie Google Chat API
Aby utworzyć polecenie po ukośniku, musisz podać informacje o tym poleceniu w konfiguracji aplikacji do obsługi czatu pod kątem interfejsu Google Chat API.
Aby skonfigurować polecenie po ukośniku w interfejsie Google Chat API, wykonaj te czynności:
W konsoli Google Cloud kliknij Menu > Interfejsy API i usługi > Włączone interfejsy API i usługi > Google Chat API.
Kliknij Konfiguracja.
W sekcji Polecenia po ukośniku kliknij Dodaj polecenie po ukośniku.
Wpisz nazwę, identyfikator i opis polecenia:
- Nazwa: wyświetlana nazwa polecenia oraz to, co użytkownicy wpisują, aby wywołać Twoją aplikację. Musi zaczynać się od ukośnika, zawierać tylko tekst i może mieć maksymalnie 50 znaków.
- Opis: tekst opisujący sposób użycia i formatowania polecenia. Opisy mogą mieć maksymalnie 50 znaków.
- Identyfikator polecenia: liczba od 1 do 1000, której aplikacja do obsługi czatu używa do rozpoznawania polecenia po ukośniku i zwracania odpowiedzi.
Opcjonalnie: jeśli chcesz, aby aplikacja do obsługi czatu reagowała okna na polecenie, zaznacz pole wyboru Otwórz okno.
Kliknij Zapisz.
Polecenie po ukośniku zostało skonfigurowane w przypadku aplikacji do obsługi czatu.
Odpowiedź na polecenie po ukośniku
Gdy użytkownicy utworzą wiadomość w Google Chat zawierającą polecenie po ukośniku, aplikacja do obsługi czatu otrzyma zdarzenie interakcji MESSAGE
.
Ładunek zdarzenia zawiera informacje o poleceniu po ukośniku, w tym pola slashCommand
i slashCommandMetadata
. Za pomocą tych pól możesz zidentyfikować identyfikator polecenia i zwrócić niestandardową odpowiedź.
Ten przykład przedstawia ładunek JSON dla zdarzenia interakcji MESSAGE
zawierającego polecenie po ukośniku /vote
:
{
...
"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"
}
}
}
]
}
}
Aby odpowiedzieć na polecenie po ukośniku, możesz sprawdzić, czy w ładunku zdarzenia występuje pole slashCommand
, a jeśli tak, zwraca odpowiedź na to polecenie.
Poniższy przykładowy kod pokazuje, jak odpowiedzieć na zdarzenie interakcji MESSAGE
zawierające polecenie po ukośniku:
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.
}
}
Google Apps Script
/**
* 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
Aby użyć kodu, zastąp ciąg:
ID
: identyfikator polecenia podawany przez Ciebie podczas konfigurowania polecenia po ukośniku w interfejsie Google Chat API.runFunction
: funkcja tworząca odpowiedź na polecenie po ukośniku.
Pełny przykład: konfigurowanie kontaktów za pomocą aplikacji Rolodex Chat
Poniższy przykład pokazuje aplikację do obsługi czatu, która odpowiada na te polecenia po ukośniku:
- Polecenie
/help
zwraca SMS-a z wyjaśnieniem, jak uzyskać pomoc dotyczącą aplikacji do obsługi czatu. Identyfikator polecenia jest ustawiony na1
. - Polecenie
/createContact
otwiera okno, w którym użytkownicy mogą wpisać szczegóły kontaktu. Identyfikator polecenia jest ustawiony na2
.
Zanim uruchomisz ten przykład, wykonaj instrukcje konfigurowania poleceń po ukośniku w interfejsie 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"
}
}
});
}
}
Google Apps Script
/**
* Responds to a MESSAGE event in Google Chat.
*
* @param {Object} event the event object from Chat API.
*
* @return {object} open a Dialog in response to a slash command
* or a card"s button click.
*/
function onMessage(event) {
// 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
return {"text": "Contact bot helps you update your address book!"}
case 2: // /createContact
return 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 {
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": "openDialog",
"interaction": "OPEN_DIALOG"
}
}
}
]
}
}
]
}
]
}
}]
};
}
}
/**
* Responds to a CARD_CLICKED event in Google Chat.
*
* @param {Object} event the event object from Google Chat
*/
function onCardClick(event) {
if (event.common.invokedFunction === "openDialog") {
return openDialog(event);
}
if (event.common.invokedFunction === "openSequentialDialog") {
return openSequentialDialog(event);
}
if (event.common.invokedFunction === "receiveDialog") {
return receiveDialog(event);
}
}
/**
* Opens and starts a dialog that lets users add details about a contact.
*
*
* @return {object} open a dialog.
*/
function openDialog(event) {
return {
"action_response": {
"type": "DIALOG",
"dialog_action": {
"dialog": {
"body": {
"sections": [
{
"header": "Add new contact",
"widgets": [
{
"textInput": {
"label": "Name",
"type": "SINGLE_LINE",
"name": "contactName"
}
},
{
"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) {
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": "receiveDialog",
"parameters": [
{
"key": "receiveDialog",
"value": "receiveDialog"
}
]
}
}
}
]
},
"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": "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 {
return {
"actionResponse": {
"type": "DIALOG",
"dialogAction": {
"actionStatus": "OK"
}
}
};
}
}
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!"
}
}
}