Mengumpulkan dan mengelola kontak di Google Chat

Tutorial ini menunjukkan cara mem-build aplikasi Google Chat yang membantu pengguna Google Chat mengelola kontak pribadi dan bisnis mereka. Untuk mengumpulkan informasi, aplikasi Chat akan meminta pengguna untuk menyelesaikan formulir kontak dalam dialog dan pesan kartu.

Lihat cara kerja aplikasi Chat:

  • Formulir kontak dari perintah garis miring.
    Gambar 1. Tujuan Aplikasi Chat merespons perintah garis miring /about dengan pesan teks dan tombol yang membuka formulir kontak.
  • Formulir kontak dalam dialog.
    Gambar 2. Tujuan Aplikasi Chat membuka dialog tempat pengguna dapat memasukkan informasi tentang kontak.
  • Konfirmasi dan tinjau dialog.
    Gambar 3. Tujuan Aplikasi Chat menampilkan dialog konfirmasi sehingga pengguna dapat meninjau dan mengonfirmasi informasi sebelum mengirimkan.
  • Pesan teks yang mengonfirmasi kontak baru.
    Gambar 4. Setelah pengguna mengirimkan formulir, aplikasi Chat akan mengirim pesan teks pribadi untuk mengonfirmasi pengiriman.
  • Formulir kontak dari pesan kartu.
    Gambar 5. Aplikasi Chat juga meminta pengguna untuk menambahkan kontak dari kartu dalam pesan.

Prasyarat

Tujuan

Arsitektur

Aplikasi Chat bawaan Google Apps Script dan penggunaan peristiwa interaksi yang akan diproses dan merespons pengguna Chat.

Berikut ini memperlihatkan bagaimana pengguna biasanya berinteraksi dengan Aplikasi Chat:

  1. Pengguna membuka pesan langsung dengan aplikasi Chat, atau menambahkan aplikasi Chat ke ruang yang ada.

  2. Aplikasi Chat meminta pengguna untuk menambahkan kontak dengan mem-build dan menampilkan formulir kontak sebagai objek card. Untuk mempresentasikan formulir kontak, aplikasi Chat merespons pengguna dengan cara berikut:

    • Membalas @sebutan dan pesan langsung dengan pesan kartu yang berisi formulir kontak.
    • Merespons perintah garis miring /addContact dengan membuka dialog berisi formulir kontak.
    • Merespons perintah garis miring /about dengan pesan teks yang memiliki Tombol Tambahkan kontak yang dapat diklik pengguna untuk membuka dialog dengan formulir kontak.
  3. Saat ditampilkan dengan formulir kontak, pengguna memasukkan informasi kontak ke dalam kolom dan widget berikut:

    • Nama depan dan belakang: textInput yang menerima string.
    • Tanggal lahir: widget dateTimePicker yang hanya menerima tanggal.
    • Jenis kontak: widget selectionInput tombol pilihan yang memungkinkan pengguna memilih dan mengirimkan satu nilai string (Personal atau Work).
    • Tombol Tinjau dan kirim: a buttonList dengan widget button yang diklik pengguna untuk mengirimkan nilai yang yang mereka masukkan.
  4. Aplikasi Google Chat menangani peristiwa interaksi CARD_CLICKED untuk memproses nilai yang dimasukkan pengguna, dan menampilkan nilai dalam kartu konfirmasi.

  5. Pengguna meninjau kartu konfirmasi dan mengklik tombol Kirim untuk menyelesaikan informasi kontak.

  6. Aplikasi Google Chat mengirim pesan teks pribadi yang mengonfirmasi pengiriman.

Menyiapkan lingkungan

Bagian ini menunjukkan cara membuat dan mengonfigurasi project Google Cloud untuk Aplikasi Chat.

Membuat project Google Cloud

Konsol Google Cloud

  1. Di konsol Google Cloud, buka Menu > IAM & Admin > Buat Project.

    Buka Membuat Project

  2. Di kolom Project Name, masukkan nama deskriptif untuk project Anda.

    Opsional: Untuk mengedit Project ID, klik Edit. Project ID tidak dapat diubah setelah proyek dibuat, jadi pilihlah ID yang sesuai dengan kebutuhan Anda sepanjang waktu proyek.

  3. Di kolom Lokasi, klik Jelajahi untuk menampilkan potensi lokasi untuk proyek. Kemudian, klik Select.
  4. Klik Buat. Konsol Google Cloud membuka halaman Dashboard dan project Anda telah dibuat dalam beberapa menit.

gcloud CLI

Di salah satu lingkungan pengembangan berikut, akses paket Google Cloud CLI (gcloud):

  • Cloud Shell: Untuk menggunakan terminal online dengan gcloud CLI yang sudah disiapkan, aktifkan Cloud Shell.
    Aktifkan Cloud Shell
  • Shell Lokal: Untuk menggunakan lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI.
    Untuk membuat project Cloud, gunakan perintah gcloud projects create:
    gcloud projects create PROJECT_ID
    Ganti PROJECT_ID dengan menetapkan ID untuk project yang ingin Anda buat.

Menyiapkan autentikasi dan otorisasi

Aplikasi Google Chat mengharuskan Anda mengonfigurasi layar izin OAuth sehingga pengguna dapat memberikan otorisasi ke aplikasi Anda di aplikasi Google Workspace, termasuk Google Chat.

Dalam tutorial ini, Anda akan men-deploy aplikasi Chat khusus untuk pengujian dan penggunaan internal, tidak masalah menggunakan informasi {i>placeholder<i} untuk layar persetujuan. Sebelum memublikasikan aplikasi Chat, ganti informasi placeholder dengan informasi yang sebenarnya.

  1. Di konsol Google Cloud, buka Menu > APIs & Services > OAuth consent screen.

    Buka layar izin OAuth

  2. Di bagian Jenis pengguna, pilih Internal, lalu klik Buat.

  3. Di App name, ketik Contact Manager.

  4. Di bagian Email dukungan pengguna, pilih alamat email Anda atau alamat Grup Google.

  5. Di bagian Informasi kontak developer, masukkan alamat email Anda.

  6. Klik Simpan dan Lanjutkan.

  7. Di halaman Cakupan, klik Simpan dan Lanjutkan. (Aplikasi Chat tidak memerlukan cakupan OAuth apa pun.)

  8. Tinjau ringkasan, lalu klik Kembali ke Dasbor.

Membuat dan men-deploy aplikasi Chat

Di bagian berikut, Anda akan menyalin dan memperbarui seluruh Project Apps Script yang berisi semua aplikasi yang diperlukan kode aplikasi Chat, jadi tidak perlu menyalin dan tempelkan setiap file.

Atau, Anda dapat melihat seluruh project di GitHub.

Lihat di GitHub

Berikut ringkasan setiap filenya:

main.gs

Menangani semua logika aplikasi, termasuk peristiwa interaksi tentang kapan pengguna mengirim pesan ke aplikasi Chat, klik tombol dari pesan aplikasi Chat, atau membuka dan menutup dialog.

Lihat kode main.gs

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: "openDialog",
              interaction: "OPEN_DIALOG"
            }}
          }]}}]
        }
      case 2:
        // If the slash command is "/addContact", opens a dialog.
        return openDialog(event);
    }
  }

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

/**
 * 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 === "openDialog") {
    return openDialog(event);
  // Second dialog form page
  } else if (event.common.invokedFunction === "openNextCard") {
    return openNextCard(
      event.user,
      fetchFormValue(event, "contactName"),
      fetchFormValue(event, "contactBirthdate"),
      fetchFormValue(event, "contactType"),
      event.isDialogEvent
    );
  // Dialog form submission
  } else if (event.common.invokedFunction === "submitForm") {
    const userInputs = event.common.parameters;
    return submitForm(event.user, userInputs, event.dialogEventType);
  }
}

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

/**
 * Opens a dialog that prompts users to add details about a contact.
 *
 * @return {Object} a message with an action response to open a dialog.
 */
function openDialog() {
  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: "openNextCard" }}
        }]}
      }])
    }]}}}
  }};
}

/**
 * Returns a dialog or card message that displays a confirmation of contact
 * details before users submit.
 *
 * @param {String} user the user who submitted the information.
 * @param {String} contactName the contact name from the previous dialog or card.
 * @param {String} contactBirthdate the birthdate from the previous dialog or card.
 * @param {String} contactType the contact type from the previous dialog or card.
 * @param {boolean} fromDialog whether the information was submitted from a dialog.
 *
 * @return {Object} returns a dialog or private card message.
 */
function openNextCard(user, contactName, contactBirthdate, contactType, fromDialog) {
  const name = contactName ?? "<i>Not provided</i>";
  const birthdate = contactBirthdate ?? "<i>Not provided</i>";
  const type = contactType ?? "<i>Not provided</i>";
  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 (fromDialog) {
    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: user,
    cardsV2: [{
      card: { sections: [cardConfirmation]}
    }]
  }
}

/**
  * Submits information from a dialog or card message.
  *
  * @param {Object} user the person who submitted the information.
  * @param {Object} userInputs the form input values from event parameters.
  * @param {boolean} dialogEventType "SUBMIT_DIALOG" if from a dialog.
  * @return {Object} a message response that opens a dialog or posts a private
  *                  message.
  */
function submitForm(user, userInputs, dialogEventType) {
  const contactName = userInputs["contactName"];
  // Checks to make sure the user entered a contact name.
  // If no name value detected, returns an error message.
  if (!contactName) {
    const errorMessage = "Don't forget to name your new contact!";
    if (dialogEventType === "SUBMIT_DIALOG") {
      return { actionResponse: {
        type: "DIALOG",
        dialogAction: { actionStatus: {
          statusCode: "INVALID_ARGUMENT",
          userFacingMessage: errorMessage
        }}
      }};
    } else {
      return {
        privateMessageViewer: 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 (dialogEventType === "SUBMIT_DIALOG") {
    return {
      actionResponse: {
        type: "NEW_MESSAGE",
        dialogAction: { actionStatus: {
          statusCode: "OK",
          userFacingMessage: "Success " + JSON.stringify(contactName)
        }}
      },
      privateMessageViewer: user,
      text: confirmationMessage
    }
  } else {
    return {
      actionResponse: { type: "NEW_MESSAGE" },
      privateMessageViewer: user,
      text: confirmationMessage
    };
  }
}

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

Berisi widget yang menerima data formulir dari pengguna. Input formulir ini widget ditampilkan di kartu yang muncul dalam pesan dan dialog.

Lihat kode contactForm.gs

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

Tujuan Manifes Apps Script yang mendefinisikan dan mengonfigurasi project Apps Script untuk Aplikasi Chat.

Lihat kode appsscript.json

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

Menemukan nomor dan ID project Cloud Anda

  1. Di konsol Google Cloud, buka project Cloud Anda.

    Buka konsol Google Cloud

  2. Klik Settings and Utilities > Project settings.

  3. Catat nilai di kolom Project number dan Project ID. Anda akan menggunakannya di bagian berikut.

Membuat project Apps Script

Untuk membuat project Apps Script dan menghubungkannya dengan project Cloud Anda:

  1. Klik tombol berikut untuk membuka project Apps Script Kelola kontak di Google Chat.
    Membuka project
  2. Klik Ringkasan.
  3. Di halaman ringkasan, klik Ikon untuk membuat salinan Buat salinan.
  4. Beri nama salinan project Apps Script:

    1. Klik Salinan Kelola kontak di Google Chat.

    2. Di Project title, ketik Contact Manager - Google Chat app

    3. Klik Ganti nama.

Menetapkan project Cloud project Apps Script

  1. Di project Apps Script Anda, klik Ikon untuk setelan project Project Settings.
  2. Pada Google Cloud Platform (GCP) Project, klik Change project.
  3. Di GCP project number, tempel nomor project dari project Cloud Anda.
  4. Klik Set project. Project Cloud dan Apps Script sekarang terhubung.

Membuat deployment Apps Script

Setelah semua kode berada di tempatnya, deploy Apps Script proyek. Anda menggunakan ID deployment saat mengonfigurasi Aplikasi Chat di Google Cloud.

  1. Di Apps Script, buka project aplikasi Chat.

    Buka Apps Script

  2. Klik Deploy > Deployment baru.

  3. Jika Add-on belum dipilih, di samping Pilih jenis, klik jenis deployment Ikon untuk setelan project, lalu pilih Add-on.

  4. Di bagian Description, masukkan deskripsi untuk versi ini, seperti Test of Contact Manager.

  5. Klik Deploy. Laporan Apps Script berhasil deployment dan memberikan ID deployment.

  6. Klik Salin untuk menyalin ID deployment, lalu klik Selesai.

Mengonfigurasi aplikasi Chat di Konsol Google Cloud

Bagian ini menunjukkan cara mengonfigurasi Google Chat API di konsol Google Cloud dengan informasi tentang aplikasi Chat Anda, termasuk ID deployment yang baru saja dibuat dari Apps Script proyek.

  1. Di Konsol Google Cloud, klik Menu &gt; Produk lainnya &gt; Google Workspace &gt; Library Produk &gt; Google Chat API &gt; Kelola &gt; Konfigurasi.

    Buka konfigurasi Chat API

  2. Di App name, ketik Contact Manager.

  3. Di Avatar URL, ketik https://developers.google.com/chat/images/contact-icon.png.

  4. Di Deskripsi, ketik Manage your personal and business contacts.

  5. Klik tombol Enable Interactive features ke posisi aktif.

  6. Di bawah Functionality, centang kotak Receive 1:1 messages dan Bergabung ke ruang dan percakapan grup.

  7. Di bagian Connection settings, pilih Apps Script..

  8. Di ID Deployment, tempel ID Deployment Apps Script yang Anda salin di bagian sebelumnya saat membuat Deployment Apps Script.

  9. Di bagian Perintah garis miring, siapkan perintah garis miring /about dan /addContact:

    1. Klik Add a slash command untuk menyiapkan perintah garis miring pertama.
    2. Di Name, ketik /about.
    3. Pada Command ID, ketik 1.
    4. Di Description, ketik Learn how to use this Chat app to manage your contacts.
    5. Pilih Opens a dialog.
    6. Klik Selesai.
    7. Klik Add a slash command untuk menyiapkan perintah garis miring lainnya.
    8. Di Nama, ketik /addContact
    9. Pada Command ID, ketik 2.
    10. Di Deskripsi, ketik Submit information about a contact.
    11. Pilih Opens a dialog.
    12. Klik Selesai.
  10. Di bagian Visibilitas, centang kotak Buat aplikasi Chat ini tersedia untuk orang dan grup tertentu di YOUR DOMAIN, lalu masukkan alamat email Anda.

  11. Di bagian Logs, pilih Log errors to Logging.

  12. Klik Simpan. Pesan konfigurasi tersimpan akan muncul.

Aplikasi Chat siap diinstal dan diuji di Chat.

Menguji aplikasi Chat

Untuk menguji aplikasi Chat, buka ruang pesan langsung dengan aplikasi Chat dan kirim pesan:

  1. Buka Google Chat menggunakan akun Google Workspace yang telah Anda yang diberikan ketika Anda menambahkan diri Anda sebagai penguji tepercaya.

    Buka Google Chat

  2. Klik Chat baru.
  3. Di kolom Tambahkan 1 orang atau lebih, ketik nama aplikasi Chat Anda.
  4. Pilih aplikasi Chat Anda dari hasil yang ditampilkan. Iklan langsung pesan terbuka.

  1. Di pesan langsung baru dengan aplikasi Chat, ketik /addContact dan tekan enter.

  2. Pada dialog yang terbuka, masukkan informasi kontak:

    1. Di kolom teks Nama depan dan nama belakang, masukkan nama.
    2. Di pemilih tanggal Birthdate, pilih tanggal.
    3. Di bagian Jenis kontak, pilih tombol pilihan Kantor atau Pribadi.
  3. Klik Tinjau dan kirim.

  4. Pada dialog konfirmasi, tinjau informasi yang Anda kirimkan dan klik Kirim. Aplikasi Chat membalas dengan teks pesan yang bertuliskan CONTACT NAME has been added to your contacts..

  5. Secara opsional, Anda juga dapat menguji dan mengirimkan formulir kontak dalam cara:

    • Gunakan perintah garis miring /about. Balasan aplikasi Chat dengan pesan teks dan tombol widget aksesori yang bertuliskan Add a contact. Anda dapat mengklik tombol untuk membuka dialog dengan formulir kontak.
    • Kirim pesan langsung ke aplikasi Chat tanpa perintah garis miring, seperti Hello. Aplikasi Chat membalas dengan teks dan kartu yang berisi formulir kontak.

Pembersihan

Agar tidak menimbulkan biaya ke akun Google Cloud Anda untuk sumber daya yang digunakan dalam tutorial ini, sebaiknya Anda menghapus project Google Cloud.

  1. Di Konsol Google Cloud, buka halaman Manage resources. Klik Menu > IAM & Admin > Kelola Resource.

    Buka Resource Manager

  2. Dalam daftar project, pilih project yang ingin Anda hapus, lalu klik Hapus .
  3. Pada dialog, ketik project ID, lalu klik Shut down untuk menghapus project.