AppsScriptPulse

Taming the Timeout: A Robust Webhook Strategy for Apps Script from Max Makhrov

Webhooks are a powerful way for developers to connect different applications, allowing them to automatically send data to a Google Apps Script project whenever an event occurs. However, this powerful technique comes with a significant challenge: if your script takes too long to process an incoming request, the sending service will time out, leading to lost data and unreliable automations.

In a recent article, Google Workspace Developer Max Makhrov shares a clever and effective architecture designed to make your webhooks both fast and reliable.

The Problem: When a Few Seconds is Too Long

The core issue is that services sending webhooks—like GitHubShopify, or Stripe—expect a nearly instant 200 OK response. These services have strict timeout policies, often between 5 to 10 seconds. If your doPost(e) function is busy with complex logic, writing to a spreadsheet, or making other API calls, it can easily fail to respond in time, causing the service to report a delivery failure.

The Solution: Cache Now, Process Later

Max’s approach decouples the initial reception of data from the heavy processing. The strategy is elegantly simple:

  1. Immediate Caching: The doPost(e) function is kept lean. Its only job is to immediately write the raw, incoming webhook data to Apps Script’s CacheService.
  2. Instant Response: With the data safely stored, the function quickly returns a success message, satisfying the sending service well within its required timeout window.
  3. Asynchronous Processing: A separate, time-driven trigger runs another function on a regular schedule (e.g., every minute). This function retrieves one or more tasks from the cache and performs the long-running processes.

To manage the tasks in the cache, Max introduces the concept of using a lightweight collection, which allows multiple webhook payloads to be queued and processed in an orderly fashion. Crucially, this pattern also uses LockService to prevent multiple processing functions from running simultaneously and trying to handle the same data.

While CacheService is perfect for this, it’s important to remember its limits: the 100KB size limit per item can be a challenge for webhooks with large payloads, and items expire after 10 minutes, so your processing trigger must run frequently enough to handle the workload.

It’s worth noting that this “fire and forget” pattern is ideal for notification-style webhooks, where the sending service only needs a 200 OK status to confirm receipt. For interactive webhooks that require a specific JSON response to be sent back immediately (like a Slack command), this asynchronous approach would not be suitable.

Here is a look at the lean doPost(e) function that captures the incoming data:

function doPost(e) {  
  try {  
    // Immediately write the raw payload to CacheService  
    writeHook2Cache\_(e);  
  } catch (err) {  
    // If caching fails, log the error  
    set2Memory\_(webhookKeys.error, err);  
  }  
  // Instantly return a 200 OK success response  
  return ContentService  
   .createTextOutput(JSON.stringify({status: 'success'}))  
   .setMimeType(ContentService.MimeType.JSON);  
}

This asynchronous architecture is a powerful pattern for any developer building robust integrations.

A big thank you to Max Makhrov for sharing this valuable technique with the community! You can find a more detailed explanation and links to the complete code on his Medium page.

Source: Using Collections for Handling Web-Hooks with App Script

Google Sheets [🔧Fixed]. Prevent users from deleting formulas with Google Apps Script

You’ve made a formula, but someone deleted it. It may be annoying to restore your formula. You are not always able to protect a range with formulas, as protection will also forbid users from sorting range, adding new rows, hiding rows, etc.

Let’s create our formula protection with the help of a few formulas and app script code.

Google Sheets are fantastic for collaboration, the downside however can be that other people can break stuff. The Protected Sheets and Ranges can help with this, but there might be times when you need an alternative solution. If you find yourself in this situation Max Makhrov has come to the rescue with a solution to rewrite formula if they are accidentally deleted. You can find out more in the source post link. As a bonus Max includes a named Google Sheets function, FormulasMap, which can be used to export functions in a range to another sheet.

Image credit:
Max Makhrov

 

Source: Google Sheets [🔧Fixed]. Prevent users from deleting formulas

Apps Script Pattern. Stop Script Execution on conditions from a Google Sheet

The common pattern for checking the business logic before executing automation

Here’s a clever little snippet from Max Makhrov which combines Google Apps Script with conditional logic created using Google Sheets functions, the resulting cell value being used for the error message.

/**
 * @param {String} rangeName
 * 
 * @returns {Boolean} toStopExecution
 */
function getStopMessageBoxFromNamedRange_(rangeName) {
  var ss = SpreadsheetApp.getActive();
  var r = ss.getRangeByName(rangeName);
  var v = r.getValue();
  if (v === '') {
    return false;
  }
  var stopHeader = 'The script was stopped';
  Browser.msgBox(stopHeader, v, Browser.Buttons.OK);
  return true;
}

If after reading Max’s post you are unsure how this works, here is an example Google Sheet with some test data and logic as well as a ‘My Menu’ open to test the bound script.

Source: Apps Script Pattern. Stop Script Execution on conditions from Sheet

5 steps to deploying Google Workspace Editors Add-ons to the Google Workspace Marketplace

This guide is not documentation, but a condensed reminder of what you must do.

Max Makhrov has put together this very succinct guide to publishing Google Workspace Editor Add-ons to the Google Workspace Marketplace. As explained by Max the guide isn’t a step-by-step tutorial, but instead provides the key steps you should remember to do. There are some great tips in this post, particularly around what to include in the recorded screencast required by the Google oAuth verification team.

Source: 5 STEPS to Deploy Google Sheets External Editors add-on

Custom function for get subtotals for each group in Google Sheets using Google Apps Script

You get subtotal sums for each of the selected columns.

The code speaks for itself in this post from Max Makhrov in which he shows how to create a custom function for Google Sheets to subtotal groups of columns. There is some impressive data manipulation/reshaping going on in the function and some nice use of using arrays in formula created with brackets { }. Some of the code is also written with OpenAI/ChatGPT (I’m guessing anything with a for loop). The icing on top is the conditional formatting for group totals. Follow the source link for all the code.

Source: Subtotals for each group in Google Sheets

📮`MMailApp` for Google Apps Script: GmailApp+MailApp+Gmail API

The library lets you send emails, using MailApp, GmailApp, and Gmail API. The library takes care of parameters, so you do not need to care about which method to use. I had trouble with my project when I wanted to automatically send emails and suddenly for me we’ve reached the daily limit. This is why I’ve decided to make some research and be sure fewer bad things happen in the future.

If you are looking for a deep dive into Google Apps Script powered email sending options you are at the door of enlightenment. In this post from Max Makrov you not only to get an explanation of the options and benefits for sending email with MailApp, GmailApp and the Gmail API, but also a handy library, MmailApp. which makes it easy to switch between all three.

Source: 📮`MMailApp` for Google Apps Script: GmailApp+MailApp+Gmail API

Sending emails with Amazon AWS Simple Email Service (SES) with Google Apps Script

This week was the first time I’ve tried AWS. I wanted to test AWS SES to write some emails with the help of Amazon. The learning curve was painful for me because I was totally lost in the documentation. Here’s what I came through

Max Makhrov is on a role with Google Apps Script and Google Sheets development. As well as this latest Medium post looking at Amazon AWS Simple Email Service (or as Max discovered – ‘Not so Simple Email Service’) if not already well worth following Max on Twitter (@max__makhrov) for lots of very useful Google Sheets/Script tips.

If you are hitting your quotas on Google Workspace daily email sends using AWS SES could be one solution. If you want to avoid the bold banners in recipients inboxes here’s some additional required reading on How to Set Up AWS SES and Avoid Spam Folders is essential reading. This covers setting up DNS records for SPF, DKIM, DMARC when using AWS SES. As these changes are required at a DNS level it’s not possible to set this up on regular @gmail.com accounts.

Source: Send Emails with Amazon AWS SES from Google Scripts

Google Apps Script library if you need to get a Google Sheet as a PDF

Library for converting Google Sheets Into PDF

Features:

  • All PDF settings including colontitles = custom headers and footers.
  • Input parameters is a single plain object.

The library uses the printing features of Google Spreadsheets to provide a complete representation of a document in a different format. It contains a huge amount of features There are settings such as page size, headers and footers, colontitles, gridlines, notes and more.

Source: Max-Makhrov/sheets2pdf_gs: Library for converting Google Sheets Into PDF

Using Google Apps Script to convert a Google Sheets selected range to an image 

Convert selected range into PNG image and save it to Drive

In this post from Max Makhrov you can discover how you can convert a selected Google Sheets range to an image. With options to embed charts and tables in Google Docs and Slides you might be asking why you would want to do this. Max highlights a couple of great reasons:

There are some limitations with this approach which are outlined in the post and if you have any solutions there is a link to contribute to the GitHub repo.

Source: Google Sheets Script. Range 2 Image

Dependent dropdown lists for Google Sheets (and lots of other Google Apps Script goodies)

Updated the script for dependent lists, and now it supports new options. New for 2022:

Dependent drop-down lists can be used to create a dynamic list of choices in Google Sheets. When the user makes a selection from the first drop-down list, the choices in the second drop-down list will be updated based on the selection. This can be used to create a cascading list of choices.

If you are looking for a nice solution to build dependent drop-down lists in Google Sheets this is a great solution from Max Makhrov. For more experienced Google Apps Script developers the solution incorporates some clever snippets both from Max and a number of other members of the community. Some highlights include: converting a column index into corresponding column letter; a tasker to batch apply updates to a Google Sheet; ChuckyCache for objects above 100Kb; and a reference to a zip compression solution. All these are referenced in the source code provided in the post.

Source: Dependent Drop-Down Lists For Google Sheets v2022