با Apps Script یک افزونه Google Workspace بسازید

این راهنمای سریع، یک افزونه ساده Google Workspace ایجاد می‌کند که صفحات اصلی، محرک‌های زمینه‌ای و اتصال به APIهای شخص ثالث را نشان می‌دهد.

این افزونه رابط‌های متنی و غیر متنی را در Gmail، Calendar و Drive ایجاد می‌کند. این افزونه یک تصویر تصادفی از یک گربه را با متنی که روی تصویر قرار دارد نمایش می‌دهد. متن یا برای صفحات اصلی ثابت است یا برای محرک‌های متنی از متن برنامه میزبان گرفته می‌شود.

اهداف

  • محیط خود را تنظیم کنید.
  • اسکریپت را تنظیم کنید.
  • اسکریپت را اجرا کنید.

پیش‌نیازها

برای استفاده از این نمونه، به پیش‌نیازهای زیر نیاز دارید:

  • یک حساب گوگل (حساب‌های کاربری گوگل ورک‌اسپیس ممکن است نیاز به تأیید مدیر داشته باشند).
  • یک مرورگر وب با دسترسی به اینترنت.

  • یک پروژه ابری گوگل .

محیط خود را تنظیم کنید

پروژه ابری خود را در کنسول گوگل کلود باز کنید

اگر هنوز باز نشده است، پروژه ابری که قصد دارید برای این نمونه استفاده کنید را باز کنید:

  1. در کنسول گوگل کلود، به صفحه انتخاب پروژه بروید.

    یک پروژه ابری انتخاب کنید

  2. پروژه گوگل کلود مورد نظر خود را انتخاب کنید. یا روی ایجاد پروژه کلیک کنید و دستورالعمل‌های روی صفحه را دنبال کنید. اگر یک پروژه گوگل کلود ایجاد می‌کنید، ممکن است لازم باشد پرداخت هزینه را برای آن پروژه فعال کنید .

افزونه‌های Google Workspace نیاز به پیکربندی صفحه رضایت دارند. پیکربندی صفحه رضایت OAuth افزونه شما، آنچه گوگل به کاربران نمایش می‌دهد را تعریف می‌کند.

  1. در کنسول گوگل کلود، به Menu > برویدGoogle Auth platform > برندسازی .

    به بخش برندسازی بروید

  2. اگر قبلاً تنظیمات را انجام داده‌اید Google Auth platformمی‌توانید تنظیمات صفحه رضایت OAuth زیر را در Branding ، Audience و Data Access پیکربندی کنید. اگر پیامی با این مضمون مشاهده کردید Google Auth platform هنوز پیکربندی نشده است ، روی شروع کار کلیک کنید:
    1. در قسمت اطلاعات برنامه ، در قسمت نام برنامه ، نامی برای برنامه وارد کنید.
    2. در ایمیل پشتیبانی کاربر ، یک آدرس ایمیل پشتیبانی انتخاب کنید که کاربران در صورت داشتن هرگونه سوال در مورد رضایت خود بتوانند با شما تماس بگیرند.
    3. روی بعدی کلیک کنید.
    4. در قسمت مخاطبان ، داخلی (Internal) را انتخاب کنید.
    5. روی بعدی کلیک کنید.
    6. در قسمت اطلاعات تماس ، یک آدرس ایمیل وارد کنید که از طریق آن بتوانید از هرگونه تغییر در پروژه خود مطلع شوید.
    7. روی بعدی کلیک کنید.
    8. در قسمت Finish ، سیاست داده‌های کاربر سرویس‌های API گوگل را مرور کنید و در صورت موافقت، گزینه «من با سیاست‌های داده‌های کاربر سرویس‌های API گوگل موافقم» را انتخاب کنید.
    9. روی ادامه کلیک کنید.
    10. روی ایجاد کلیک کنید.
  3. فعلاً می‌توانید از اضافه کردن محدوده‌ها صرف نظر کنید. در آینده، وقتی برنامه‌ای برای استفاده در خارج از سازمان Google Workspace خود ایجاد می‌کنید، باید نوع کاربر (User type) را به خارجی (External) تغییر دهید. سپس محدوده‌های مجوز مورد نیاز برنامه خود را اضافه کنید. برای کسب اطلاعات بیشتر، به راهنمای کامل پیکربندی رضایت OAuth مراجعه کنید.

اسکریپت را تنظیم کنید

پروژه Apps Script را ایجاد کنید

  1. برای ایجاد یک پروژه جدید Apps Script، به script.new بروید.
  2. روی پروژه بدون عنوان کلیک کنید.
  3. نام پروژه Apps Script را به Cats تغییر دهید و روی Rename کلیک کنید.
  4. در کنار فایل Code.gs ، روی More > Rename کلیک کنید. نام فایل را Common بگذارید.
  5. روی فایل > اسکریپت کلیک کنید. نام فایل را Gmail قرار دهید.
  6. مرحله ۵ را برای ایجاد ۲ فایل اسکریپت دیگر با نام‌های Calendar و Drive تکرار کنید. وقتی این کار را انجام دادید، باید ۴ فایل اسکریپت جداگانه داشته باشید.
  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;
    }
    
      

    جیمیل.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;
    }
    
      

    تقویم.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);
    }
    
      

    درایو.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. تیک گزینه‌ی «نمایش فایل مانیفست "appsscript.json" در ویرایشگر» را بزنید.

  10. روی ویرایشگر کلیک کنید.

  11. فایل appsscript.json را باز کنید و محتویات آن را با کد زیر جایگزین کنید، سپس روی ذخیره کلیک کنید. آیکون ذخیره .

    appsscript.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"
          }
        }
      }
    }
    
      

شماره پروژه ابری را کپی کنید

  1. در کنسول گوگل کلود، به Menu > IAM & Admin > Settings بروید.

    به تنظیمات IAM و مدیریت بروید

  2. در فیلد شماره پروژه ، مقدار را کپی کنید.

پروژه Cloud مربوط به پروژه Apps Script را تنظیم کنید.

  1. در پروژه Apps Script خود، روی تنظیمات پروژه کلیک کنید. آیکون مربوط به تنظیمات پروژه .
  2. در زیر پروژه پلتفرم ابری گوگل (GCP) ، روی تغییر پروژه کلیک کنید.
  3. در قسمت شماره پروژه GCP ، شماره پروژه Google Cloud را وارد کنید.
  4. روی تنظیم پروژه کلیک کنید.

نصب یک نسخه آزمایشی

  1. در پروژه Apps Script خود، روی Editor کلیک کنید.
  2. روی استقرار > آزمایش استقرارها کلیک کنید.
  3. روی نصب > انجام شد کلیک کنید.

اسکریپت را اجرا کنید

  1. به جیمیل بروید.
  2. برای باز کردن افزونه، در پنل سمت راست، روی «گربه‌ها، کلیک کنید.
  3. در صورت درخواست، افزونه را تأیید کنید.
  4. این افزونه تصویر و متن گربه را نمایش می‌دهد. برای تغییر تصویر، روی «تغییر گربه» کلیک کنید.
  5. اگر در حین باز بودن افزونه، ایمیلی را باز کنید، تصویر رفرش می‌شود و متن به خط موضوع ایمیل تغییر می‌کند (اگر خیلی طولانی باشد، کوتاه می‌شود).

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

مراحل بعدی