Google Workspace ऐड-ऑन क्विकस्टार्ट

यह क्विकस्टार्ट, एक आसान Google Workspace ऐड-ऑन बनाता है. यह होम पेज, कॉन्टेक्स्ट के हिसाब से ट्रिगर, और तीसरे पक्ष के एपीआई से कनेक्ट करने के बारे में बताता है.

ऐड-ऑन, Gmail, Calendar, और Drive में कॉन्टेक्स्ट के हिसाब से और नॉन-कॉन्टेक्स्ट के इंटरफ़ेस बनाता है. ऐड-ऑन में किसी बिल्ली की एक रैंडम इमेज दिखती है, जिसकी इमेज पर टेक्स्ट ओवरले होता है. होम पेज के लिए टेक्स्ट स्टैटिक होता है या कॉन्टेक्स्ट के ट्रिगर के लिए, होस्ट ऐप्लिकेशन के कॉन्टेक्स्ट से लिया जाता है.

मकसद

  • अपना एनवायरमेंट सेट अप करें.
  • स्क्रिप्ट सेट अप करें.
  • स्क्रिप्ट चलाएं.

ज़रूरी शर्तें

इस सैंपल का इस्तेमाल करने के लिए, आपको ये ज़रूरी शर्तें पूरी करनी होंगी:

  • Google खाता (Google Workspace खातों के लिए एडमिन की अनुमति ज़रूरी हो सकती है).
  • इंटरनेट ऐक्सेस करने वाला वेब ब्राउज़र.

  • Google Cloud प्रोजेक्ट.

अपना एनवायरमेंट सेट अप करें

Google Cloud Console में अपना Cloud प्रोजेक्ट खोलें

अगर यह पहले से नहीं खुला है, तो वह Cloud प्रोजेक्ट खोलें जिसे आपको इस सैंपल के लिए इस्तेमाल करना है:

  1. Google Cloud Console में, कोई प्रोजेक्ट चुनें पेज पर जाएं.

    Cloud प्रोजेक्ट चुनें

  2. वह Google Cloud प्रोजेक्ट चुनें जिसका आपको इस्तेमाल करना है. या प्रोजेक्ट बनाएं पर क्लिक करके, स्क्रीन पर दिए गए निर्देशों का पालन करें. अगर आपने Google Cloud प्रोजेक्ट बनाया है, तो आपको प्रोजेक्ट के लिए बिलिंग चालू करनी पड़ सकती है.

Google Workspace ऐड-ऑन के लिए, ऐसी स्क्रीन कॉन्फ़िगरेशन की ज़रूरत होती है जिसके लिए सहमति दी जाती है. अपने ऐड-ऑन की OAuth सहमति स्क्रीन को कॉन्फ़िगर करने से यह तय होता है कि Google, उपयोगकर्ताओं को क्या दिखाएगा.

  1. Google Cloud Console में, मेन्यू > एपीआई और सेवाएं > OAuth की सहमति वाली स्क्रीन पर जाएं.

    ऐसी स्क्रीन पर जाएं जहां OAuth के लिए सहमति दी जाती है

  2. उपयोगकर्ता टाइप के लिए, अंदरूनी चुनें. इसके बाद, बनाएं पर क्लिक करें.
  3. ऐप्लिकेशन रजिस्ट्रेशन फ़ॉर्म भरें. इसके बाद, सेव करें और जारी रखें पर क्लिक करें.
  4. फ़िलहाल, दायरों को छोड़कर आगे बढ़ा जा सकता है. साथ ही, सेव करें और जारी रखें पर क्लिक करें. आने वाले समय में, जब अपने Google Workspace संगठन से बाहर इस्तेमाल करने के लिए कोई ऐप्लिकेशन बनाया जाएगा, तो आपको उपयोगकर्ता टाइप को बाहरी उपयोगकर्ता में बदलना होगा. इसके बाद, आपको अपने ऐप्लिकेशन के लिए ज़रूरी अनुमति के दायरे जोड़ने होंगे.

  5. अपने ऐप्लिकेशन रजिस्ट्रेशन की खास जानकारी देखें. बदलाव करने के लिए, बदलाव करें पर क्लिक करें. अगर ऐप्लिकेशन रजिस्ट्रेशन ठीक लग रहा है, तो डैशबोर्ड पर वापस जाएं पर क्लिक करें.

स्क्रिप्ट सेट अप करें

Apps Script प्रोजेक्ट बनाना

  1. नया Apps Script प्रोजेक्ट बनाने के लिए, script.new पर जाएं.
  2. बिना टाइटल वाला प्रोजेक्ट पर क्लिक करें.
  3. Apps Script प्रोजेक्ट का नाम बिल्लियां रखें और नाम बदलें पर क्लिक करें.
  4. Code.gs फ़ाइल के बगल में, ज़्यादा > नाम बदलें पर क्लिक करें. फ़ाइल को Common नाम दें.
  5. फ़ाइल जोड़ें > स्क्रिप्ट पर क्लिक करें. फ़ाइल को Gmail नाम दें.
  6. 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. "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"
          }
        }
      }
    }
    
      

Cloud प्रोजेक्ट नंबर कॉपी करें

  1. Google Cloud Console में, मेन्यू > IAM और एडमिन > सेटिंग पर जाएं.

    IAM और एडमिन सेटिंग पर जाएं

  2. प्रोजेक्ट नंबर फ़ील्ड में, वैल्यू कॉपी करें.

Apps Script प्रोजेक्ट का क्लाउड प्रोजेक्ट सेट करें

  1. अपने Apps Script प्रोजेक्ट में, प्रोजेक्ट सेटिंग प्रोजेक्ट सेटिंग का आइकॉन पर क्लिक करें.
  2. Google Cloud Platform (GCP) प्रोजेक्ट में जाकर, प्रोजेक्ट बदलें पर क्लिक करें.
  3. GCP प्रोजेक्ट नंबर में, Google Cloud प्रोजेक्ट नंबर चिपकाएं.
  4. प्रोजेक्ट सेट करें पर क्लिक करें.

टेस्ट डिप्लॉयमेंट इंस्टॉल करें

  1. अपने Apps Script प्रोजेक्ट में, एडिटर पर क्लिक करें.
  2. Common.gs फ़ाइल खोलें और Run पर क्लिक करें. जब कहा जाए, तब स्क्रिप्ट को अनुमति दें.
  3. डिप्लॉयमेंट > डिप्लॉयमेंट की जांच करें पर क्लिक करें.
  4. इंस्टॉल करें > हो गया पर क्लिक करें.

स्क्रिप्ट चलाएं

  1. Gmail पर जाएं.
  2. ऐड-ऑन खोलने के लिए, दाईं ओर मौजूद साइड पैनल में, बिल्लियां पर क्लिक करें.
  3. अगर कहा जाए, तो ऐड-ऑन को अनुमति दें.
  4. ऐड-ऑन में बिल्ली की इमेज और टेक्स्ट दिखता है. इमेज बदलने के लिए, बिल्ली बदलें पर क्लिक करें.
  5. अगर ऐड-ऑन खुला होने पर कोई ईमेल खोला जाता है, तो इमेज रीफ़्रेश हो जाती है और टेक्स्ट, ईमेल की सब्जेक्ट लाइन में बदल जाता है. अगर वह बहुत लंबा है, तो उसे छोटा कर दिया जाता है.

आपको Calendar और Drive में, ऐसी ही सुविधाएं दिखेंगी. आपको होस्ट किए गए ऐप्लिकेशन में ऐड-ऑन का इस्तेमाल करने के लिए, फिर से अनुमति देने की ज़रूरत नहीं है.

अगले चरण