Собирайте контакты и управляйте ими в Google Chat

В этом руководстве показано, как создать приложение Google Chat, которое поможет пользователям Google Chat управлять своими личными и деловыми контактами. Для сбора информации приложение Chat предлагает пользователям заполнить контактную форму в карточках сообщений и диалогах.

Посмотрите, как работает приложение «Чат»:

  • Форма обратной связи, созданная с помощью команды слэш.
    Figure 1. The Chat app responds to the slash command /about with a text message and button that opens a contact form.
  • Форма обратной связи в диалоговом окне.
    Figure 2. The Chat app opens a dialog where users can input information about a contact.
  • Подтвердите и просмотрите диалог.
    Figure 3. The Chat app returns a confirmation dialog so that users can review and confirm the information before submitting.
  • Текстовое сообщение, подтверждающее новый контакт.
    Figure 4. After the user submits the form, the Chat app sends a private text message to confirm the submission.
  • Форма обратной связи из сообщения на открытке.
    Figure 5. The Chat app also prompts users to add a contact from a card in a message.

Предварительные требования

Цели

Архитектура

The Chat app is built in Google Apps Script and uses interaction events to process and respond to Chat users.

Ниже показано, как пользователь обычно взаимодействует с приложением «Чат»:

  1. Пользователь открывает личное сообщение в приложении «Чат» или добавляет приложение «Чат» в уже существующее пространство.

  2. The Chat app prompts the user to add a contact by building and displaying a contact form as a card object. To present the contact form, the Chat app responds to users in the following ways:

    • Отвечает на упоминания (@mentions) и личные сообщения с помощью карточки, содержащей форму обратной связи.
    • Responds to the slash command /addContact by opening a dialog with the contact form.
    • Responds to the slash command /about with a text message that has a Add a contact button that users can click to open a dialog with the contact form.
  3. При появлении контактной формы пользователь вводит контактную информацию в следующие поля и виджеты:

    • First and last name : a textInput widget that accepts strings.
    • Birthdate : a dateTimePicker widget that accepts only dates.
    • Contact type : a selectionInput widget of radio buttons that lets users select and submit a single string value (either Personal or Work ).
    • Review and submit button: a buttonList array with button widget that the user clicks to submit the values that they input.
  4. The Google Chat app handles a CARD_CLICKED interaction event to process the values that the user inputs, and displays the values in a confirmation card.

  5. The user reviews the confirmation card and clicks the Submit button to finalize the contact information.

  6. Приложение Google Chat отправляет личное текстовое сообщение, подтверждающее отправку.

Подготовьте окружающую среду

В этом разделе показано, как настроить проект Google Cloud для приложения «Чат».

Откройте свой облачный проект в консоли Google Cloud.

Если проект Cloud, который вы собираетесь использовать в этом примере, еще не открыт, откройте его:

  1. In the Google Cloud console, go to the Select a project page.

    Выберите облачный проект

  2. Select the Google Cloud project you want to use. Or, click Create project and follow the on-screen instructions. If you create a Google Cloud project, you might need to turn on billing for the project .

Настройте аутентификацию и авторизацию.

Google Chat apps require you to configure an OAuth consent screen so that users can authorize your app in Google Workspace applications, including Google Chat.

В этом руководстве вы развернете приложение чата, предназначенное только для тестирования и внутреннего использования, поэтому допустимо использовать информацию-заполнитель для экрана согласия. Перед публикацией приложения чата замените любую информацию-заполнитель реальной информацией.

  1. In the Google Cloud console, go to Menu >Google Auth platform > Branding .

    Перейти к разделу «Брендинг»

  2. Если вы уже настроилиGoogle Auth platform, you can configure the following OAuth Consent Screen settings in Branding , Audience , and Data Access . If you see a message that says Google Auth platform not configured yet , click Get Started :

    1. Under App Information , in App name , type Contact Manager .
    2. In User support email , select your email address or an appropriate Google group.
    3. Нажмите «Далее» .
    4. Under Audience , select Internal . If you can't select Internal , select External .
    5. Нажмите «Далее» .
    6. Under Contact Information , enter an Email address where you can be notified about any changes to your project.
    7. Нажмите «Далее» .
    8. Under Finish , review the Google API Services User Data Policy and if you agree, select I agree to the Google API Services: User Data Policy .
    9. Click Continue .
    10. Click Create .
    11. If you selected External for user type, add test users:
      1. Click Audience .
      2. Under Test users , click Add users .
      3. Enter your email address and any other authorized test users, then click Save .

Создайте и разверните приложение «Чат».

В следующем разделе вы скопируете и обновите весь проект Apps Script, содержащий весь необходимый код приложения для вашего чат-приложения, поэтому нет необходимости копировать и вставлять каждый файл по отдельности.

При желании вы можете посмотреть весь проект на GitHub.

Посмотреть на GitHub

Вот краткий обзор каждого файла:

main.gs

Обрабатывает всю логику приложения, включая события взаимодействия, связанные с отправкой пользователями сообщений в приложение чата, нажатием кнопок в сообщениях приложения чата, а также открытием и закрытием диалоговых окон.

View main.gs code

apps-script/contact-form-app/main.gs
/**
 * Copyright 2024 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Responds to a MESSAGE interaction event in Google Chat.
 *
 * @param {Object} event the MESSAGE interaction event from Chat API.
 * @return {Object} message response that opens a dialog or sends private
 *                          message with text and card.
 */
function onMessage(event) {
  if (event.message.slashCommand) {
    switch (event.message.slashCommand.commandId) {
      case 1:
        // If the slash command is "/about", responds with a text message and button
        // that opens a dialog.
        return {
          text: "Manage your personal and business contacts 📇. To add a " +
                  "contact, use the slash command `/addContact`.",
          accessoryWidgets: [{
            buttonList: { buttons: [{
              text: "Add Contact",
              onClick: { action: {
                function: "openInitialDialog",
                interaction: "OPEN_DIALOG"
              }}
            }]}
          }]
        }
      case 2:
        // If the slash command is "/addContact", opens a dialog.
        return openInitialDialog();
    }
  }

  // If user sends the Chat app a message without a slash command, the app responds
  // privately with a text and card to add a contact.
  return {
    privateMessageViewer: event.user,
    text: "To add a contact, try `/addContact` or complete the form below:",
    cardsV2: [{
      cardId: "addContactForm",
      card: {
        header: { title: "Add a contact" },
        sections:[{ widgets: CONTACT_FORM_WIDGETS.concat([{
          buttonList: { buttons: [{
            text: "Review and submit",
            onClick: { action: { function : "openConfirmation" }}
          }]}
        }])}]
      }
    }]
  };
}

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

/**
  * Validates and submits information from a dialog or card message
  * and notifies status.
  *
  * @param {Object} event the interactive event with parameters.
  * @return {Object} a message response that opens a dialog or posts a private
  *                  message.
  */
function submitForm(event) {
  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
      }}
    }};
  }
  if (!contactName) {
    return {
      privateMessageViewer: event.user,
      text: errorMessage
    };
  }

  // 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
        }}
      }
    };
  }
  return {
    actionResponse: { type: "NEW_MESSAGE" },
    privateMessageViewer: event.user,
    text: confirmationMessage
  };
}

/**
 * Extracts form input value for a given widget.
 *
 * @param {Object} event the CARD_CLICKED interaction event from Google Chat.
 * @param {String} widgetName a unique ID for the widget, specified in the widget's name field.
 * @returns the value inputted by the user, null if no value can be found.
 */
function fetchFormValue(event, widgetName) {
  const formItem = event.common.formInputs[widgetName][""];
  // For widgets that receive StringInputs data, the value input by the user.
  if (formItem.hasOwnProperty("stringInputs")) {
    const stringInput = event.common.formInputs[widgetName][""].stringInputs.value[0];
    if (stringInput != null) {
      return stringInput;
    }
  // For widgets that receive dateInput data, the value input by the user.
  } else if (formItem.hasOwnProperty("dateInput")) {
    const dateInput = event.common.formInputs[widgetName][""].dateInput.msSinceEpoch;
     if (dateInput != null) {
       return dateInput;
     }
  }

  return null;
}

/**
 * Converts date in milliseconds since epoch to user-friendly string.
 *
 * @param {Object} millis the milliseconds since epoch time.
 * @return {string} Display-friend date (English US).
 */
function convertMillisToDateString(millis) {
  const date = new Date(millis);
  const options = { year: 'numeric', month: 'long', day: 'numeric' };
  return date.toLocaleDateString('en-US', options);
}
contactForm.gs

Содержит виджеты, получающие данные из форм от пользователей. Эти виджеты ввода данных из форм отображаются в карточках, которые появляются в сообщениях и диалогах.

View contactForm.gs code

apps-script/contact-form-app/contactForm.gs
/**
 * Copyright 2024 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * The section of the contact card that contains the form input widgets. Used in a dialog and card message.
 * To add and preview widgets, use the Card Builder: https://addons.gsuite.google.com/uikit/builder
 */
const CONTACT_FORM_WIDGETS = [
  {
    "textInput": {
      "name": "contactName",
      "label": "First and last name",
      "type": "SINGLE_LINE"
    }
  },
  {
    "dateTimePicker": {
      "name": "contactBirthdate",
      "label": "Birthdate",
      "type": "DATE_ONLY"
    }
  },
  {
    "selectionInput": {
      "name": "contactType",
      "label": "Contact type",
      "type": "RADIO_BUTTON",
      "items": [
        {
          "text": "Work",
          "value": "Work",
          "selected": false
        },
        {
          "text": "Personal",
          "value": "Personal",
          "selected": false
        }
      ]
    }
  }
];
appsscript.json

The Apps Script manifest that defines and configures the Apps Script project for the Chat app.

View appsscript.json code

apps-script/contact-form-app/appsscript.json
{
  "timeZone": "America/Los_Angeles",
  "dependencies": {},
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "chat": {}
}

Создайте проект Apps Script.

Для создания проекта Apps Script:

  1. Click the following button to open the Manage contacts in Google Chat Apps Script project.
    Откройте проект
  2. Click Overview .
  3. На странице обзора нажмите Значок для создания копии Make a copy .
  4. Назовите свою копию проекта Apps Script:

    1. Click Copy of Manage contacts in Google Chat .

    2. In Project title , type Contact Manager - Google Chat app

    3. Click Rename .

In the future, if you want to use certain Google APIs or publish your app, you must associate your Cloud project with your Apps Script project. For this guide, you don't need to do so. To learn more, see the Google Cloud projects guide .

Создайте развертывание Apps Script.

Теперь, когда весь код готов, разверните проект Apps Script. Идентификатор развертывания используется при настройке приложения «Чат» в Google Cloud.

  1. В Apps Script откройте проект приложения «Чат».

    Перейдите в раздел Apps Script.

  2. Click Deploy > New deployment .

  3. If Add-on isn't already selected, next to Select type , click deployment types Значок для настроек проекта and select Add-on .

  4. In Description , enter a description for this version, like Test of Contact Manager .

  5. Click Deploy . Apps Script reports successful deployment and provides a deployment ID.

  6. Click Copy to copy the deployment ID and then click Done .

Настройте приложение «Чат» в консоли Google Cloud.

В этом разделе показано, как настроить API Google Chat в консоли Google Cloud, используя информацию о вашем приложении Chat, включая идентификатор развертывания, которое вы только что создали из своего проекта Apps Script.

  1. In the Google Cloud console, click Menu > More products > Google Workspace > Product Library > Google Chat API > Manage > Configuration .

    Перейдите в раздел «Настройка API чата».

  2. Clear Build this Chat app as a Google Workspace add-on . A dialog opens asking you to confirm. In the dialog, click Disable .

  3. In App name , type Contact Manager .

  4. In Avatar URL , type https://developers.google.com/chat/images/contact-icon.png .

  5. In Description , type Manage your personal and business contacts .

  6. Click the Enable Interactive features toggle to the on position.

  7. Under Functionality , select Join spaces and group conversations .

  8. Under Connection settings , select Apps Script .

  9. In Deployment ID , paste the Apps Script Deployment ID that you copied in the previous section when you created the Apps Script deployment.

  10. Under Commands , set up the slash commands /about and /addContact :

    1. Click Add a slash command to set up the first slash command.
    2. In Name , type About .
    3. In Command ID , type 1 .
    4. In Description , type Learn how to use this Chat app to manage your contacts .
    5. Under Command type , select Slash command .
    6. In Slash command name , type /about .
    7. Select Opens a dialog .
    8. Click Done .
    9. Click Add a command to set up another slash command.
    10. In Name , type Add a contact .
    11. In Command ID , type 2 .
    12. In Description , type Submit information about a contact .
    13. Under Command type , select Slash command .
    14. In Slash command name , type /addContact .
    15. Select Opens a dialog .
    16. Click Done .
  11. Under Visibility , select the Make this Chat app available to specific people and groups in YOUR DOMAIN checkbox and enter your email address.

  12. Under Logs , select Log errors to Logging .

  13. Click Save . A configuration saved message appears.

Приложение «Чат» готово к установке и тестированию в приложении «Чат».

Протестируйте приложение для чата

Чтобы протестировать приложение «Чат», откройте личное сообщение в приложении «Чат» и отправьте сообщение:

  1. Откройте Google Chat, используя учетную запись Google Workspace, которую вы указали при добавлении себя в качестве доверенного тестировщика.

    Перейдите в Google Чат

  2. Click New chat .
  3. In the Add 1 or more people field, type the name of your Chat app.
  4. Выберите ваше приложение для чата из результатов поиска. Откроется личное сообщение.

  1. In the new direct message with the Chat app, type /addContact and press enter .

  2. В открывшемся диалоговом окне введите контактную информацию:

    1. In the First and last name text field, enter a name.
    2. In the Birthdate date picker, select a date.
    3. Under Contact type , select the Work or Personal radio button.
  3. Click Review and submit .

  4. In the confirmation dialog, review the information that you submitted and click Submit . The Chat app replies with a text message that says CONTACT NAME has been added to your contacts. .

  5. При желании вы также можете протестировать и отправить форму обратной связи следующими способами:

    • Use the /about slash command. Chat app replies with a text message and an accessory widget button that says Add a contact . You can click the button to open a dialog with the contact form.
    • Send the Chat app a direct message without a slash command, such as Hello . The Chat app replies with a text and card that contains the contact form.

Уборка

Чтобы избежать списания средств с вашего аккаунта Google Cloud за ресурсы, использованные в этом руководстве, мы рекомендуем удалить проект Cloud.

  1. In the Google Cloud console, go to the Manage resources page. Click Menu > IAM & Admin > Manage Resources .

    Перейдите в Диспетчер ресурсов

  2. In the project list, select the project you want to delete and then click Delete .
  3. In the dialog, type the project ID and then click Shut down to delete the project.