Etkileşimli iletişim kutularını destekleme

Bu sayfada, Chat uygulamanızın kullanıcılara yanıt vermek için nasıl iletişim kutuları açabileceği açıklanmaktadır.

Diyaloglar, Chat alanından veya mesajından açılan, pencereli ve kart tabanlı arayüzlerdir. İletişim kutusu ve içeriği yalnızca onu açan kullanıcı tarafından görülebilir.

Chat uygulamaları, çok adımlı formlar da dahil olmak üzere Chat kullanıcılarından bilgi istemek ve bilgi toplamak için iletişim kutularını kullanabilir. Form girişleri oluşturma hakkında daha fazla bilgi için Kullanıcılardan bilgi toplama ve bu bilgileri işleme başlıklı makaleyi inceleyin.

Ön koşullar

Node.js

Etkileşim etkinliklerini alan ve bunlara yanıt veren bir Google Chat uygulaması. HTTP hizmeti kullanarak etkileşimli bir Chat uygulaması oluşturmak için bu hızlı başlangıç kılavuzunu tamamlayın.

Python

Etkileşim etkinliklerini alan ve bunlara yanıt veren bir Google Chat uygulaması. HTTP hizmeti kullanarak etkileşimli bir Chat uygulaması oluşturmak için bu hızlı başlangıç kılavuzunu tamamlayın.

Java

Etkileşim etkinliklerini alan ve bunlara yanıt veren bir Google Chat uygulaması. HTTP hizmeti kullanarak etkileşimli bir Chat uygulaması oluşturmak için bu hızlı başlangıç kılavuzunu tamamlayın.

Apps Komut Dosyası

Etkileşim etkinliklerini alan ve bunlara yanıt veren bir Google Chat uygulaması. Apps Komut Dosyası'nda etkileşimli bir Chat uygulaması oluşturmak için bu hızlı başlangıç kılavuzunu tamamlayın.

İletişim kutusu açma

Çeşitli widget'ların yer aldığı bir iletişim kutusu.
Şekil 1: İletişim bilgilerini toplamak için bir iletişim kutusu açan örnek bir Chat uygulaması.

Bu bölümde, aşağıdakileri yaparak nasıl yanıt vereceğiniz ve iletişim kutusu oluşturacağınız açıklanmaktadır:

  1. Kullanıcı etkileşiminden iletişim kutusu isteğini tetikleyin.
  2. Bir iletişim kutusu döndürüp açarak isteği işleyin.
  3. Kullanıcılar bilgi gönderdikten sonra, iletişim kutusunu kapatarak veya başka bir iletişim kutusu döndürerek gönderimi işleyin.

İletişim kutusu isteğini tetikleme

Bir Chat uygulaması, yalnızca kullanıcı etkileşimlerine (ör. komut veya karttaki bir mesajdan düğme tıklama) yanıt vermek için iletişim kutuları açabilir.

Kullanıcılara iletişim kutusuyla yanıt vermek için bir Chat uygulamasının aşağıdaki gibi bir etkileşim oluşturması gerekir:

  • Komutlara yanıt verme İsteği bir komuttan tetiklemek için komutu yapılandırırken İletişim kutusu açar onay kutusunu işaretlemeniz gerekir.
  • Mesajdaki bir düğme tıklamasına yanıt verme: Kartın bir parçası olarak veya mesajın alt kısmında. İsteği bir iletideki düğmeden tetiklemek için düğmenin onClick işlemini, interaction özelliğini OPEN_DIALOG olarak ayarlayarak yapılandırın.
  • Chat uygulaması ana sayfasında düğme tıklamalarına yanıt verme. Ana sayfalardan iletişim kutularını açma hakkında bilgi edinmek için Google Chat uygulamanız için ana sayfa oluşturma başlıklı makaleye bakın.
İletişim kutusunu tetikleyen düğme
Şekil 2: Bir Chat uygulaması, kullanıcılardan /addContact eğik çizgi komutunu kullanmalarını isteyen bir mesaj gönderiyor.
Mesajda, kullanıcıların komutu tetiklemek için tıklayabileceği bir düğme de bulunur.

Aşağıdaki kod örneğinde, bir kart mesajındaki düğmeden nasıl iletişim kutusu isteği tetikleneceği gösterilmektedir. İletişim kutusunu açmak için button.interaction alanı OPEN_DIALOG olarak ayarlanır:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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

İlk iletişim kutusunu açma

Bir kullanıcı iletişim kutusu isteğini tetiklediğinde Chat uygulamanız, Chat API'sinde event türü olarak gösterilen bir etkileşim etkinliği alır. Etkileşim bir iletişim kutusu isteğini tetikliyorsa etkinliğin dialogEventType alanı REQUEST_DIALOG olarak ayarlanır.

Chat uygulamanız, bir iletişim kutusu açmak için isteğe type özelliği DIALOG olarak ayarlanmış bir actionResponse nesnesi ve Message nesnesi döndürerek yanıt verebilir. İletişim kutusunun içeriğini belirtmek için aşağıdaki nesneleri eklersiniz:

  • type özelliği DIALOG olarak ayarlanmış bir actionResponse nesnesi.
  • dialogAction nesnesi. body alanı, kartta gösterilecek kullanıcı arayüzü (UI) öğelerini içerir. Bu öğeler arasında bir veya daha fazla sections widget'ı bulunur. Kullanıcılardan bilgi toplamak için form girişi widget'ları ve bir düğme widget'ı belirtebilirsiniz. Form girişlerini tasarlama hakkında daha fazla bilgi edinmek için Kullanıcılardan bilgi toplama ve bu bilgileri işleme başlıklı makaleyi inceleyin.

Aşağıdaki kod örneğinde, bir Chat uygulamasının iletişim kutusu açan bir yanıtı nasıl döndürdüğü gösterilmektedir:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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" }}
        }]}
      }])
    }]}}}
  }};
}

İletişim kutusu gönderimini işleme

Kullanıcılar bir iletişim kutusunu gönderen düğmeyi tıkladığında, sohbet uygulamanızda CARD_CLICKED etkileşim etkinliği gerçekleşir. Bu etkinlikte dialogEventType SUBMIT_DIALOG olur. İletişim kutusundaki bilgilerin nasıl toplanıp işleneceğini öğrenmek için Chat kullanıcılarından bilgi toplama ve işleme başlıklı makaleyi inceleyin.

Sohbet uygulamanız, etkileşim etkinliğine aşağıdaki yöntemlerden birini kullanarak yanıt vermelidir:

İsteğe bağlı: Başka bir iletişim kutusu döndürme

Kullanıcılar ilk iletişim kutusunu gönderdikten sonra Chat uygulamaları, kullanıcıların bilgileri göndermeden önce incelemesine, çok adımlı formları tamamlamasına veya form içeriğini dinamik olarak doldurmasına yardımcı olmak için bir veya daha fazla ek iletişim kutusu döndürebilir.

Kullanıcıların girdiği verileri işlemek için Chat uygulaması event.common.formInputs nesnesini kullanır. Giriş widget'larından değer alma hakkında daha fazla bilgi edinmek için Kullanıcılardan bilgi toplama ve bu bilgileri işleme başlıklı makaleyi inceleyin.

Kullanıcıların ilk iletişim kutusundan girdiği verileri takip etmek için sonraki iletişim kutusunu açan düğmeye parametreler eklemeniz gerekir. Ayrıntılar için Verileri başka bir karta aktarma başlıklı makaleyi inceleyin.

Bu örnekte, bir sohbet uygulaması, gönderilmeden önce onay için ikinci bir iletişim kutusuna yönlendiren ilk iletişim kutusunu açıyor:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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]}
    }]
  }
}

İletişim kutusunu kapat

Kullanıcılar bir iletişim kutusundaki düğmeyi tıkladığında Chat uygulamanız ilişkili işlemi yürütür ve etkinlik nesnesini aşağıdaki bilgilerle birlikte sağlar:

Sohbet uygulaması, type özelliği DIALOG olarak ayarlanmış ve dialogAction özelliği doldurulmuş bir ActionResponse nesnesi döndürmelidir. İşlem başarısız olmadıysa aşağıdaki örnekte olduğu gibi dialogAction.actionStatus, OK olmalıdır:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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
      }}
    }
  };
}

İsteğe bağlı: Geçici bir bildirim görüntüleme

İletişim kutusunu kapattığınızda, uygulamayla etkileşimde bulunan kullanıcıya geçici bir metin bildirimi de gösterebilirsiniz.

Chat uygulaması, actionStatus ayarlanmış bir ActionResponse döndürerek başarı veya hata bildirimiyle yanıt verebilir.

Aşağıdaki örnekte, parametrelerin geçerli olup olmadığı kontrol edilir ve geçersiz olduğunda metin bildirimiyle iletişim kutusu kapatılır:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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
    }}
  }};
}

Parametreleri iletişim kutuları arasında aktarma hakkında ayrıntılı bilgi için Verileri başka bir karta aktarma başlıklı makaleyi inceleyin.

İsteğe bağlı: Onay sohbet mesajı gönderme

İletişim kutusunu kapattığınızda yeni bir sohbet mesajı da gönderebilir veya mevcut bir mesajı güncelleyebilirsiniz.

Yeni bir mesaj göndermek için type parametresi NEW_MESSAGE olarak ayarlanmış bir ActionResponse nesnesi döndürün. Aşağıdaki örnekte, onay metin mesajıyla iletişim kutusu kapatılıyor:

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 Komut Dosyası

Bu örnek, card JSON döndürerek kart mesajı gönderir. Apps Komut Dosyası kart hizmetini de kullanabilirsiniz.

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

Bir mesajı güncellemek için güncellenmiş mesajı içeren bir actionResponse nesnesi döndürün ve type değerini aşağıdakilerden biri olarak ayarlayın:

Sorun giderme

Bir Google Chat uygulaması veya kartı hata döndürdüğünde Chat arayüzünde "Bir hata oluştu" mesajı gösterilir. veya "İsteğiniz işlenemiyor." Bazen Chat kullanıcı arayüzünde hata mesajı gösterilmez ancak Chat uygulaması veya kartı beklenmedik bir sonuç üretir. Örneğin, kart mesajı görünmeyebilir.

Chat kullanıcı arayüzünde hata mesajı gösterilmese de Chat uygulamaları için hata günlüğü kaydı etkinleştirildiğinde hataları düzeltmenize yardımcı olacak açıklayıcı hata mesajları ve günlük verileri kullanılabilir. Hataları görüntüleme, hataları ayıklama ve düzeltme konusunda yardım için Google Chat hatalarını giderme ve düzeltme başlıklı makaleyi inceleyin.