پشتیبانی از گفتگوهای تعاملی

این صفحه توضیح می‌دهد که چگونه برنامه چت شما می‌تواند پنجره‌های گفتگو را برای پاسخ به کاربران باز کند.

دیالوگ‌ها رابط‌های کاربری مبتنی بر کارت و پنجره‌ای هستند که از یک فضای چت یا پیام باز می‌شوند. دیالوگ و محتوای آن فقط برای کاربری که آن را باز کرده قابل مشاهده است.

برنامه‌های چت می‌توانند از دیالوگ‌ها برای درخواست و جمع‌آوری اطلاعات از کاربران چت، از جمله فرم‌های چند مرحله‌ای، استفاده کنند. برای جزئیات بیشتر در مورد ساخت ورودی‌های فرم، به بخش جمع‌آوری و پردازش اطلاعات از کاربران مراجعه کنید.

پیش‌نیازها

نود جی اس

یک برنامه چت گوگل که رویدادهای تعاملی را دریافت و به آنها پاسخ می‌دهد. برای ایجاد یک برنامه چت تعاملی با استفاده از سرویس HTTP، این راهنمای سریع را تکمیل کنید.

پایتون

یک برنامه چت گوگل که رویدادهای تعاملی را دریافت و به آنها پاسخ می‌دهد. برای ایجاد یک برنامه چت تعاملی با استفاده از سرویس HTTP، این راهنمای سریع را تکمیل کنید.

جاوا

یک برنامه چت گوگل که رویدادهای تعاملی را دریافت و به آنها پاسخ می‌دهد. برای ایجاد یک برنامه چت تعاملی با استفاده از سرویس HTTP، این راهنمای سریع را تکمیل کنید.

اسکریپت برنامه‌ها

یک برنامه چت گوگل که رویدادهای تعاملی را دریافت و به آنها پاسخ می‌دهد. برای ایجاد یک برنامه چت تعاملی در Apps Script، این راهنمای سریع را تکمیل کنید.

باز کردن یک کادر محاوره‌ای

یک پنجره محاوره‌ای که شامل انواع ویجت‌های مختلف است.
شکل ۱ : یک برنامه چت نمونه که یک پنجره محاوره‌ای برای جمع‌آوری اطلاعات تماس باز می‌کند.

این بخش نحوه پاسخ دادن و تنظیم یک گفتگو را با انجام موارد زیر توضیح می‌دهد:

  1. درخواست گفتگو را از تعامل کاربر فعال می‌کند.
  2. با بازگرداندن و باز کردن یک کادر محاوره‌ای، درخواست را مدیریت کنید.
  3. پس از ارسال اطلاعات توسط کاربران، با بستن کادر محاوره‌ای یا بازگرداندن کادر محاوره‌ای دیگر، اطلاعات ارسالی را پردازش کنید.

ایجاد یک درخواست محاوره‌ای

یک برنامه چت فقط می‌تواند دیالوگ‌هایی را برای پاسخ به تعامل کاربر، مانند یک دستور یا کلیک روی دکمه‌ای از یک پیام در یک کارت، باز کند.

برای پاسخ به کاربران با یک دیالوگ، یک برنامه چت باید تعاملی ایجاد کند که درخواست دیالوگ را فعال کند، مانند موارد زیر:

  • پاسخ به یک فرمان. برای فعال کردن درخواست از یک فرمان، باید هنگام پیکربندی فرمان، کادر انتخاب Opens a dialog را علامت بزنید.
  • به کلیک دکمه در یک پیام ، چه به عنوان بخشی از یک کارت و چه در پایین پیام، پاسخ دهید . برای اجرای درخواست از یک دکمه در یک پیام، می‌توانید با تنظیم interaction آن با OPEN_DIALOG ، عملکرد onClick دکمه را پیکربندی کنید.
  • به کلیک دکمه در صفحه اصلی برنامه چت پاسخ دهید . برای کسب اطلاعات در مورد باز کردن پنجره‌های گفتگو از صفحات اصلی، به بخش «ساخت صفحه اصلی برای برنامه Google Chat» مراجعه کنید.
دکمه‌ای که یک کادر محاوره‌ای را باز می‌کند
شکل ۲ : یک برنامه چت پیامی ارسال می‌کند که کاربران را به استفاده از دستور /addContact اسلش ترغیب می‌کند.
این پیام همچنین شامل دکمه‌ای است که کاربران می‌توانند برای اجرای دستور روی آن کلیک کنند.

نمونه کد زیر نحوه‌ی فعال‌سازی درخواست دیالوگ از یک دکمه در یک پیام کارت را نشان می‌دهد. برای باز کردن دیالوگ، فیلد button.interaction روی OPEN_DIALOG تنظیم می‌شود:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/main.py
'buttonList': { 'buttons': [{
  'text': "Add Contact",
  'onClick': { 'action': {
    'function': "openInitialDialog",
    'interaction': "OPEN_DIALOG"
  }}
}]}

جاوا

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

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.gs
buttonList: { buttons: [{
  text: "Add Contact",
  onClick: { action: {
    function: "openInitialDialog",
    interaction: "OPEN_DIALOG"
  }}
}]}

باز کردن کادر محاوره‌ای اولیه

وقتی کاربری درخواست دیالوگ را ارسال می‌کند، برنامه چت شما یک رویداد تعاملی دریافت می‌کند که به عنوان یک نوع event در Chat API نمایش داده می‌شود. اگر این تعامل منجر به درخواست دیالوگ شود، فیلد dialogEventType رویداد روی REQUEST_DIALOG تنظیم می‌شود.

برای باز کردن یک کادر محاوره‌ای، برنامه چت شما می‌تواند با برگرداندن یک شیء actionResponse با type تنظیم شده روی DIALOG و شیء Message به درخواست پاسخ دهد. برای مشخص کردن محتوای کادر محاوره‌ای، اشیاء زیر را وارد می‌کنید:

  • یک شیء actionResponse ، که type آن روی DIALOG تنظیم شده است.
  • یک شیء dialogAction . فیلد body شامل عناصر رابط کاربری (UI) برای نمایش در کارت، از جمله یک یا چند sections از ویجت‌ها است. برای جمع‌آوری اطلاعات از کاربران، می‌توانید ویجت‌های ورودی فرم و یک ویجت دکمه را مشخص کنید. برای کسب اطلاعات بیشتر در مورد طراحی ورودی‌های فرم، به بخش جمع‌آوری و پردازش اطلاعات از کاربران مراجعه کنید.

نمونه کد زیر نشان می‌دهد که چگونه یک برنامه چت، پاسخی را برمی‌گرداند که یک کادر محاوره‌ای را باز می‌کند:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/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/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()))))))));
}

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.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" }}
        }]}
      }])
    }]}}}
  }};
}

مدیریت ارسال دیالوگ

وقتی کاربران روی دکمه‌ای که یک کادر محاوره‌ای را ارسال می‌کند کلیک می‌کنند، برنامه چت شما یک رویداد تعاملی CARD_CLICKED دریافت می‌کند که در آن dialogEventType SUBMIT_DIALOG است. برای درک نحوه جمع‌آوری و پردازش اطلاعات در کادر محاوره‌ای، به بخش جمع‌آوری و پردازش اطلاعات از کاربران چت مراجعه کنید.

برنامه چت شما باید با انجام یکی از موارد زیر به رویداد تعامل پاسخ دهد:

اختیاری: یک کادر محاوره‌ای دیگر برگردانید

پس از ارسال دیالوگ اولیه توسط کاربران، برنامه‌های چت می‌توانند یک یا چند دیالوگ اضافی را برای کمک به کاربران در بررسی اطلاعات قبل از ارسال، تکمیل فرم‌های چند مرحله‌ای یا پر کردن پویای محتوای فرم، برگردانند.

برای پردازش داده‌هایی که کاربران وارد می‌کنند، برنامه چت از شیء event.common.formInputs استفاده می‌کند. برای کسب اطلاعات بیشتر در مورد بازیابی مقادیر از ویجت‌های ورودی، به بخش جمع‌آوری و پردازش اطلاعات از کاربران مراجعه کنید.

برای پیگیری هرگونه داده‌ای که کاربران از کادر محاوره‌ای اولیه وارد می‌کنند، باید پارامترهایی را به دکمه‌ای که کادر محاوره‌ای بعدی را باز می‌کند اضافه کنید. برای جزئیات بیشتر، به بخش انتقال داده به کارت دیگر مراجعه کنید.

در این مثال، یک برنامه چت یک کادر محاوره‌ای اولیه را باز می‌کند که قبل از ارسال، به کادر محاوره‌ای دوم برای تأیید منتهی می‌شود:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/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/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)))));
}

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.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]}
    }]
  }
}

بستن کادر محاوره‌ای

وقتی کاربران روی دکمه‌ای در یک کادر محاوره‌ای کلیک می‌کنند، برنامه چت شما اکشن مرتبط با آن را اجرا می‌کند و اطلاعات زیر را به شیء رویداد ارائه می‌دهد:

برنامه چت باید یک شیء ActionResponse را با type تنظیم شده روی DIALOG برگرداند و dialogAction پر کند. اگر عمل با شکست مواجه نشد، dialogAction.actionStatus باید مانند مثال زیر OK باشد:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/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/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))));
}

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.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
      }}
    }
  };
}

اختیاری: نمایش یک اعلان موقت

وقتی کادر محاوره‌ای را می‌بندید، می‌توانید یک اعلان متنی موقت نیز به کاربری که در حال تعامل با برنامه است، نمایش دهید.

برنامه چت می‌تواند با برگرداندن یک ActionResponse با تنظیم actionStatus ، اعلان موفقیت یا خطا را ارسال کند.

مثال زیر بررسی می‌کند که پارامترها معتبر هستند و در صورت نامعتبر بودن، کادر محاوره‌ای را با اعلان متنی می‌بندد:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/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/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))));
}

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.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
    }}
  }};
}

برای جزئیات بیشتر در مورد ارسال پارامترها بین کادرهای محاوره‌ای، به بخش انتقال داده به کارت دیگر مراجعه کنید.

اختیاری: ارسال پیام چت تأیید

وقتی کادر محاوره‌ای را می‌بندید، می‌توانید یک پیام چت جدید ارسال کنید یا یک پیام موجود را به‌روزرسانی کنید.

برای ارسال پیام جدید، یک شیء ActionResponse با type تنظیم شده روی NEW_MESSAGE برگردانید. مثال زیر کادر محاوره‌ای را با پیام متنی تأیید می‌بندد:

نود جی اس

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

پایتون

پایتون/فرم تماس-برنامه/main.py
return {
  'actionResponse': { 'type': "NEW_MESSAGE" },
  'privateMessageViewer': event.get('user'),
  'text': confirmation_message
}

جاوا

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

اسکریپت برنامه‌ها

این مثال با برگرداندن JSON کارت، یک پیام کارت ارسال می‌کند. همچنین می‌توانید از سرویس کارت Apps Script استفاده کنید.

اسکریپت برنامه‌ها/فرم تماس-برنامه/اصلی.gs
return {
  actionResponse: { type: "NEW_MESSAGE" },
  privateMessageViewer: event.user,
  text: confirmationMessage
};

برای به‌روزرسانی یک پیام، یک شیء actionResponse که حاوی پیام به‌روزرسانی‌شده است را برمی‌گرداند و type آن را روی یکی از موارد زیر تنظیم می‌کند:

عیب‌یابی

وقتی یک برنامه یا کارت چت گوگل خطایی را برمی‌گرداند، رابط چت پیامی با عنوان «مشکلی پیش آمده است» یا «درخواست شما قابل پردازش نیست» نمایش می‌دهد. گاهی اوقات رابط کاربری چت هیچ پیام خطایی را نمایش نمی‌دهد، اما برنامه یا کارت چت نتیجه غیرمنتظره‌ای را ایجاد می‌کند؛ برای مثال، ممکن است پیام کارت ظاهر نشود.

اگرچه ممکن است پیام خطا در رابط کاربری چت نمایش داده نشود، پیام‌های خطای توصیفی و داده‌های گزارش برای کمک به شما در رفع خطاها هنگام فعال بودن ثبت خطا برای برنامه‌های چت در دسترس هستند. برای کمک به مشاهده، اشکال‌زدایی و رفع خطاها، به عیب‌یابی و رفع خطاهای گوگل چت مراجعه کنید.