Questa pagina spiega come impostare e rispondere ai comandi slash per App Google Chat.
Un comando slash è un modo comune che gli utenti richiamano e interagiscono con un App Chat. I comandi slash aiutano inoltre gli utenti a scoprire utilizzare le funzionalità principali di un'app di Chat.
Per utilizzare un comando slash, gli utenti digitano una barra (/
) e poi un breve comando di testo.
come /about
per ottenere informazioni sull'app Chat.
Gli utenti possono scoprire i comandi slash disponibili digitando una barra
Google Chat, che visualizza una finestra in cui sono elencati i comandi disponibili per
App Chat:
Quando un utente invia un messaggio che contiene un comando slash, il messaggio visibile all'utente e all'app Chat.
Per decidere se impostare i comandi slash e capire come progettare le interazioni degli utenti, consulta Definire tutti i percorsi dell'utente.
Prerequisiti
Node.js
Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.
Apps Script
Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un app di Chat interattiva in Apps Script, completa questa guida rapida.
Python
Un'app di Google Chat abilitata per le funzionalità interattive. Per creare un un'app di chat interattiva utilizzando un servizio HTTP, completa questa guida rapida.
Configura un comando slash
Questa sezione spiega come completare i seguenti passaggi per impostare una barra :
- Assegna un nome al comando slash.
- Configura il comando slash nell'API Google Chat.
Assegna un nome al comando slash
Il nome di un comando slash è quello che gli utenti digitano in un messaggio di Chat per richiamare l'app Chat. Anche una breve descrizione sotto il nome, per chiedere agli utenti ulteriori informazioni su come utilizzare il comando:
Quando scegli un nome e una descrizione per il comando slash, considera l'utilizzo seguenti consigli:
Per assegnare un nome al comando slash:
- Usa parole o frasi brevi, descrittive e utili per rendere il
comandi chiari e semplici per l'utente. Ad esempio, invece di dire
/createAReminder
, usa/remindMe
. - Se il tuo comando contiene più di una parola, aiuta gli utenti a leggerlo
utilizzando solo lettere minuscole per la prima parola e poi la prima parola in maiuscolo
lettera di parole aggiuntive. Ad esempio, invece di
/updatecontact
, utilizza/updateContact
. - Valuta se utilizzare un nome univoco o comune per il comando. Se
il comando descrive una caratteristica o un'interazione tipica, puoi utilizzare
nome comune che gli utenti riconoscono e si aspettano, ad esempio
/settings
o/feedback
. Altrimenti, prova a usare nomi di comandi univoci, perché se nome comando è lo stesso di altre app di Chat, l'utente deve filtrando comandi simili per trovare e usare i tuoi.
- Usa parole o frasi brevi, descrittive e utili per rendere il
comandi chiari e semplici per l'utente. Ad esempio, invece di dire
Per descrivere il comando slash:
- La descrizione deve essere breve e chiara in modo che gli utenti sappiano cosa aspettarsi quando richiamano il comando.
- Comunica agli utenti se sono previsti requisiti di formattazione per il comando.
Ad esempio, se crei un comando
/remindMe
che richiede un argomento di testo, imposta la descrizione ad esempioRemind me to do [something] at [time]
. - Fai sapere agli utenti se l'app Chat risponde
tutti nello spazio o privatamente all'utente che richiama il comando.
Ad esempio, per il comando slash
/about
, puoi descrivere questo comando comeLearn about this app (Only visible to you)
. Per rispondere in privato a una slash, consulta la sezione Rispondere con un messaggio privato.
Configura il tuo comando slash nell'API Google Chat
Per creare un comando slash, devi specificare le relative informazioni in la configurazione dell'app Chat per l'API Google Chat.
Per configurare un comando slash nell'API Google Chat, completa quanto segue passaggi:
Nella console Google Cloud, fai clic su Menu > API e Servizi > API abilitate e Servizi > API Google Chat
Fai clic su Configurazione.
In Comandi Slash, fai clic su Aggiungi un comando con barra.
Inserisci un nome, un ID comando e una descrizione per il comando:
- Nome: il nome visualizzato del comando e il testo digitato dagli utenti per richiamare la tua app. Deve iniziare con una barra, contenere solo testo e può contenere fino a 50 caratteri.
- Descrizione: il testo che descrive come utilizzare e formattare il comando. Le descrizioni possono contenere fino a 50 caratteri.
- ID comando: un numero compreso tra 1 e 1000 che il tuo L'app di chat utilizza per riconoscere il comando slash e restituire una risposta.
(Facoltativo) Se vuoi che l'app Chat risponda a sul comando con una finestra di dialogo, seleziona Casella di controllo Apri una finestra di dialogo.
Fai clic su Salva.
Il comando slash è ora configurato per l'app Chat.
Rispondi a un comando slash
Quando gli utenti creano un messaggio di Chat contenente un comando slash,
l'app Chat riceve un evento di interazione MESSAGE
.
Il payload dell'evento contiene informazioni sul comando slash,
incluso slashCommand
e slashCommandMetadata
campi. Questi campi consentono di identificare l'ID comando e restituire una
risposta.
L'esempio seguente mostra il payload JSON per un evento di interazione MESSAGE
che include il comando slash /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"
}
}
}
]
}
}
Per rispondere a un comando slash, puoi rilevare se il campo slashCommand
è presente nel payload dell'evento e, in questo caso, restituisce una risposta al comando.
Il seguente esempio di codice mostra come rispondere a un evento di interazione MESSAGE
che contiene un comando slash:
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.json(runFunction); // The response to the slash command.
}
}
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
Per utilizzare il codice, sostituisci quanto segue:
ID
: l'ID comando che specifichi quando configurare il comando slash nell'API Google Chat.runFunction
: una funzione che crea una risposta a il comando slash.
(Facoltativo) Rispondi con un messaggio privato
I messaggi che contengono comandi slash sono visibili solo all'utente che ha inviato e l'app Chat che riceve il comando. Se hai configurato l'aggiunta dell'app di Chat agli spazi con più persone, potresti rispondere al comando slash privatamente, per mantenere privata l'interazione tra l'utente e App Chat.
Ad esempio, se un team utilizza un'app di Chat che gestisce
servizio di assistenza clienti, gli utenti potrebbero richiamare un comando slash come
/myCases
per visualizzare le richieste di assistenza assegnate. Se il team aggiunge
di Chat a uno spazio, un utente che usa questo comando slash
nello spazio potrebbero volere che l'app Chat risponda solo alle
che li rappresentano. Per evitare di pubblicare le richieste di assistenza dell'utente per tutti nello spazio,
L'app Chat può rispondere in privato.
Per rispondere privatamente a un comando slash, consulta Inviare messaggi privati agli utenti di Google Chat.
Esempio completo: configurare i contatti utilizzando l'app Rolodex Chat
L'esempio seguente mostra un'app di Chat che risponde i seguenti comandi slash:
- Il comando
/help
restituisce un messaggio che spiega come ottenere assistenza con l'app Chat. L'ID comando è impostato a1
. - Il comando
/createContact
apre una finestra di dialogo in cui gli utenti possono inserire i dettagli di un contatto. L'ID comando è impostato su2
.
Prima di eseguire questo esempio, segui i passaggi per configurare i comandi slash nell'API Google Chat.
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.json(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.json(openDialog(event));
}
if (event.common.invokedFunction === "openSequentialDialog") {
res.json(openSequentialDialog(event));
}
if (event.common.invokedFunction === "confirmDialogSuccess") {
res.json(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) {
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": "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": "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 {
return {
"actionResponse": {
"type": "DIALOG",
"dialogAction": {
"actionStatus": "OK"
}
}
};
}
}
Apps Script
Questo esempio invia un messaggio di una scheda restituendo JSON card. Puoi utilizzare anche Servizio di schede Apps Script.
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!"
}
}
}