5
votes

I have a VBA script which converts an Excel file to a PDF then saves it to a Google drive folder via Google Drive desktop sync.

What I would like to do is then have a Google script trigger monitor the given folder and each time a file is saved there it runs a script to email the file. I I have the script working fine when running on a time based trigger, every 15 minutes, but would prefer a realtime solution.

So i'm after like a onChange() trigger but for Google Drive.

possible?

thanks

3

3 Answers

5
votes

This should be possible with the Push Notifications API of Google Drive. See this link for details.

Push Notifications

This document describes how to use push notifications that inform your application when a resource changes.

Overview

The Drive API provides push notifications that let you watch for changes to resources. You can use this feature to improve the performance of your application. It allows you to eliminate the extra network and compute costs involved with polling resources to determine if they have changed. Whenever a watched resource changes, the Drive API notifies your application. To use push notifications, you need to do two things:

  • Set up your receiving URL, or "Webhook" callback receiver.
  • This is an HTTPS server that handles the API notification messages that are triggered when a resource changes.
  • Set up a notification channel for each resource endpoint you want to watch.
    A channel specifies routing information for notification messages. As part of the channel setup, you identify the specific URL where you want to receive notifications. Whenever a channel's resource changes, the Drive API sends a notification message as a POST request to that URL.

Currently, the Drive API supports notifications for changes to the Files and Changes resources.

1
votes

That kind of script trigger is not currently possible with GAS. You'll have to run a time-based script which keeps checking.

0
votes

I found this blog and with a few modifications it worked for me:

function setupTrigger(){
  let oneMinuteAgo = new Date(new Date().getTime() - 1 * 60 * 1000).toISOString();  
  let files = DriveApp.searchFiles('("1w0P5s5-BAlWB1EIr124h3wFPha_q6BPt" in parents) and (modifiedDate > "' + oneMinuteAgo + '")');
  while (files.hasNext()){
    let file = files.next();
  }
}

where 1w0P5s5-BAlWB1EIr124h3wFPha_q6BPt is the folder ID where I am uploading the files. Be aware that the modifiedDate implies the modification date of the file (so if you created a file a day ago then the modifiedDate would indicate a day ago, not the upload date).