คู่มือเริ่มต้นฉบับย่อสําหรับส่วนเสริม Google Workspace

จัดทุกอย่างให้เป็นระเบียบอยู่เสมอด้วยคอลเล็กชัน บันทึกและจัดหมวดหมู่เนื้อหาตามค่ากำหนดของคุณ

คู่มือเริ่มใช้งานฉบับย่อนี้จะสร้างส่วนเสริม Google Workspace แบบง่ายๆ ซึ่งแสดงหน้าแรก ทริกเกอร์ตามบริบท และการเชื่อมต่อกับ API ของบุคคลที่สาม

ส่วนเสริมจะสร้างอินเทอร์เฟซตามบริบทและไม่มีบริบทใน Gmail, ปฏิทิน และไดรฟ์ ส่วนเสริมจะแสดงรูปภาพแมวแบบสุ่มที่มีข้อความวางซ้อนบนรูปภาพ ข้อความจะเป็นภาพนิ่งสําหรับหน้าแรก หรือมาจากบริบทแอปพลิเคชันโฮสต์สําหรับทริกเกอร์ตามบริบท

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อม
  • ตั้งค่าสคริปต์
  • เรียกใช้สคริปต์

สิ่งที่ต้องดำเนินการก่อน

หากต้องการใช้ตัวอย่างนี้ คุณต้องมีข้อกําหนดเบื้องต้นต่อไปนี้

  • บัญชี Google (บัญชี Google Workspace อาจต้องได้รับการอนุมัติจากผู้ดูแลระบบ)
  • เว็บเบราว์เซอร์ที่เข้าถึงอินเทอร์เน็ตได้

  • โปรเจ็กต์ Google Cloud

ตั้งค่าสภาพแวดล้อม

เปิดโปรเจ็กต์ที่อยู่ในระบบคลาวด์ใน Google Cloud Console

หากยังไม่ได้เปิด ให้เปิดโปรเจ็กต์ Cloud ที่คุณตั้งใจจะใช้สําหรับตัวอย่างนี้

  1. ไปที่หน้าเลือกโปรเจ็กต์ในคอนโซล Google Cloud

    เลือกโปรเจ็กต์ที่อยู่ในระบบคลาวด์

  2. เลือกโปรเจ็กต์ Google Cloud ที่ต้องการใช้ หรือคลิกสร้างโปรเจ็กต์และทําตามวิธีการบนหน้าจอ หากคุณสร้างโปรเจ็กต์ Google Cloud คุณอาจต้องเปิดการเรียกเก็บเงินสําหรับโปรเจ็กต์

ส่วนเสริมของ Google Workspace ต้องมีการกําหนดค่าหน้าจอขอความยินยอม การกําหนดค่าหน้าจอขอความยินยอม OAuth ของส่วนเสริมจะกําหนดสิ่งที่ Google แสดงต่อผู้ใช้

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และบริการ > หน้าจอขอความยินยอม OAuth

    ไปที่หน้าจอคํายินยอม OAuth

  2. เลือกประเภทผู้ใช้สําหรับแอป แล้วคลิกสร้าง
  3. กรอกแบบฟอร์มการลงทะเบียนแอป แล้วคลิกบันทึกและต่อไป
  4. ในระหว่างนี้ คุณสามารถข้ามการเพิ่มขอบเขต แล้วคลิกบันทึกและต่อไป ในอนาคตเมื่อคุณสร้างแอปสําหรับการใช้งานภายนอกองค์กร Google Workspace คุณต้องเพิ่มและยืนยันขอบเขตการให้สิทธิ์ที่แอปต้องการ

  5. หากเลือกภายนอกสําหรับประเภทผู้ใช้ ให้เพิ่มผู้ใช้ทดสอบ ดังนี้
    1. ในส่วนทดสอบผู้ใช้ ให้คลิกเพิ่มผู้ใช้
    2. ป้อนอีเมลและผู้ใช้ทดสอบคนอื่นๆ ที่ได้รับอนุญาต จากนั้นคลิกบันทึกและดําเนินการต่อ
  6. ดูสรุปการลงทะเบียนแอป หากต้องการทําการเปลี่ยนแปลง ให้คลิกแก้ไข หากการลงทะเบียนแอปถูกต้องแล้ว ให้คลิกกลับไปที่หน้าแดชบอร์ด

ตั้งค่าสคริปต์

สร้างโปรเจ็กต์ Apps Script

  1. หากต้องการสร้างโปรเจ็กต์ Apps Script ใหม่ ให้ไปที่ script.new
  2. คลิกโปรเจ็กต์ที่ไม่มีชื่อ
  3. เปลี่ยนชื่อโครงการ Apps Script Cats แล้วคลิกเปลี่ยนชื่อ
  4. ถัดจากไฟล์ Code.gs ให้คลิกเพิ่มเติม > เปลี่ยนชื่อ ตั้งชื่อไฟล์ว่า Common
  5. คลิกเพิ่มไฟล์ > สคริปต์ ตั้งชื่อไฟล์ว่า Gmail
  6. ทําขั้นตอนที่ 5 ซ้ําเพื่อสร้างไฟล์สคริปต์อีก 2 ไฟล์ชื่อ Calendar และ Drive เมื่อทําเสร็จแล้ว คุณควรมีไฟล์สคริปต์ 4 ไฟล์แยกกัน
  7. แทนที่เนื้อหาของแต่ละไฟล์ด้วยรหัสที่เกี่ยวข้องต่อไปนี้

    Common.gs

      /**
     * This simple Google Workspace Add-on shows a random image of a cat in the
     * sidebar. When opened manually (the homepage card), some static text is
     * overlayed on the image, but when contextual cards are opened a new cat image
     * is shown with the text taken from that context (such as a message's subject
     * line) overlaying the image. There is also a button that updates the card with
     * a new random cat image.
     *
     * Click "File > Make a copy..." to copy the script, and "Publish > Deploy from
     * manifest > Install add-on" to install it.
     */
    
    /**
     * The maximum number of characters that can fit in the cat image.
     */
    var MAX_MESSAGE_LENGTH = 40;
    
    /**
     * Callback for rendering the homepage card.
     * @return {CardService.Card} The card to show to the user.
     */
    function onHomepage(e) {
      console.log(e);
      var hour = Number(Utilities.formatDate(new Date(), e.userTimezone.id, 'H'));
      var message;
      if (hour >= 6 && hour < 12) {
        message = 'Good morning';
      } else if (hour >= 12 && hour < 18) {
        message = 'Good afternoon';
      } else {
        message = 'Good night';
      }
      message += ' ' + e.hostApp;
      return createCatCard(message, true);
    }
    
    /**
     * Creates a card with an image of a cat, overlayed with the text.
     * @param {String} text The text to overlay on the image.
     * @param {Boolean} isHomepage True if the card created here is a homepage;
     *      false otherwise. Defaults to false.
     * @return {CardService.Card} The assembled card.
     */
    function createCatCard(text, isHomepage) {
      // Explicitly set the value of isHomepage as false if null or undefined.
      if (!isHomepage) {
        isHomepage = false;
      }
    
      // Use the "Cat as a service" API to get the cat image. Add a "time" URL
      // parameter to act as a cache buster.
      var now = new Date();
      // Replace forward slashes in the text, as they break the CataaS API.
      var caption = text.replace(/\//g, ' ');
      var imageUrl =
          Utilities.formatString('https://cataas.com/cat/says/%s?time=%s',
              encodeURIComponent(caption), now.getTime());
      var image = CardService.newImage()
          .setImageUrl(imageUrl)
          .setAltText('Meow')
    
      // Create a button that changes the cat image when pressed.
      // Note: Action parameter keys and values must be strings.
      var action = CardService.newAction()
          .setFunctionName('onChangeCat')
          .setParameters({text: text, isHomepage: isHomepage.toString()});
      var button = CardService.newTextButton()
          .setText('Change cat')
          .setOnClickAction(action)
          .setTextButtonStyle(CardService.TextButtonStyle.FILLED);
      var buttonSet = CardService.newButtonSet()
          .addButton(button);
    
      // Create a footer to be shown at the bottom.
      var footer = CardService.newFixedFooter()
          .setPrimaryButton(CardService.newTextButton()
              .setText('Powered by cataas.com')
              .setOpenLink(CardService.newOpenLink()
                  .setUrl('https://cataas.com')));
    
      // Assemble the widgets and return the card.
      var section = CardService.newCardSection()
          .addWidget(image)
          .addWidget(buttonSet);
      var card = CardService.newCardBuilder()
          .addSection(section)
          .setFixedFooter(footer);
    
      if (!isHomepage) {
        // Create the header shown when the card is minimized,
        // but only when this card is a contextual card. Peek headers
        // are never used by non-contexual cards like homepages.
        var peekHeader = CardService.newCardHeader()
          .setTitle('Contextual Cat')
          .setImageUrl('https://www.gstatic.com/images/icons/material/system/1x/pets_black_48dp.png')
          .setSubtitle(text);
        card.setPeekCardHeader(peekHeader)
      }
    
      return card.build();
    }
    
    /**
     * Callback for the "Change cat" button.
     * @param {Object} e The event object, documented {@link
     *     https://developers.google.com/gmail/add-ons/concepts/actions#action_event_objects
     *     here}.
     * @return {CardService.ActionResponse} The action response to apply.
     */
    function onChangeCat(e) {
      console.log(e);
      // Get the text that was shown in the current cat image. This was passed as a
      // parameter on the Action set for the button.
      var text = e.parameters.text;
    
      // The isHomepage parameter is passed as a string, so convert to a Boolean.
      var isHomepage = e.parameters.isHomepage === 'true';
    
      // Create a new card with the same text.
      var card = createCatCard(text, isHomepage);
    
      // Create an action response that instructs the add-on to replace
      // the current card with the new one.
      var navigation = CardService.newNavigation()
          .updateCard(card);
      var actionResponse = CardService.newActionResponseBuilder()
          .setNavigation(navigation);
      return actionResponse.build();
    }
    
    /**
     * Truncate a message to fit in the cat image.
     * @param {string} message The message to truncate.
     * @return {string} The truncated message.
     */
    function truncate(message) {
      if (message.length > MAX_MESSAGE_LENGTH) {
        message = message.slice(0, MAX_MESSAGE_LENGTH);
        message = message.slice(0, message.lastIndexOf(' ')) + '...';
      }
      return message;
    }
    
      

    Gmail.gs

      /**
     * Callback for rendering the card for a specific Gmail message.
     * @param {Object} e The event object.
     * @return {CardService.Card} The card to show to the user.
     */
    function onGmailMessage(e) {
      console.log(e);
      // Get the ID of the message the user has open.
      var messageId = e.gmail.messageId;
    
      // Get an access token scoped to the current message and use it for GmailApp
      // calls.
      var accessToken = e.gmail.accessToken;
      GmailApp.setCurrentMessageAccessToken(accessToken);
    
      // Get the subject of the email.
      var message = GmailApp.getMessageById(messageId);
      var subject = message.getThread().getFirstMessageSubject();
    
      // Remove labels and prefixes.
      subject = subject
          .replace(/^([rR][eE]|[fF][wW][dD])\:\s*/, '')
          .replace(/^\[.*?\]\s*/, '');
    
      // If neccessary, truncate the subject to fit in the image.
      subject = truncate(subject);
    
      return createCatCard(subject);
    }
    
    /**
     * Callback for rendering the card for the compose action dialog.
     * @param {Object} e The event object.
     * @return {CardService.Card} The card to show to the user.
     */
    function onGmailCompose(e) {
      console.log(e);
      var header = CardService.newCardHeader()
          .setTitle('Insert cat')
          .setSubtitle('Add a custom cat image to your email message.');
      // Create text input for entering the cat's message.
      var input = CardService.newTextInput()
          .setFieldName('text')
          .setTitle('Caption')
          .setHint('What do you want the cat to say?');
      // Create a button that inserts the cat image when pressed.
      var action = CardService.newAction()
          .setFunctionName('onGmailInsertCat');
      var button = CardService.newTextButton()
          .setText('Insert cat')
          .setOnClickAction(action)
          .setTextButtonStyle(CardService.TextButtonStyle.FILLED);
      var buttonSet = CardService.newButtonSet()
          .addButton(button);
      // Assemble the widgets and return the card.
      var section = CardService.newCardSection()
          .addWidget(input)
          .addWidget(buttonSet);
      var card = CardService.newCardBuilder()
          .setHeader(header)
          .addSection(section);
      return card.build();
    }
    
    /**
     * Callback for inserting a cat into the Gmail draft.
     * @param {Object} e The event object.
     * @return {CardService.UpdateDraftActionResponse} The draft update response.
     */
    function onGmailInsertCat(e) {
      console.log(e);
      // Get the text that was entered by the user.
      var text = e.formInput.text;
      // Use the "Cat as a service" API to get the cat image. Add a "time" URL
      // parameter to act as a cache buster.
      var now = new Date();
      var imageUrl = 'https://cataas.com/cat';
      if (text) {
        // Replace forward slashes in the text, as they break the CataaS API.
        var caption = text.replace(/\//g, ' ');
        imageUrl += Utilities.formatString('/says/%s?time=%s',
            encodeURIComponent(caption), now.getTime());
      }
      var imageHtmlContent = '<img style="display: block; max-height: 300px;" src="'
          + imageUrl + '"/>';
      var response = CardService.newUpdateDraftActionResponseBuilder()
          .setUpdateDraftBodyAction(CardService.newUpdateDraftBodyAction()
              .addUpdateContent(imageHtmlContent,CardService.ContentType.MUTABLE_HTML)
              .setUpdateType(CardService.UpdateDraftBodyType.IN_PLACE_INSERT))
          .build();
      return response;
    }
    
      

    Calendar.gs

      /**
     * Callback for rendering the card for a specific Calendar event.
     * @param {Object} e The event object.
     * @return {CardService.Card} The card to show to the user.
     */
    function onCalendarEventOpen(e) {
      console.log(e);
      var calendar = CalendarApp.getCalendarById(e.calendar.calendarId);
      // The event metadata doesn't include the event's title, so using the
      // calendar.readonly scope and fetching the event by it's ID.
      var event = calendar.getEventById(e.calendar.id);
      if (!event) {
        // This is a new event still being created.
        return createCatCard('A new event! Am I invited?');
      }
      var title = event.getTitle();
      // If necessary, truncate the title to fit in the image.
      title = truncate(title);
      return createCatCard(title);
    }
    
      

    Drive.gs

      /**
     * Callback for rendering the card for specific Drive items.
     * @param {Object} e The event object.
     * @return {CardService.Card} The card to show to the user.
     */
    function onDriveItemsSelected(e) {
      console.log(e);
      var items = e.drive.selectedItems;
      // Include at most 5 items in the text.
      items = items.slice(0, 5);
      var text = items.map(function(item) {
        var title = item.title;
        // If neccessary, truncate the title to fit in the image.
        title = truncate(title);
        return title;
      }).join('\n');
      return createCatCard(text);
    }
    
      

  8. คลิกการตั้งค่าโปรเจ็กต์ ไอคอนสําหรับการตั้งค่าโปรเจ็กต์

  9. เลือกช่องแสดงไฟล์ Manifest "appsscript.json" ในเครื่องมือแก้ไข

  10. คลิกตัดต่อวิดีโอ

  11. เปิดไฟล์ appsscript.json และแทนที่เนื้อหาด้วยโค้ดต่อไปนี้ แล้วคลิกบันทึก ไอคอน &quot;บันทึก&quot;

    appscript.json

       {
      "timeZone": "America/New_York",
      "dependencies": {
      },
      "exceptionLogging": "STACKDRIVER",
      "oauthScopes": [
        "https://www.googleapis.com/auth/calendar.addons.execute",
        "https://www.googleapis.com/auth/calendar.readonly",
        "https://www.googleapis.com/auth/drive.addons.metadata.readonly",
        "https://www.googleapis.com/auth/gmail.addons.current.action.compose",
        "https://www.googleapis.com/auth/gmail.addons.current.message.readonly",
        "https://www.googleapis.com/auth/gmail.addons.execute",
        "https://www.googleapis.com/auth/script.locale"],
      "runtimeVersion": "V8",
      "addOns": {
        "common": {
          "name": "Cats",
          "logoUrl": "https://www.gstatic.com/images/icons/material/system/1x/pets_black_48dp.png",
          "useLocaleFromApp": true,
          "homepageTrigger": {
            "runFunction": "onHomepage",
            "enabled": true
          },
          "universalActions": [{
            "label": "Learn more about Cataas",
            "openLink": "https://cataas.com"
          }]
        },
        "gmail": {
          "contextualTriggers": [{
            "unconditional": {
            },
            "onTriggerFunction": "onGmailMessage"
          }],
          "composeTrigger": {
            "selectActions": [{
              "text": "Insert cat",
              "runFunction": "onGmailCompose"
            }],
            "draftAccess": "NONE"
          }
        },
        "drive": {
          "onItemsSelectedTrigger": {
            "runFunction": "onDriveItemsSelected"
          }
        },
        "calendar": {
          "eventOpenTrigger": {
            "runFunction": "onCalendarEventOpen"
          }
        }
      }
    }
    
      

คัดลอกหมายเลขโปรเจ็กต์ Cloud

  1. ไปที่โปรเจ็กต์ Cloud ในคอนโซล Google Cloud
  2. คลิกการตั้งค่าและยูทิลิตี > การตั้งค่าโปรเจ็กต์
  3. คัดลอกหมายเลขโปรเจ็กต์

ตั้งโปรเจ็กต์ที่อยู่ในระบบคลาวด์ของ Apps Script

  1. ในโปรเจ็กต์ Apps Script ให้คลิกการตั้งค่าโปรเจ็กต์ ไอคอนสําหรับการตั้งค่าโปรเจ็กต์
  2. ในส่วนโปรเจ็กต์ Google Cloud Platform (GCP) ให้คลิกเปลี่ยนโปรเจ็กต์
  3. วางหมายเลขโปรเจ็กต์ Google Cloud ในหมายเลขโปรเจ็กต์ GCP
  4. คลิกตั้งค่าโปรเจ็กต์

ติดตั้งการทําให้ใช้งานได้ของการทดสอบ

  1. คลิกเอดิเตอร์ ในโปรเจ็กต์ Apps Script
  2. เปิดไฟล์ Common.gs แล้วคลิกเรียกใช้ ให้สิทธิ์สคริปต์เมื่อได้รับแจ้ง
  3. คลิกการทําให้ใช้งานได้ > ทดสอบการติดตั้งใช้งาน
  4. คลิกติดตั้ง > เสร็จสิ้น

เรียกใช้สคริปต์

  1. ไปที่ Gmail
  2. หากต้องการเปิดส่วนเสริม ให้คลิก "แมว" ในแผงด้านขวา
  3. ให้สิทธิ์ส่วนเสริมหากได้รับแจ้ง
  4. ส่วนเสริมจะแสดงรูปภาพและข้อความแมว หากต้องการเปลี่ยนรูปภาพ ให้คลิกเปลี่ยนแมว
  5. หากคุณเปิดอีเมลขณะที่ส่วนเสริมเปิดอยู่ รูปภาพจะรีเฟรชและข้อความจะเปลี่ยนเป็นบรรทัดเรื่องของอีเมล (ถูกตัดหากยาวเกินไป)

คุณจะเห็นฟังก์ชันที่คล้ายกันนี้ในปฏิทินและไดรฟ์ คุณไม่จําเป็นต้องให้สิทธิ์ส่วนเสริมนี้ซ้ําเพื่อใช้กับแอปโฮสต์เหล่านั้น

ขั้นตอนถัดไป