Interaktive Dialogfelder unterstützen

Auf dieser Seite wird beschrieben, wie Ihre Chat-App Dialogfelder öffnen kann, um auf Nutzer zu reagieren.

Dialogfelder sind fensterbasierte, kartenbasierte Oberflächen, die über einen Chatbereich oder eine Nachricht geöffnet werden. Das Dialogfeld und sein Inhalt sind nur für den Nutzer sichtbar, der es geöffnet hat.

Chat-Apps können Dialogfelder verwenden, um Informationen von Chat-Nutzern anzufordern und zu erfassen, einschließlich mehrstufiger Formulare. Weitere Informationen zum Erstellen von Formulareingaben finden Sie unter Informationen von Nutzern erfassen und verarbeiten.

Vorbereitung

Node.js

Eine Google Chat-App, die Interaktionsereignisse empfängt und darauf reagiert. Wenn Sie eine interaktive Chat-App mit einem HTTP-Dienst erstellen möchten, folgen Sie dieser Kurzanleitung.

Python

Eine Google Chat-App, die Interaktionsereignisse empfängt und darauf reagiert. Wenn Sie eine interaktive Chat-App mit einem HTTP-Dienst erstellen möchten, folgen Sie dieser Kurzanleitung.

Java

Eine Google Chat-App, die Interaktionsereignisse empfängt und darauf reagiert. Wenn Sie eine interaktive Chat-App mit einem HTTP-Dienst erstellen möchten, folgen Sie dieser Kurzanleitung.

Apps Script

Eine Google Chat-App, die Interaktionsereignisse empfängt und darauf reagiert. Wenn Sie eine interaktive Chat-App in Apps Script erstellen möchten, folgen Sie dieser Kurzanleitung.

Dialogfeld öffnen

Ein Dialogfeld mit verschiedenen Widgets.
Abbildung 1: Eine Beispiel-Chat-App, die ein Dialogfeld zum Erfassen von Kontaktinformationen öffnet.

In diesem Abschnitt wird beschrieben, wie Sie antworten und einen Dialog einrichten, indem Sie Folgendes tun:

  1. Dialoganfrage durch eine Nutzerinteraktion auslösen
  2. Verarbeite die Anfrage, indem du ein Dialogfeld zurückgibst und öffnest.
  3. Nachdem Nutzer Informationen gesendet haben, verarbeiten Sie die Einreichung, indem Sie entweder das Dialogfeld schließen oder ein anderes Dialogfeld zurückgeben.

Dialoganfrage auslösen

Eine Chat-App kann Dialogfelder nur als Reaktion auf eine Nutzerinteraktion öffnen, z. B. auf einen Befehl oder einen Klick auf eine Schaltfläche in einer Nachricht auf einer Karte.

Damit eine Chat-App mit einem Dialog auf Nutzer reagieren kann, muss sie eine Interaktion erstellen, die die Dialoganfrage auslöst, z. B.:

  • Auf einen Befehl reagieren Wenn Sie die Anfrage über einen Befehl auslösen möchten, müssen Sie beim Konfigurieren des Befehls das Kästchen Öffnet ein Dialogfeld aktivieren.
  • Auf einen Schaltflächenklick in einer Nachricht reagieren, entweder als Teil einer Karte oder unten in der Nachricht. Wenn Sie die Anfrage über eine Schaltfläche in einer Nachricht auslösen möchten, konfigurieren Sie die onClick-Aktion der Schaltfläche, indem Sie deren interaction auf OPEN_DIALOG festlegen.
  • Auf einen Schaltflächenklick auf der Startseite einer Chat-App reagieren Informationen zum Öffnen von Dialogfeldern über Startseiten finden Sie unter Startseite für Ihre Google Chat App erstellen.
Schaltfläche, die ein Dialogfeld auslöst
Abbildung 2: Eine Chat-App sendet eine Nachricht, in der Nutzer aufgefordert werden, den Slash-Befehl /addContact zu verwenden.
Die Nachricht enthält auch eine Schaltfläche, auf die Nutzer klicken können, um den Befehl auszulösen.

Das folgende Codebeispiel zeigt, wie eine Dialoganfrage über eine Schaltfläche in einer Kartenmitteilung ausgelöst wird. Damit das Dialogfeld geöffnet wird, muss das Feld button.interaction auf OPEN_DIALOG festgelegt sein:

Node.js

node/contact-form-app/index.js
buttonList: { buttons: [{
  text: "Add Contact",
  onClick: { action: {
    function: "openInitialDialog",
    interaction: "OPEN_DIALOG"
  }}
}]}

Python

python/contact-form-app/main.py
'buttonList': { 'buttons': [{
  'text': "Add Contact",
  'onClick': { 'action': {
    'function': "openInitialDialog",
    'interaction': "OPEN_DIALOG"
  }}
}]}

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
.setButtonList(new GoogleAppsCardV1ButtonList().setButtons(List.of(new GoogleAppsCardV1Button()
  .setText("Add Contact")
  .setOnClick(new GoogleAppsCardV1OnClick().setAction(new GoogleAppsCardV1Action()
    .setFunction("openInitialDialog")
    .setInteraction("OPEN_DIALOG"))))))));

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
buttonList: { buttons: [{
  text: "Add Contact",
  onClick: { action: {
    function: "openInitialDialog",
    interaction: "OPEN_DIALOG"
  }}
}]}

Erstes Dialogfeld öffnen

Wenn ein Nutzer eine Dialoganfrage auslöst, empfängt Ihre Chat-App ein Interaktionsereignis, das in der Chat API als Typ event dargestellt wird. Wenn durch die Interaktion eine Dialoganfrage ausgelöst wird, wird das Feld dialogEventType des Ereignisses auf REQUEST_DIALOG gesetzt.

Um ein Dialogfeld zu öffnen, kann Ihre Chat-App auf die Anfrage reagieren, indem sie ein actionResponse-Objekt mit type auf DIALOG und Message-Objekt zurückgibt. Um den Inhalt des Dialogfelds anzugeben, fügen Sie die folgenden Objekte ein:

  • Ein actionResponse-Objekt, dessen type auf DIALOG gesetzt ist.
  • Ein dialogAction-Objekt. Das Feld body enthält die Benutzeroberflächenelemente, die auf der Karte angezeigt werden sollen, einschließlich eines oder mehrerer sections-Widgets. Wenn Sie Informationen von Nutzern erfassen möchten, können Sie Formulareingabe-Widgets und ein Schaltflächen-Widget angeben. Weitere Informationen zum Entwerfen von Formulareingaben finden Sie unter Informationen von Nutzern erheben und verarbeiten.

Das folgende Codebeispiel zeigt, wie eine Chat-App eine Antwort zurückgibt, die ein Dialogfeld öffnet:

Node.js

node/contact-form-app/index.js
/**
 * Opens the initial step of the dialog that lets users add contact details.
 *
 * @return {Object} a message with an action response to open a dialog.
 */
function openInitialDialog() {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { dialog: { body: { sections: [{
      header: "Add new contact",
      widgets: CONTACT_FORM_WIDGETS.concat([{
        buttonList: { buttons: [{
          text: "Review and submit",
          onClick: { action: { function: "openConfirmation" }}
        }]}
      }])
    }]}}}
  }};
}

Python

python/contact-form-app/main.py
def open_initial_dialog() -> dict:
  """Opens the initial step of the dialog that lets users add contact details."""
  return { 'actionResponse': {
    'type': "DIALOG",
    'dialogAction': { 'dialog': { 'body': { 'sections': [{
      'header': "Add new contact",
      'widgets': CONTACT_FORM_WIDGETS + [{
        'buttonList': { 'buttons': [{
          'text': "Review and submit",
          'onClick': { 'action': { 'function': "openConfirmation" }}
        }]}
      }]
    }]}}}
  }}

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
// Opens the initial step of the dialog that lets users add contact details.
Message openInitialDialog() {
  return new Message().setActionResponse(new ActionResponse()
    .setType("DIALOG")
    .setDialogAction(new DialogAction().setDialog(new Dialog().setBody(new GoogleAppsCardV1Card()
      .setSections(List.of(new GoogleAppsCardV1Section()
        .setHeader("Add new contact")
        .setWidgets(Stream.concat(
          CONTACT_FORM_WIDGETS.stream(),
          List.of(new GoogleAppsCardV1Widget()
            .setButtonList(new GoogleAppsCardV1ButtonList().setButtons(List.of(new GoogleAppsCardV1Button()
            .setText("Review and submit")
            .setOnClick(new GoogleAppsCardV1OnClick().setAction(new GoogleAppsCardV1Action()
              .setFunction("openConfirmation"))))))).stream()).collect(Collectors.toList()))))))));
}

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
/**
 * Opens the initial step of the dialog that lets users add contact details.
 *
 * @return {Object} a message with an action response to open a dialog.
 */
function openInitialDialog() {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { dialog: { body: { sections: [{
      header: "Add new contact",
      widgets: CONTACT_FORM_WIDGETS.concat([{
        buttonList: { buttons: [{
          text: "Review and submit",
          onClick: { action: { function: "openConfirmation" }}
        }]}
      }])
    }]}}}
  }};
}

Dialogfeld-Übermittlung verarbeiten

Wenn Nutzer auf eine Schaltfläche klicken, mit der ein Dialogfeld gesendet wird, empfängt Ihre Chat-App ein CARD_CLICKED-Interaktionsereignis, bei dem dialogEventType gleich SUBMIT_DIALOG ist. Informationen dazu, wie Sie die Informationen im Dialogfeld erfassen und verarbeiten, finden Sie unter Informationen von Chat-Nutzern erfassen und verarbeiten.

Ihre Chat-App muss auf das Interaktionsereignis reagieren, indem sie eine der folgenden Aktionen ausführt:

  • Return another dialog (Gib einen weiteren Dialog zurück), um eine weitere Karte oder ein weiteres Formular zu füllen.
  • Schließen Sie das Dialogfeld, nachdem Sie die vom Nutzer eingereichten Daten überprüft haben, und senden Sie optional eine Bestätigungsnachricht.

Optional: Einen weiteren Dialog zurückgeben

Nachdem Nutzer den ersten Dialog gesendet haben, können Chat-Apps einen oder mehrere zusätzliche Dialoge zurückgeben, damit Nutzer Informationen vor dem Senden überprüfen, mehrstufige Formulare ausfüllen oder Formularinhalte dynamisch einfügen können.

Zum Verarbeiten der von Nutzern eingegebenen Daten verwendet die Chat-App das event.common.formInputs-Objekt. Weitere Informationen zum Abrufen von Werten aus Eingabe-Widgets finden Sie unter Informationen von Nutzern erfassen und verarbeiten.

Wenn Sie Daten erfassen möchten, die Nutzer im ersten Dialogfeld eingeben, müssen Sie der Schaltfläche, mit der das nächste Dialogfeld geöffnet wird, Parameter hinzufügen. Weitere Informationen finden Sie unter Daten auf eine andere Karte übertragen.

In diesem Beispiel öffnet eine Chat-App ein erstes Dialogfeld, das zu einem zweiten Dialogfeld zur Bestätigung vor dem Senden führt:

Node.js

node/contact-form-app/index.js
/**
 * Responds to CARD_CLICKED interaction events in Google Chat.
 *
 * @param {Object} event the CARD_CLICKED interaction event from Google Chat.
 * @return {Object} message responses specific to the dialog handling.
 */
function onCardClick(event) {
  // Initial dialog form page
  if (event.common.invokedFunction === "openInitialDialog") {
    return openInitialDialog();
  // Confirmation dialog form page
  } else if (event.common.invokedFunction === "openConfirmation") {
    return openConfirmation(event);
  // Submission dialog form page
  } else if (event.common.invokedFunction === "submitForm") {
    return submitForm(event);
  }
}

/**
 * Opens the initial step of the dialog that lets users add contact details.
 *
 * @return {Object} a message with an action response to open a dialog.
 */
function openInitialDialog() {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { dialog: { body: { sections: [{
      header: "Add new contact",
      widgets: CONTACT_FORM_WIDGETS.concat([{
        buttonList: { buttons: [{
          text: "Review and submit",
          onClick: { action: { function: "openConfirmation" }}
        }]}
      }])
    }]}}}
  }};
}

/**
 * Returns the second step as a dialog or card message that lets users confirm details.
 *
 * @param {Object} event the interactive event with form inputs.
 * @return {Object} returns a dialog or private card message.
 */
function openConfirmation(event) {
  const name = fetchFormValue(event, "contactName") ?? "";
  const birthdate = fetchFormValue(event, "contactBirthdate") ?? "";
  const type = fetchFormValue(event, "contactType") ?? "";
  const cardConfirmation = {
    header: "Your contact",
    widgets: [{
      textParagraph: { text: "Confirm contact information and submit:" }}, {
      textParagraph: { text: "<b>Name:</b> " + name }}, {
      textParagraph: {
        text: "<b>Birthday:</b> " + convertMillisToDateString(birthdate)
      }}, {
      textParagraph: { text: "<b>Type:</b> " + type }}, {
      buttonList: { buttons: [{
        text: "Submit",
        onClick: { action: {
          function: "submitForm",
          parameters: [{
            key: "contactName", value: name }, {
            key: "contactBirthdate", value: birthdate }, {
            key: "contactType", value: type
          }]
        }}
      }]}
    }]
  };

  // Returns a dialog with contact information that the user input.
  if (event.isDialogEvent) {
    return { action_response: {
      type: "DIALOG",
      dialogAction: { dialog: { body: { sections: [ cardConfirmation ]}}}
    }};
  }

  // Updates existing card message with contact information that the user input.
  return {
    actionResponse: { type: "UPDATE_MESSAGE" },
    privateMessageViewer: event.user,
    cardsV2: [{
      card: { sections: [cardConfirmation]}
    }]
  }
}

Python

python/contact-form-app/main.py
def on_card_click(event: dict) -> dict:
  """Responds to CARD_CLICKED interaction events in Google Chat."""
  # Initial dialog form page
  if "openInitialDialog" == event.get('common').get('invokedFunction'):
    return open_initial_dialog()
  # Confirmation dialog form page
  elif "openConfirmation" == event.get('common').get('invokedFunction'):
    return open_confirmation(event)
  # Submission dialog form page
  elif "submitForm" == event.get('common').get('invokedFunction'):
    return submit_form(event)


def open_initial_dialog() -> dict:
  """Opens the initial step of the dialog that lets users add contact details."""
  return { 'actionResponse': {
    'type': "DIALOG",
    'dialogAction': { 'dialog': { 'body': { 'sections': [{
      'header': "Add new contact",
      'widgets': CONTACT_FORM_WIDGETS + [{
        'buttonList': { 'buttons': [{
          'text': "Review and submit",
          'onClick': { 'action': { 'function': "openConfirmation" }}
        }]}
      }]
    }]}}}
  }}


def open_confirmation(event: dict) -> dict:
  """Returns the second step as a dialog or card message that lets users confirm details."""
  name = fetch_form_value(event, "contactName") or ""
  birthdate = fetch_form_value(event, "contactBirthdate") or ""
  type = fetch_form_value(event, "contactType") or ""
  card_confirmation = {
    'header': "Your contact",
    'widgets': [{
      'textParagraph': { 'text': "Confirm contact information and submit:" }}, {
      'textParagraph': { 'text': "<b>Name:</b> " + name }}, {
      'textParagraph': {
        'text': "<b>Birthday:</b> " + convert_millis_to_date_string(birthdate)
      }}, {
      'textParagraph': { 'text': "<b>Type:</b> " + type }}, {
      'buttonList': { 'buttons': [{
        'text': "Submit",
        'onClick': { 'action': {
          'function': "submitForm",
          'parameters': [{
            'key': "contactName", 'value': name }, {
            'key': "contactBirthdate", 'value': birthdate }, {
            'key': "contactType", 'value': type
          }]
        }}
      }]}
    }]
  }

  # Returns a dialog with contact information that the user input.
  if event.get('isDialogEvent'): 
    return { 'action_response': {
      'type': "DIALOG",
      'dialogAction': { 'dialog': { 'body': { 'sections': [card_confirmation] }}}
    }}

  # Updates existing card message with contact information that the user input.
  return {
    'actionResponse': { 'type': "UPDATE_MESSAGE" },
    'privateMessageViewer': event.get('user'),
    'cardsV2': [{
      'card': { 'sections': [card_confirmation] }
    }]
  }

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
// Responds to CARD_CLICKED interaction events in Google Chat.
Message onCardClick(JsonNode event) {
  String invokedFunction = event.at("/common/invokedFunction").asText();
  // Initial dialog form page
  if ("openInitialDialog".equals(invokedFunction)) {
    return openInitialDialog();
  // Confirmation dialog form page
  } else if ("openConfirmation".equals(invokedFunction)) {
    return openConfirmation(event);
  // Submission dialog form page
  } else if ("submitForm".equals(invokedFunction)) {
    return submitForm(event);
  }
  return null; 
}

// Opens the initial step of the dialog that lets users add contact details.
Message openInitialDialog() {
  return new Message().setActionResponse(new ActionResponse()
    .setType("DIALOG")
    .setDialogAction(new DialogAction().setDialog(new Dialog().setBody(new GoogleAppsCardV1Card()
      .setSections(List.of(new GoogleAppsCardV1Section()
        .setHeader("Add new contact")
        .setWidgets(Stream.concat(
          CONTACT_FORM_WIDGETS.stream(),
          List.of(new GoogleAppsCardV1Widget()
            .setButtonList(new GoogleAppsCardV1ButtonList().setButtons(List.of(new GoogleAppsCardV1Button()
            .setText("Review and submit")
            .setOnClick(new GoogleAppsCardV1OnClick().setAction(new GoogleAppsCardV1Action()
              .setFunction("openConfirmation"))))))).stream()).collect(Collectors.toList()))))))));
}

// Returns the second step as a dialog or card message that lets users confirm details.
Message openConfirmation(JsonNode event) {
  String name = fetchFormValue(event, "contactName") != null ?
    fetchFormValue(event, "contactName") : "";
  String birthdate = fetchFormValue(event, "contactBirthdate") != null ?
    fetchFormValue(event, "contactBirthdate") : "";
  String type = fetchFormValue(event, "contactType") != null ?
    fetchFormValue(event, "contactType") : "";
  GoogleAppsCardV1Section cardConfirmationSection = new GoogleAppsCardV1Section()
    .setHeader("Your contact")
    .setWidgets(List.of(
      new GoogleAppsCardV1Widget().setTextParagraph(new GoogleAppsCardV1TextParagraph()
        .setText("Confirm contact information and submit:")),
      new GoogleAppsCardV1Widget().setTextParagraph(new GoogleAppsCardV1TextParagraph()
        .setText("<b>Name:</b> " + name)),
      new GoogleAppsCardV1Widget().setTextParagraph(new GoogleAppsCardV1TextParagraph()
        .setText("<b>Birthday:</b> " + convertMillisToDateString(birthdate))),
      new GoogleAppsCardV1Widget().setTextParagraph(new GoogleAppsCardV1TextParagraph()
        .setText("<b>Type:</b> " + type)),
      new GoogleAppsCardV1Widget().setButtonList(new GoogleAppsCardV1ButtonList().setButtons(List.of(new GoogleAppsCardV1Button()
        .setText("Submit")
        .setOnClick(new GoogleAppsCardV1OnClick().setAction(new GoogleAppsCardV1Action()
          .setFunction("submitForm")
          .setParameters(List.of(
            new GoogleAppsCardV1ActionParameter().setKey("contactName").setValue(name),
            new GoogleAppsCardV1ActionParameter().setKey("contactBirthdate").setValue(birthdate),
            new GoogleAppsCardV1ActionParameter().setKey("contactType").setValue(type))))))))));

  // Returns a dialog with contact information that the user input.
  if (event.at("/isDialogEvent") != null && event.at("/isDialogEvent").asBoolean()) {
    return new Message().setActionResponse(new ActionResponse()
      .setType("DIALOG")
      .setDialogAction(new DialogAction().setDialog(new Dialog().setBody(new GoogleAppsCardV1Card()
        .setSections(List.of(cardConfirmationSection))))));
  }

  // Updates existing card message with contact information that the user input.
  return new Message()
    .setActionResponse(new ActionResponse()
      .setType("UPDATE_MESSAGE"))
    .setPrivateMessageViewer(new User().setName(event.at("/user/name").asText()))
    .setCardsV2(List.of(new CardWithId().setCard(new GoogleAppsCardV1Card()
      .setSections(List.of(cardConfirmationSection)))));
}

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
/**
 * Responds to CARD_CLICKED interaction events in Google Chat.
 *
 * @param {Object} event the CARD_CLICKED interaction event from Google Chat.
 * @return {Object} message responses specific to the dialog handling.
 */
function onCardClick(event) {
  // Initial dialog form page
  if (event.common.invokedFunction === "openInitialDialog") {
    return openInitialDialog();
  // Confirmation dialog form page
  } else if (event.common.invokedFunction === "openConfirmation") {
    return openConfirmation(event);
  // Submission dialog form page
  } else if (event.common.invokedFunction === "submitForm") {
    return submitForm(event);
  }
}

/**
 * Opens the initial step of the dialog that lets users add contact details.
 *
 * @return {Object} a message with an action response to open a dialog.
 */
function openInitialDialog() {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { dialog: { body: { sections: [{
      header: "Add new contact",
      widgets: CONTACT_FORM_WIDGETS.concat([{
        buttonList: { buttons: [{
          text: "Review and submit",
          onClick: { action: { function: "openConfirmation" }}
        }]}
      }])
    }]}}}
  }};
}

/**
 * Returns the second step as a dialog or card message that lets users confirm details.
 *
 * @param {Object} event the interactive event with form inputs.
 * @return {Object} returns a dialog or private card message.
 */
function openConfirmation(event) {
  const name = fetchFormValue(event, "contactName") ?? "";
  const birthdate = fetchFormValue(event, "contactBirthdate") ?? "";
  const type = fetchFormValue(event, "contactType") ?? "";
  const cardConfirmation = {
    header: "Your contact",
    widgets: [{
      textParagraph: { text: "Confirm contact information and submit:" }}, {
      textParagraph: { text: "<b>Name:</b> " + name }}, {
      textParagraph: {
        text: "<b>Birthday:</b> " + convertMillisToDateString(birthdate)
      }}, {
      textParagraph: { text: "<b>Type:</b> " + type }}, {
      buttonList: { buttons: [{
        text: "Submit",
        onClick: { action: {
          function: "submitForm",
          parameters: [{
            key: "contactName", value: name }, {
            key: "contactBirthdate", value: birthdate }, {
            key: "contactType", value: type
          }]
        }}
      }]}
    }]
  };

  // Returns a dialog with contact information that the user input.
  if (event.isDialogEvent) {
    return { action_response: {
      type: "DIALOG",
      dialogAction: { dialog: { body: { sections: [ cardConfirmation ]}}}
    }};
  }

  // Updates existing card message with contact information that the user input.
  return {
    actionResponse: { type: "UPDATE_MESSAGE" },
    privateMessageViewer: event.user,
    cardsV2: [{
      card: { sections: [cardConfirmation]}
    }]
  }
}

Dialogfeld schließen

Wenn Nutzer auf eine Schaltfläche in einem Dialogfeld klicken, führt Ihre Chat-App die zugehörige Aktion aus und stellt das Ereignisobjekt mit den folgenden Informationen bereit:

Die Chat-App sollte ein ActionResponse-Objekt mit dem auf DIALOG festgelegten type und dem ausgefüllten dialogAction zurückgeben. Wenn die Aktion nicht fehlgeschlagen ist, sollte dialogAction.actionStatus den Wert OK haben, wie im folgenden Beispiel:

Node.js

node/contact-form-app/index.js
// The Chat app indicates that it received form data from the dialog or card.
// Sends private text message that confirms submission.
const confirmationMessage = "✅ " + contactName + " has been added to your contacts.";
if (event.dialogEventType === "SUBMIT_DIALOG") {
  return {
    actionResponse: {
      type: "DIALOG",
      dialogAction: { actionStatus: {
        statusCode: "OK",
        userFacingMessage: "Success " + contactName
      }}
    }
  };
}

Python

python/contact-form-app/main.py
# The Chat app indicates that it received form data from the dialog or card.
# Sends private text message that confirms submission.
confirmation_message = "✅ " + contact_name + " has been added to your contacts.";
if "SUBMIT_DIALOG" == event.get('dialogEventType'):
  return {
    'actionResponse': {
      'type': "DIALOG",
      'dialogAction': { 'actionStatus': {
        'statusCode': "OK",
        'userFacingMessage': "Success " + contact_name
      }}
    }
  }

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
// The Chat app indicates that it received form data from the dialog or card.
// Sends private text message that confirms submission.
String confirmationMessage = "✅ " + contactName + " has been added to your contacts.";
if (event.at("/dialogEventType") != null && "SUBMIT_DIALOG".equals(event.at("/dialogEventType").asText())) {
  return new Message().setActionResponse(new ActionResponse()
    .setType("DIALOG")
    .setDialogAction(new DialogAction().setActionStatus(new ActionStatus()
      .setStatusCode("OK")
      .setUserFacingMessage("Success " + contactName))));
}

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
// The Chat app indicates that it received form data from the dialog or card.
// Sends private text message that confirms submission.
const confirmationMessage = "✅ " + contactName + " has been added to your contacts.";
if (event.dialogEventType === "SUBMIT_DIALOG") {
  return {
    actionResponse: {
      type: "DIALOG",
      dialogAction: { actionStatus: {
        statusCode: "OK",
        userFacingMessage: "Success " + contactName
      }}
    }
  };
}

Optional: Temporäre Benachrichtigung anzeigen

Wenn Sie das Dialogfeld schließen, können Sie dem Nutzer, der mit der App interagiert, auch eine temporäre Textbenachrichtigung anzeigen.

Die Chat-App kann mit einer Erfolgs- oder Fehlermeldung antworten, indem sie ein ActionResponse mit dem gesetzten actionStatus zurückgibt.

Im folgenden Beispiel wird geprüft, ob die Parameter gültig sind. Wenn nicht, wird das Dialogfeld mit einer Textbenachrichtigung geschlossen:

Node.js

node/contact-form-app/index.js
const contactName = event.common.parameters["contactName"];
// Checks to make sure the user entered a contact name.
// If no name value detected, returns an error message.
const errorMessage = "Don't forget to name your new contact!";
if (!contactName && event.dialogEventType === "SUBMIT_DIALOG") {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { actionStatus: {
      statusCode: "INVALID_ARGUMENT",
      userFacingMessage: errorMessage
    }}
  }};
}

Python

python/contact-form-app/main.py
contact_name = event.get('common').get('parameters')["contactName"]
# Checks to make sure the user entered a contact name.
# If no name value detected, returns an error message.
error_message = "Don't forget to name your new contact!"
if contact_name == "" and "SUBMIT_DIALOG" == event.get('dialogEventType'):
  return { 'actionResponse': {
    'type': "DIALOG",
    'dialogAction': { 'actionStatus': {
      'statusCode': "INVALID_ARGUMENT",
      'userFacingMessage': error_message
    }}
  }}

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
String contactName = event.at("/common/parameters/contactName").asText();
// Checks to make sure the user entered a contact name.
// If no name value detected, returns an error message.
String errorMessage = "Don't forget to name your new contact!";
if (contactName.isEmpty() && event.at("/dialogEventType") != null && "SUBMIT_DIALOG".equals(event.at("/dialogEventType").asText())) {
  return new Message().setActionResponse(new ActionResponse()
    .setType("DIALOG")
    .setDialogAction(new DialogAction().setActionStatus(new ActionStatus()
      .setStatusCode("INVALID_ARGUMENT")
      .setUserFacingMessage(errorMessage))));
}

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
const contactName = event.common.parameters["contactName"];
// Checks to make sure the user entered a contact name.
// If no name value detected, returns an error message.
const errorMessage = "Don't forget to name your new contact!";
if (!contactName && event.dialogEventType === "SUBMIT_DIALOG") {
  return { actionResponse: {
    type: "DIALOG",
    dialogAction: { actionStatus: {
      statusCode: "INVALID_ARGUMENT",
      userFacingMessage: errorMessage
    }}
  }};
}

Weitere Informationen zum Übergeben von Parametern zwischen Dialogfeldern finden Sie unter Daten an eine andere Karte übertragen.

Optional: Bestätigungs-Chatnachricht senden

Wenn Sie das Dialogfeld schließen, können Sie auch eine neue Chatnachricht senden oder eine vorhandene Nachricht aktualisieren.

Wenn Sie eine neue Nachricht senden möchten, geben Sie ein ActionResponse-Objekt mit dem auf NEW_MESSAGE festgelegten type zurück. Im folgenden Beispiel wird das Dialogfeld mit einer Bestätigungsnachricht geschlossen:

Node.js

node/contact-form-app/index.js
return {
  actionResponse: { type: "NEW_MESSAGE" },
  privateMessageViewer: event.user,
  text: confirmationMessage
};

Python

python/contact-form-app/main.py
return {
  'actionResponse': { 'type': "NEW_MESSAGE" },
  'privateMessageViewer': event.get('user'),
  'text': confirmation_message
}

Java

java/contact-form-app/src/main/java/com/google/chat/contact/App.java
return new Message()
  .setActionResponse(new ActionResponse().setType("NEW_MESSAGE"))
  .setPrivateMessageViewer(new User().setName(event.at("/user/name").asText()))
  .setText(confirmationMessage);

Apps Script

In diesem Beispiel wird eine Kartenmitteilung gesendet, indem Karten-JSON zurückgegeben wird. Sie können auch den Apps Script-Kartendienst verwenden.

apps-script/contact-form-app/main.gs
return {
  actionResponse: { type: "NEW_MESSAGE" },
  privateMessageViewer: event.user,
  text: confirmationMessage
};

Wenn Sie eine Nachricht aktualisieren möchten, geben Sie ein actionResponse-Objekt zurück, das die aktualisierte Nachricht enthält, und legen Sie type auf einen der folgenden Werte fest:

Fehlerbehebung

Wenn eine Google Chat-App oder Karte einen Fehler zurückgibt, wird in der Chat-Benutzeroberfläche die Meldung „Ein Fehler ist aufgetreten“ angezeigt. oder „Ihre Anfrage kann nicht bearbeitet werden.“ Manchmal wird in der Chat-Benutzeroberfläche keine Fehlermeldung angezeigt, aber die Chat-App oder ‑Karte liefert ein unerwartetes Ergebnis, z. B. wird eine Kartennachricht nicht angezeigt.

Auch wenn in der Chat-Benutzeroberfläche keine Fehlermeldung angezeigt wird, sind aussagekräftige Fehlermeldungen und Protokolldaten verfügbar, die Ihnen helfen, Fehler zu beheben, wenn die Fehlerprotokollierung für Chat-Apps aktiviert ist. Informationen zum Ansehen, Debuggen und Beheben von Fehlern finden Sie unter Google Chat-Fehler beheben.