Merespons insiden dengan Google Chat, Vertex AI, dan Apps Script

Tutorial ini menunjukkan cara membuat aplikasi Google Chat yang merespons insiden secara real time. Saat merespons insiden, aplikasi akan membuat dan mengisi ruang Chat, memfasilitasi penyelesaian insiden dengan pesan, perintah garis miring, dan dialog, serta menggunakan AI untuk meringkas respons insiden dalam dokumen Google Dokumen.

Insiden adalah peristiwa yang perlu segera ditangani oleh tim yang terdiri dari orang-orang. Contoh insiden meliputi:

  • Kasus mendesak dibuat di platform Pengelolaan Hubungan Pelanggan (CRM), sehingga tim layanan harus berkolaborasi dalam menyelesaikan masalah.
  • Sebuah sistem akan offline, memberi tahu sekelompok Site Reliability Engineer (SRE) agar mereka dapat bekerja sama untuk mengembalikannya ke internet.
  • Gempa bumi berkekuatan tinggi terjadi, dan pekerja darurat perlu mengoordinasikan respons mereka.

Untuk tujuan tutorial ini, notifikasi insiden dimulai saat seseorang melaporkan insiden dengan klik tombol dari halaman web. Halaman web menyimulasikan insiden dengan meminta pengguna memasukkan informasi insiden dasar: judul, deskripsi, dan alamat email responden.

Lihat cara kerja aplikasi Chat manajemen insiden:

  • Situs web yang memulai insiden.
    Gambar 1. Situs tempat seseorang dapat melaporkan insiden.
  • Notifikasi bahwa ruang Chat insiden dibuat.
    Gambar 2. Notifikasi bahwa ruang Chat insiden dibuat.
  • Ruang Chat respons insiden.
    Gambar 3. Ruang Chat respons insiden.
  • Menyelesaikan insiden dengan perintah garis miring.
    Gambar 4. Menyelesaikan insiden dengan perintah garis miring.
  • Dialog resolusi insiden.
    Gambar 5. Dialog penyelesaian insiden.
  • Dokumen Google Dokumen resolusi insiden dibagikan di ruang.
    Gambar 6. Dokumen Google Dokumen resolusi insiden dibagikan di ruang.
  • Google Dokumen resolusi insiden ringkasan AI.
    Gambar 7. Dokumen Google Dokumen penyelesaian insiden ringkasan AI.

Prasyarat

Jika Anda perlu mengaktifkan salah satu prasyarat tersebut untuk organisasi Anda, minta administrator Google Workspace untuk mengaktifkannya:

  • Akun Google Workspace dengan akses ke Google Chat.
  • Mengaktifkan Direktori (berbagi kontak) untuk Google Workspace. Aplikasi insiden menggunakan direktori untuk mencari info kontak responden insiden, seperti nama dan alamat email. Perespons insiden harus merupakan pengguna dengan akun Google Chat di organisasi Google Workspace Anda.

Tujuan

  • Bangun aplikasi Chat yang merespons insiden.
  • Bantu pengguna merespons insiden dengan melakukan hal berikut:
    • Membuat ruang respons insiden.
    • Memposting pesan yang meringkas insiden dan respons.
    • Mendukung kolaborasi dengan fitur aplikasi Chat interaktif.
  • Meringkas percakapan dan resolusi dengan Vertex AI.

Arsitektur

Diagram berikut menunjukkan arsitektur resource Google Workspace dan Google Cloud yang digunakan oleh aplikasi Google Chat respons insiden.

Arsitektur aplikasi Google Chat respons insiden

Arsitektur ini menunjukkan cara aplikasi Google Chat respons insiden memproses insiden dan resolusi.

  1. Pengguna memulai insiden dari situs eksternal yang dihosting di Apps Script.

  2. Situs mengirimkan permintaan HTTP asinkron ke aplikasi Google Chat, yang juga dihosting di Apps Script.

  3. Aplikasi Google Chat respons insiden akan memproses permintaan tersebut:

    1. Layanan Apps Script Admin SDK mendapatkan informasi anggota tim, seperti ID pengguna dan alamat email.

    2. Dengan serangkaian permintaan HTTP ke Chat API menggunakan layanan Chat Lanjutan Apps Script, aplikasi Google Chat respons insiden akan membuat ruang Chat insiden, mengisinya dengan anggota tim, dan mengirim pesan ke ruang tersebut.

  4. Anggota tim mendiskusikan insiden di ruang Chat.

  5. Anggota tim memanggil perintah garis miring untuk menandakan penyelesaian pada insiden.

    1. Panggilan HTTP ke Chat API menggunakan layanan Chat Lanjutan Apps Script akan mencantumkan semua pesan Chat ruang.

    2. Vertex AI menerima pesan yang tercantum dan membuat ringkasan.

    3. Layanan DocumentApp Apps Script membuat dokumen Dokumen dan menambahkan ringkasan Vertex AI ke dokumen tersebut.

    4. Aplikasi Google Chat respons insiden memanggil Chat API untuk mengirim pesan yang membagikan link ke dokumen ringkasan Dokumen.

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 > Create a Project.

    Buka Create a Project

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

    Opsional: Untuk mengedit ID Project, klik Edit. Project ID tidak dapat diubah setelah project dibuat. Jadi, pilih ID yang sesuai dengan kebutuhan Anda sepanjang waktu project tersebut.

  3. Di kolom Location, klik Browse untuk menampilkan lokasi potensial project. Kemudian, klik Select.
  4. Klik Create. Konsol Google Cloud akan membuka halaman Dashboard dan project Anda akan dibuat dalam beberapa menit.

gcloud CLI

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

  • Cloud Shell: Untuk menggunakan terminal online dengan gcloud CLI yang sudah disiapkan, aktifkan Cloud Shell.
    Mengaktifkan Cloud Shell
  • Local Shell: Untuk menggunakan lingkungan pengembangan lokal, instal dan initialize gcloud CLI.
    Untuk membuat project Cloud, gunakan perintah `gcloud projects create`:
    gcloud projects create PROJECT_ID
    Ganti PROJECT_ID dengan menetapkan ID project yang ingin Anda buat.

Mengaktifkan penagihan untuk project Cloud

Konsol Google Cloud

  1. Di konsol Google Cloud, buka Billing. Klik Menu > Penagihan > Project Saya.

    Buka Billing for My Project

  2. Di bagian Select an organization, pilih organisasi yang terkait dengan project Google Cloud Anda.
  3. Di baris project, buka menu Actions (), klik Change billing, dan pilih akun Penagihan Cloud.
  4. Klik Tetapkan akun.

gcloud CLI

  1. Untuk menampilkan akun penagihan yang tersedia, jalankan:
    gcloud billing accounts list
  2. Tautkan akun penagihan dengan project Google Cloud:
    gcloud billing projects link PROJECT_ID --billing-account=BILLING_ACCOUNT_ID

    Ganti kode berikut:

    • PROJECT_ID adalah Project ID untuk project Cloud yang ingin Anda aktifkan penagihannya.
    • BILLING_ACCOUNT_ID adalah ID akun penagihan yang akan ditautkan dengan project Google Cloud.

Mengaktifkan API

Konsol Google Cloud

  1. Di konsol Google Cloud, aktifkan Google Chat API, Google Docs API, Admin SDK API, dan Vertex AI API.

    Aktifkan API

  2. Pastikan Anda mengaktifkan API di project Cloud yang benar, lalu klik Next.

  3. Pastikan Anda mengaktifkan API yang benar, lalu klik Enable.

gcloud CLI

  1. Jika perlu, tetapkan project Cloud saat ini ke project yang Anda buat menggunakan perintah gcloud config set project:

    gcloud config set project PROJECT_ID
    

    Ganti PROJECT_ID dengan Project ID dari project Cloud yang Anda buat.

  2. Aktifkan Google Chat API, Google Docs API, Admin SDK API, dan Vertex AI API dengan perintah gcloud services enable:

    gcloud services enable chat.googleapis.com docs.googleapis.com admin.googleapis.com aiplatform.googleapis.com
    

Menyiapkan autentikasi dan otorisasi

Autentikasi dan otorisasi memungkinkan aplikasi Chat mengakses resource di Google Workspace dan Google Cloud untuk memproses respons insiden.

Dalam tutorial ini, Anda akan memublikasikan aplikasi secara internal sehingga boleh menggunakan informasi placeholder. Sebelum memublikasikan aplikasi secara eksternal, ganti informasi placeholder dengan informasi sebenarnya untuk layar izin.

  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 Incident Management.

  4. Di Email dukungan pengguna, pilih alamat email Anda atau grup Google yang sesuai.

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

  6. Klik Save and Continue.

  7. Klik Tambahkan atau Hapus Cakupan. Sebuah panel akan muncul dan berisi daftar cakupan untuk setiap API yang telah diaktifkan di project Cloud Anda.

  8. Pada bagian Tambahkan cakupan secara manual, tempel cakupan berikut:

    • https://www.googleapis.com/auth/chat.spaces.create
    • https://www.googleapis.com/auth/chat.memberships
    • https://www.googleapis.com/auth/chat.memberships.app
    • https://www.googleapis.com/auth/chat.messages
    • https://www.googleapis.com/auth/documents
    • https://www.googleapis.com/auth/admin.directory.user.readonly
    • https://www.googleapis.com/auth/script.external_request
    • https://www.googleapis.com/auth/userinfo.email
    • https://www.googleapis.com/auth/cloud-platform
  9. Klik Add to Table.

  10. Klik Perbarui.

  11. Klik Save and Continue.

  12. Tinjau ringkasan pendaftaran aplikasi, lalu klik Kembali ke Dasbor.

Membuat dan men-deploy aplikasi Chat

Di bagian berikut, Anda akan menyalin dan mengupdate seluruh project Apps Script yang berisi semua kode aplikasi yang diperlukan untuk aplikasi Chat Anda, sehingga Anda tidak perlu menyalin dan menempel setiap file.

Beberapa fungsi menyertakan garis bawah di akhir namanya, seperti processSlashCommand_() dari ChatApp.gs. Garis bawah menyembunyikan fungsi dari halaman web inisialisasi insiden saat dibuka di browser. Untuk mengetahui informasi selengkapnya, lihat Fungsi pribadi.

Apps Script mendukung dua jenis file, skrip .gs dan file .html. Untuk mematuhi dukungan ini, JavaScript sisi klien aplikasi disertakan dalam tag <script /> dan CSS-nya disertakan di dalam tag <style /> di dalam file HTML.

Anda juga dapat melihat seluruh project di GitHub.

Lihat di GitHub

Berikut ini ringkasan setiap file:

Consts.gs

Menentukan konstanta yang dirujuk oleh file kode lain, termasuk project ID Cloud, ID lokasi Vertex AI, dan ID perintah garis miring untuk menutup insiden.

Lihat kode Consts.gs

apps-script/incident-response/Consts.gs
const PROJECT_ID = 'replace-with-your-project-id';
const VERTEX_AI_LOCATION_ID = 'us-central1';
const CLOSE_INCIDENT_COMMAND_ID = 1;
ChatApp.gs

Menangani peristiwa interaksi Chat, termasuk pesan, klik kartu, perintah garis miring, dan dialog. Merespons perintah garis miring /closeIncident dengan membuka dialog untuk mengumpulkan detail resolusi insiden. Membaca pesan dalam ruang dengan memanggil metode spaces.messages.list di Chat API. Mendapatkan ID pengguna menggunakan layanan Direktori Admin SDK di Apps Script.

Lihat kode ChatApp.gs

apps-script/incident-response/ChatApp.gs
/**
 * Responds to a MESSAGE event in Google Chat.
 *
 * This app only responds to a slash command with the ID 1 ("/closeIncident").
 * It will respond to any other message with a simple "Hello" text message.
 *
 * @param {Object} event the event object from Google Chat
 */
function onMessage(event) {
  if (event.message.slashCommand) {
    return processSlashCommand_(event);
  }
  return { "text": "Hello from Incident Response app!" };
}

/**
 * Responds to a CARD_CLICKED event in Google Chat.
 *
 * This app only responds to one kind of dialog (Close Incident).
 *
 * @param {Object} event the event object from Google Chat
 */
function onCardClick(event) {
  if (event.isDialogEvent) {
    if (event.dialogEventType == 'SUBMIT_DIALOG') {
      return processSubmitDialog_(event);
    }
    return {
      actionResponse: {
        type: "DIALOG",
        dialogAction: {
          actionStatus: "OK"
        }
      }
    };
  }
}

/**
 * Responds to a MESSAGE event with a Slash command in Google Chat.
 *
 * This app only responds to a slash command with the ID 1 ("/closeIncident")
 * by returning a Dialog.
 *
 * @param {Object} event the event object from Google Chat
 */
function processSlashCommand_(event) {
  if (event.message.slashCommand.commandId != CLOSE_INCIDENT_COMMAND_ID) {
    return {
      "text": "Command not recognized. Use the command `/closeIncident` to close the incident managed by this space."
    };
  }
  const sections = [
    {
      header: "Close Incident",
      widgets: [
        {
          textInput: {
            label: "Please describe the incident resolution",
            type: "MULTIPLE_LINE",
            name: "description"
          }
        },
        {
          buttonList: {
            buttons: [
              {
                text: "Close Incident",
                onClick: {
                  action: {
                    function: "closeIncident"
                  }
                }
              }
            ]
          }
        }
      ]
    }
  ];
  return {
    actionResponse: {
      type: "DIALOG",
      dialogAction: {
        dialog: {
          body: {
            sections,
          }
        }
      }
    }
  };
}

/**
 * Responds to a CARD_CLICKED event with a Dialog submission in Google Chat.
 *
 * This app only responds to one kind of dialog (Close Incident).
 * It creates a Doc with a summary of the incident information and posts a message
 * to the space with a link to the Doc.
 *
 * @param {Object} event the event object from Google Chat
 */
function processSubmitDialog_(event) {
  const resolution = event.common.formInputs.description[""].stringInputs.value[0];
  const chatHistory = concatenateAllSpaceMessages_(event.space.name);
  const chatSummary = summarizeChatHistory_(chatHistory);
  const docUrl = createDoc_(event.space.displayName, resolution, chatHistory, chatSummary);
  return {
    actionResponse: {
      type: "NEW_MESSAGE",
    },
    text: `Incident closed with the following resolution: ${resolution}\n\nHere is the automatically generated post-mortem:\n${docUrl}`
  };
}

/**
 * Lists all the messages in the Chat space, then concatenate all of them into
 * a single text containing the full Chat history.
 *
 * For simplicity for this demo, it only fetches the first 100 messages.
 *
 * Messages with slash commands are filtered out, so the returned history will
 * contain only the conversations between users and not app command invocations.
 *
 * @return {string} a text containing all the messages in the space in the format:
 *          Sender's name: Message
 */
function concatenateAllSpaceMessages_(spaceName) {
  // Call Chat API method spaces.messages.list
  const response = Chat.Spaces.Messages.list(spaceName, { 'pageSize': 100 });
  const messages = response.messages;
  // Fetch the display names of the message senders and returns a text
  // concatenating all the messages.
  let userMap = new Map();
  return messages
    .filter(message => message.slashCommand === undefined)
    .map(message => `${getUserDisplayName_(userMap, message.sender.name)}: ${message.text}`)
    .join('\n');
}

/**
 * Obtains the display name of a user by using the Admin Directory API.
 *
 * The fetched display name is cached in the provided map, so we only call the API
 * once per user.
 *
 * If the user does not have a display name, then the full name is used.
 *
 * @param {Map} userMap a map containing the display names previously fetched
 * @param {string} userName the resource name of the user
 * @return {string} the user's display name
 */
function getUserDisplayName_(userMap, userName) {
  if (userMap.has(userName)) {
    return userMap.get(userName);
  }
  let displayName = 'Unknown User';
  try {
    const user = AdminDirectory.Users.get(
      userName.replace("users/", ""),
      { projection: 'BASIC', viewType: 'domain_public' });
    displayName = user.name.displayName ? user.name.displayName : user.name.fullName;
  } catch (e) {
    // Ignore error if the API call fails (for example, because it's an
    // out-of-domain user or Chat app)) and just use 'Unknown User'.
  }
  userMap.set(userName, displayName);
  return displayName;
}
ChatSpaceCreator.gs

Menerima data formulir yang dimasukkan pengguna di halaman web inisialisasi insiden, dan menggunakannya untuk menyiapkan ruang Chat dengan membuat dan mengisinya, lalu memposting pesan tentang insiden.

Lihat kode ChatSpaceCreator.gs

apps-script/incident-response/ChatSpaceCreator.gs
/**
 * Creates a space in Google Chat with the provided title and members, and posts an
 * initial message to it.
 *
 * @param {Object} formData the data submitted by the user. It should contain the fields
 *                          title, description, and users.
 * @return {string} the resource name of the new space.
 */
function createChatSpace(formData) {
  const users = formData.users.trim().length > 0 ? formData.users.split(',') : [];
  const spaceName = setUpSpace_(formData.title, users);
  addAppToSpace_(spaceName);
  createMessage_(spaceName, formData.description);
  return spaceName;
}

/**
 * Creates a space in Google Chat with the provided display name and members.
 *
 * @return {string} the resource name of the new space.
 */
function setUpSpace_(displayName, users) {
  const memberships = users.map(email => ({
    member: {
      name: `users/${email}`,
      type: "HUMAN"
    }
  }));
  const request = {
    space: {
      displayName: displayName,
      spaceType: "SPACE",
      externalUserAllowed: true
    },
    memberships: memberships
  };
  // Call Chat API method spaces.setup
  const space = Chat.Spaces.setup(request);
  return space.name;
}

/**
 * Adds this Chat app to the space.
 *
 * @return {string} the resource name of the new membership.
 */
function addAppToSpace_(spaceName) {
  const request = {
    member: {
      name: "users/app",
      type: "BOT"
    }
  };
  // Call Chat API method spaces.members.create
  const membership = Chat.Spaces.Members.create(request, spaceName);
  return membership.name;
}

/**
 * Posts a text message to the space on behalf of the user.
 *
 * @return {string} the resource name of the new message.
 */
function createMessage_(spaceName, text) {
  const request = {
    text: text
  };
  // Call Chat API method spaces.messages.create
  const message = Chat.Spaces.Messages.create(request, spaceName);
  return message.name;
}
DocsApi.gs

Memanggil Google Docs API untuk membuat dokumen Google Dokumen di Google Drive pengguna dan menulis ringkasan informasi insiden, yang dibuat di VertexAiApi.gs, ke dokumen tersebut.

Lihat kode DocsApi.gs

apps-script/incident-response/DocsApi.gs
/**
 * Creates a Doc in the user's Google Drive and writes a summary of the incident information to it.
 *
 * @param {string} title The title of the incident
 * @param {string} resolution Incident resolution described by the user
 * @param {string} chatHistory The whole Chat history be included in the document
 * @param {string} chatSummary A summary of the Chat conversation to be included in the document
 * @return {string} the URL of the created Doc
 */
function createDoc_(title, resolution, chatHistory, chatSummary) {
  let doc = DocumentApp.create(title);
  let body = doc.getBody();
  body.appendParagraph(`Post-Mortem: ${title}`).setHeading(DocumentApp.ParagraphHeading.TITLE);
  body.appendParagraph("Resolution").setHeading(DocumentApp.ParagraphHeading.HEADING1);
  body.appendParagraph(resolution);
  body.appendParagraph("Summary of the conversation").setHeading(DocumentApp.ParagraphHeading.HEADING1);
  body.appendParagraph(chatSummary);
  body.appendParagraph("Full Chat history").setHeading(DocumentApp.ParagraphHeading.HEADING1);
  body.appendParagraph(chatHistory);
  return doc.getUrl();
}
VertexAiApi.gs

Merangkum percakapan di ruang Chat menggunakan Vertex AI. Ringkasan ini diposting dalam dokumen yang dibuat khusus di DocsAPI.gs.

Lihat kode VertexAiApi.gs

apps-script/incident-response/VertexAiApi.gs
/**
 * Summarizes a Chat conversation using the Vertex AI text prediction API.
 *
 * @param {string} chatHistory The Chat history that will be summarized.
 * @return {string} The content from the text prediction response.
 */
function summarizeChatHistory_(chatHistory) {
  const prompt =
    "Summarize the following conversation between Engineers resolving an incident"
      + " in a few sentences. Use only the information from the conversation.\n\n"
      + chatHistory;
  const request = {
    instances: [
      { prompt: prompt }
    ],
    parameters: {
      temperature: 0.2,
      maxOutputTokens: 256,
      topK: 40,
      topP: 0.95
    }
  }
  const fetchOptions = {
    method: 'POST',
    headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
    contentType: 'application/json',
    payload: JSON.stringify(request)
  }
  const response = UrlFetchApp.fetch(
    `https://${VERTEX_AI_LOCATION_ID}-aiplatform.googleapis.com/v1`
      + `/projects/${PROJECT_ID}/locations/${VERTEX_AI_LOCATION_ID}`
      + "/publishers/google/models/text-bison:predict",
    fetchOptions);
  const payload = JSON.parse(response.getContentText());
  return payload.predictions[0].content;
}
WebController.gs

Menyajikan situs inisialisasi insiden.

Lihat kode WebController.gs

apps-script/incident-response/WebController.gs
/**
 * Serves the web page from Index.html.
 */
function doGet() {
  return HtmlService
    .createTemplateFromFile('Index')
    .evaluate();
}

/**
 * Serves the web content from the specified filename.
 */
function include(filename) {
  return HtmlService
    .createHtmlOutputFromFile(filename)
    .getContent();
}

/**
 * Returns the email address of the user running the script.
 */
function getUserEmail() {
  return Session.getActiveUser().getEmail();
}
Index.html

HTML yang berisi situs inisialisasi insiden.

Lihat kode Index.html

apps-script/incident-response/Index.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>
    <?!= include('Stylesheet'); ?>
  </head>
  <body>
    <div class="container">
      <div class="content">
        <h1>Incident Manager</h1>
        <form id="incident-form" onsubmit="handleFormSubmit(this)">
          <div id="form">
            <p>
              <label for="title">Incident title</label><br/>
              <input type="text" name="title" id="title" />
            </p>
            <p>
              <label for="users">Incident responders</label><br/>
              <small>
                Please enter a comma-separated list of email addresses of the users
                that should be added to the space.
                Do not include <?= getUserEmail() ?> as it will be added automatically.
              </small><br/>
              <input type="text" name="users" id="users" />
            </p>
            <p>
              <label for="description">Initial message</label></br>
              <small>This message will be posted after the space is created.</small><br/>
              <textarea name="description" id="description"></textarea>
            </p>
            <p class="text-center">
              <input type="submit" value="CREATE CHAT SPACE" />
            </p>
          </div>
          <div id="output" class="hidden"></div>
          <div id="clear" class="hidden">
            <input type="reset" value="CREATE ANOTHER INCIDENT" onclick="onReset()" />
          </div>
        </form>
      </div>
    </div>
    <?!= include('JavaScript'); ?>
  </body>
</html>
JavaScript.html

Menangani perilaku formulir termasuk pengiriman, error, dan penghapusan, untuk situs inisialisasi insiden. Fungsi ini disertakan ke dalam Index.html oleh fungsi include kustom di WebController.gs.

Lihat kode JavaScript.html

apps-script/incident-response/JavaScript.html
<script>
  var formDiv = document.getElementById('form');
  var outputDiv = document.getElementById('output');
  var clearDiv = document.getElementById('clear');

  function handleFormSubmit(formObject) {
    event.preventDefault();
    outputDiv.innerHTML = 'Please wait while we create the space...';
    hide(formDiv);
    show(outputDiv);
    google.script.run
      .withSuccessHandler(updateOutput)
      .withFailureHandler(onFailure)
      .createChatSpace(formObject);
  }

  function updateOutput(response) {
    var spaceId = response.replace('spaces/', '');
    outputDiv.innerHTML =
      '<p>Space created!</p><p><a href="https://mail.google.com/chat/#chat/space/'
        + spaceId
        + '" target="_blank">Open space</a></p>';
    show(outputDiv);
    show(clearDiv);
  }

  function onFailure(error) {
    outputDiv.innerHTML = 'ERROR: ' + error.message;
    outputDiv.classList.add('error');
    show(outputDiv);
    show(clearDiv);
  }

  function onReset() {
    outputDiv.innerHTML = '';
    outputDiv.classList.remove('error');
    show(formDiv);
    hide(outputDiv);
    hide(clearDiv);
  }

  function hide(element) {
    element.classList.add('hidden');
  }

  function show(element) {
    element.classList.remove('hidden');
  }
</script>
Stylesheet.html

CSS untuk situs inisialisasi insiden. Disertakan ke dalam Index.html oleh fungsi include kustom di WebController.gs.

Lihat kode Stylesheet.html

apps-script/incident-response/Stylesheet.html
<style>
  * {
    box-sizing: border-box;
  }
  body {
    font-family: Roboto, Arial, Helvetica, sans-serif;
  }
  div.container {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 0; bottom: 0; left: 0; right: 0;
  }
  div.content {
    width: 80%;
    max-width: 1000px;
    padding: 1rem;
    border: 1px solid #999;
    border-radius: 0.25rem;
    box-shadow: 0 2px 2px 0 rgba(66, 66, 66, 0.08), 0 2px 4px 2px rgba(66, 66, 66, 0.16);
  }
  h1 {
    text-align: center;
    padding-bottom: 1rem;
    margin: 0 -1rem 1rem -1rem;
    border-bottom: 1px solid #999;
  }
 #output {
    text-align: center;
    min-height: 250px;
  }
  div#clear {
    text-align: center;
    padding-top: 1rem;
    margin: 1rem -1rem 0 -1rem;
    border-top: 1px solid #999;
  }
  input[type=text], textarea {
    width: 100%;
    padding: 1rem 0.5rem;
    margin: 0.5rem 0;
    border: 0;
    border-bottom: 1px solid #999;
    background-color: #f0f0f0;
  }
  textarea {
    height: 5rem;
  }
  small {
    color: #999;
  }
  input[type=submit], input[type=reset] {
    padding: 1rem;
    border: none;
    background-color: #6200ee;
    color: #fff;
    border-radius: 0.25rem;
    width: 25%;
  }
  .hidden {
    display: none;
  }
  .text-center {
    text-align: center;
  }
  .error {
    color: red;
  }
</style>

Menemukan nomor dan ID project Cloud

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

    Buka konsol Google Cloud

  2. Klik Setelan dan Utilitas > Setelan project.

  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 Respons insiden dengan Google Chat.
    Buka project
  2. Klik Ringkasan.
  3. Di halaman ringkasan, klik Ikon untuk membuat salinan Buat salinan.
  4. Beri nama salinan project Apps Script Anda:

    1. Klik Salin Respons insiden dengan Google Chat.

    2. Di Project title, ketik Incident Management Chat app.

    3. Klik Ganti nama.

  5. Di salinan project Apps Script, buka file Consts.gs dan ganti YOUR_PROJECT_ID dengan ID project Cloud Anda.

Menetapkan project Cloud project Apps Script

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

Membuat deployment Apps Script

Setelah semua kode siap, deploy project Apps Script. Anda dapat menggunakan ID deployment saat mengonfigurasi aplikasi Chat di Google Cloud.

  1. Di Apps Script, buka project aplikasi respons insiden.

    Buka Apps Script

  2. Klik Deploy > New deployment.

  3. Jika Add-on dan Web app belum dipilih, di samping Select type, klik deployment types Ikon untuk setelan project, lalu pilih Add-on dan Web app.

  4. Di Description, masukkan deskripsi untuk versi ini, seperti Complete version of incident management app.

  5. Di bagian Execute as, pilih Pengguna yang mengakses aplikasi web

  6. Di bagian Siapa yang memiliki akses, pilih Siapa saja dalam organisasi Workspace Anda, dengan "organisasi Workspace Anda" adalah nama organisasi Google Workspace Anda.

  7. Klik Deploy. Apps Script melaporkan deployment yang berhasil dan memberikan ID deployment serta URL untuk halaman web inisialisasi insiden.

  8. Catat URL Aplikasi web untuk dikunjungi nanti saat Anda memulai insiden. Salin ID Deployment. Anda dapat menggunakan ID ini saat mengonfigurasi aplikasi Chat di Konsol Google Cloud.

  9. Klik Done.

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 project Apps Script.

  1. Di konsol Google Cloud, klik Menu > More products > Google Workspace > Product Library > Google Chat API > Manage > Configuration.

    Buka konfigurasi Chat API

  2. Di App name, ketik Incident Management.

  3. Di Avatar URL, ketik https://developers.google.com/chat/images/quickstart-app-avatar.png.

  4. Di Description, ketik Responds to incidents..

  5. Klik tombol Enable Interactive features ke posisi aktif.

  6. Di bagian Functionality, pilih Receive 1:1 messages, Join spaces and group conversations.

  7. Di bawah Connection settings, pilih Apps Script project.

  8. Di ID Deployment, tempel ID Deployment Apps Script yang Anda salin sebelumnya dari deployment project Apps Script.

  9. Daftarkan perintah garis miring yang digunakan oleh aplikasi Chat yang diimplementasikan sepenuhnya:

    1. Di bagian Perintah garis miring, klik Tambahkan perintah garis miring.

    2. Pada Name, ketik /closeIncident.

    3. Di Command ID, ketik 1.

    4. Di Description, ketik Closes the incident being discussed in the space.

    5. Pilih Opens a dialog.

    6. Klik Done. Perintah garis miring telah didaftarkan dan dicantumkan.

  10. Di bagian Visibility, pilih Jadikan aplikasi Chat ini tersedia untuk orang dan grup tertentu di Domain Workspace Anda, lalu masukkan alamat email.

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

  12. Klik Save. Pesan konfigurasi tersimpan akan muncul, yang berarti aplikasi siap diuji.

Menguji aplikasi Chat

Untuk menguji aplikasi Chat manajemen insiden, mulai insiden dari halaman web dan verifikasi bahwa aplikasi Chat berfungsi seperti yang diharapkan:

  1. Buka URL aplikasi web deployment Apps Script.

  2. Saat Apps Script meminta izin untuk mengakses data Anda, klik Tinjau izin, login dengan Akun Google yang sesuai di domain Google Workspace Anda, lalu klik Izinkan.

  3. Halaman web inisialisasi insiden akan terbuka. Masukkan informasi pengujian:

    1. Di Incident title, ketik The First Incident.
    2. Secara opsional, di bagian Perespons insiden, masukkan alamat email rekan petugas respons insiden Anda. Mereka harus merupakan pengguna dengan akun Google Chat di organisasi Google Workspace Anda. Jika tidak, pembuatan ruang akan gagal. Jangan masukkan alamat email Anda sendiri karena disertakan secara otomatis.
    3. Di Initial message, ketik Testing the incident management Chat app.
  4. Klik Create Chat Space. Pesan creating space akan muncul.

  5. Setelah ruang dibuat, pesan Space created! akan muncul. Klik Buka ruang, yang akan membuka ruang di Chat di tab baru.

  6. Secara opsional, Anda dan responden insiden lainnya dapat mengirim pesan di ruang. Aplikasi ini merangkum pesan-pesan tersebut menggunakan Vertex AI dan membagikan dokumen retrospektif.

  7. Untuk mengakhiri respons insiden dan memulai proses penyelesaian, ketik /closeIncident di ruang Chat. Dialog manajemen insiden akan terbuka.

  8. Di bagian Tutup insiden, masukkan deskripsi untuk penyelesaian insiden, seperti Test complete.

  9. Klik Tutup Insiden.

Aplikasi Incident Management mencantumkan pesan dalam ruang, merangkumnya dengan Vertex AI, menempelkan ringkasan dalam dokumen Google Dokumen, dan membagikan dokumen di ruang.

Pembersihan

Agar tidak menimbulkan biaya pada akun Google Cloud Anda untuk resource yang digunakan dalam tutorial ini, sebaiknya hapus project Cloud.

  1. Pada Konsol Google Cloud, buka halaman Kelola resource Klik Menu > IAM & Admin > Manage Resources.

    Buka Resource Manager

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