Auf dieser Seite wird erläutert, wie Sie Slash-Befehle für Ihre Google Chat-App einrichten.
Ein Slash-Befehl ist eine gängige Methode, mit der Nutzer eine Chat-App aufrufen und mit ihr interagieren. Mit Slash-Befehlen können Nutzer außerdem wichtige Funktionen einer Chat-App entdecken und verwenden.
Um einen Slash-Befehl zu verwenden, geben Nutzer einen Schrägstrich (/
) und dann einen kurzen Textbefehl ein, z. B. /about
, um Informationen zur Chat-App zu erhalten. Die verfügbaren Slash-Befehle können Nutzer finden, indem sie in Google Chat einen Schrägstrich eingeben. Daraufhin wird ein Fenster mit den verfügbaren Befehlen für die Chat-App angezeigt:

In den Designprinzipien für Google Chat erfahren Sie, wie Sie Slash-Befehle einrichten und Nutzerinteraktionen entwerfen.
Voraussetzungen
Node.js
- Ein Google Workspace-Konto mit Zugriff auf Google Chat.
- Eine Chat-App. Folgen Sie dieser quickstart, um eine Chat-App zu erstellen.
Apps Script
- Ein Google Workspace-Konto mit Zugriff auf Google Chat.
- Eine Chat-App. Folgen Sie dieser quickstart, um eine Chat-App zu erstellen.
Python
- Ein Google Workspace-Konto mit Zugriff auf Google Chat.
- Eine Chat-App. Folgen Sie dieser quickstart, um eine Chat-App zu erstellen.
Slash-Befehl einrichten
So richten Sie einen Slash-Befehl ein:
- Geben Sie einen Namen für den Slash-Befehl ein.
- Konfigurieren Sie den Slash-Befehl in der Google Chat API.
- Erstellen Sie eine Antwort für den Slash-Befehl, z. B. einen Text oder eine Kartennachricht.
In diesem Abschnitt werden die Schritte zum Einrichten eines Slash-Befehls erläutert.
Slash-Befehl benennen
Der Name eines Slash-Befehls wird vom Nutzer in eine Chat-Nachricht eingegeben, um die Chat-Anwendung aufzurufen. Unter dem Namen wird außerdem eine kurze Beschreibung angezeigt, die Nutzer zur Verwendung des Befehls auffordert:

Beachten Sie bei der Auswahl eines Namens und einer Beschreibung für den Slash-Befehl die folgenden Empfehlungen:
So benennen Sie den Slash-Befehl:
- Verwenden Sie kurze, beschreibende und umsetzbare Wörter oder Wortgruppen, um die Befehle für den Nutzer klar und einfach zu gestalten. Verwenden Sie beispielsweise anstelle von
/createAReminder
/remindMe
. - Wenn Ihr Befehl mehr als ein Wort enthält, helfen Sie den Nutzern, den Befehl zu lesen, indem Sie für das erste Wort nur Kleinbuchstaben und dann den ersten Buchstaben von weiteren Wörtern in Großbuchstaben schreiben. Verwenden Sie beispielsweise
/updateContact
anstelle von/updatecontact
. - Überlegen Sie, ob Sie für den Befehl einen eindeutigen oder allgemeinen Namen verwenden möchten. Wenn der Befehl eine typische Interaktion oder Funktion beschreibt, können Sie einen gängigen Namen verwenden, den die Nutzer kennen und erwarten, z. B.
/settings
oder/feedback
. Versuchen Sie andernfalls, eindeutige Befehlsnamen zu verwenden. Wenn Ihr Befehlsname für andere Chat-Anwendungen identisch ist, muss der Nutzer nach ähnlichen Befehlen filtern, um Ihren zu finden und zu verwenden.
- Verwenden Sie kurze, beschreibende und umsetzbare Wörter oder Wortgruppen, um die Befehle für den Nutzer klar und einfach zu gestalten. Verwenden Sie beispielsweise anstelle von
So beschreiben Sie Ihren Slash-Befehl:
- Halten Sie die Beschreibung kurz und klar, damit Nutzer wissen, was sie beim Aufrufen des Befehls erwarten können.
- Teilen Sie Nutzern mit, ob für den Befehl Formatierungsanforderungen bestehen.
Wenn Sie beispielsweise einen
/remindMe
-Befehl erstellen, für den Argumenttext erforderlich ist, geben Sie für die Beschreibung etwaRemind me to do [something] at [time]
an.
Slash-Befehl in der Google Chat API konfigurieren
Zum Erstellen eines Slash-Befehls müssen Sie Informationen zu dem Befehl in der Konfiguration Ihrer Chat-App für die Google Chat API angeben.
Führen Sie die folgenden Schritte aus, um einen Slash-Befehl in der Google Chat API zu konfigurieren:
Klicken Sie in der Google Cloud Console auf das Dreistrich-Menü > APIs und Dienste > Aktivierte APIs und Dienste > Google Chat API
Klicken Sie auf Konfiguration.
Klicken Sie unter Slash-Befehle auf Slash-Befehl hinzufügen.
Geben Sie einen Namen, eine Befehls-ID und eine Beschreibung für den Befehl ein:
- Name:Der Anzeigename für den Befehl und die Eingabe, die Nutzer zum Aufrufen der Anwendung eingeben. Muss mit einem Schrägstrich beginnen, darf nur Text enthalten und kann bis zu 50 Zeichen umfassen.
- Description: Text zur Verwendung und Formatierung des Befehls. Beschreibungen dürfen maximal 50 Zeichen lang sein.
- Befehls-ID:Eine Zahl zwischen 1 und 1.000, mit der die Chat-App den Slash-Befehl erkennt und eine Antwort zurückgibt.
Optional: Wenn die Chat-App mit einem Dialogfeld auf den Befehl reagieren soll, klicken Sie das Kästchen Dialogfeld öffnen an.
Klicken Sie auf Speichern.
Der Slash-Befehl ist jetzt für die Chat-App konfiguriert.
Auf einen Slash-Befehl reagieren
Wenn Nutzer eine Chatnachricht erstellen, die einen Slash-Befehl enthält, empfängt Ihre Chat-App ein MESSAGE
-Interaktionsereignis.
Die Ereignisnutzlast enthält Informationen zum Slash-Befehl, einschließlich der Felder slashCommand
und slashCommandMetadata
. Sie verwenden diese Felder, um die Befehls-ID zu ermitteln und eine benutzerdefinierte Antwort zurückzugeben.
Das folgende Beispiel zeigt die JSON-Nutzlast für ein MESSAGE
-Interaktionsereignis, das den Slash-Befehl /vote
enthält:
{
...
"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"
}
}
}
]
}
}
Wenn Sie auf einen Slash-Befehl reagieren möchten, können Sie prüfen, ob das Feld slashCommand
in der Ereignisnutzlast vorhanden ist. Wenn ja, wird eine Antwort auf den Befehl zurückgegeben.
Das folgende Codebeispiel zeigt, wie auf ein MESSAGE
-Interaktionsereignis reagiert wird, das einen Slash-Befehl enthält:
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 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
Ersetzen Sie Folgendes, um den Code zu verwenden:
ID
: die Befehls-ID, die Sie bei der Konfiguration des Slash-Befehls in der Google Chat API angeben.runFunction
: eine Funktion, die eine Antwort auf den Slash-Befehl erstellt.
Vollständiges Beispiel: Kontakte mit der Rolodex Chat App einrichten
Das folgende Beispiel zeigt eine Chat-Anwendung, die auf die folgenden Slash-Befehle reagiert:
- Der Befehl
/help
gibt eine Textnachricht zurück, in der erläutert wird, wie Sie Unterstützung für die Chat-App erhalten. Die Befehls-ID ist auf1
festgelegt. - Mit dem Befehl
/createContact
wird ein Dialogfeld geöffnet, in dem Nutzer Details zu einem Kontakt eingeben können. Die Befehls-ID ist auf2
festgelegt.
Bevor Sie dieses Beispiel ausführen, müssen Sie die Slash-Befehle in der Google Chat API konfigurieren.
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 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!"
}
}
}