Trigger webhook on new file upload on Google Drive

Google Drive app on Make doesn’t offer an instant trigger on file uploads – so you either has to schedule your scenario and waste a lot of check runs or you do some other sourcery to trigger it on demand.

Well… I’ve searched and found out a way to use Google Apps Script to do this recurrent check on a Google Drive folder – so it fires a Make webhook that you can then use to start your scenario.

In order for this to work, go to script.google.com and create a new project.
Paste in this code:

// Replace 'myFolderID' with the actual ID of your folder and 'https://mysample.webhook.com' with your webhook URL
const folderId = 'myFolderID';
const webhookUrl = 'https://mysample.webhook.com';

const cache = CacheService.getScriptCache();

function isRecentlyCreated(file) {
  const now = new Date();
  const threshold = 60 * 1000; // Check for files created in the last minute (adjust as needed)
  return now - file.getLastUpdated() < threshold;
}

function checkForNewFiles() {
  const folder = DriveApp.getFolderById(folderId);
  const files = folder.getFiles();
  
  let newFilesFound = false;
  
  while (files.hasNext()) {
    const file = files.next();
    const fileId = file.getId();
    
    // Check cache for processed fileId
    if (!cache.get(fileId)) {
      if (isRecentlyCreated(file)) {
        const payload = { fileId };
        UrlFetchApp.fetch(webhookUrl, {
          method: 'post',
          contentType: 'application/json',
          payload: JSON.stringify(payload)
        });
        cache.put(fileId, 'processed', 60 * 60); // Cache processed fileId for 1 hour
        console.log(`New file found: ${fileId}`);
        newFilesFound = true;
      }
    } else {
      console.log(`File ${fileId} already processed`);
    }
  }
  
  if (!newFilesFound) {
    console.log('No new files found');
  }
}

function startMonitoring() {
  // Schedule a function to check for new files periodically (e.g., every minute)
  ScriptApp.newTrigger('checkForNewFiles')
      .timeBased()
      .everyMinutes(1)
      .create();
}

function main() {
  startMonitoring();
}


Also, click on the “Resources” section, on the left-side panel and add the Drive API.
Then, select the function “main” on the menu at the top and click “Execute” to run it. You’ll first will be prompted to authorize the script with your credentials, then click “Execute” again to create the trigger.

In order to see if this is working or not, go to the “Triggers” section (on the left-side panel) and check if there is a trigger created.
You can also see all the events executions in the “Executions” section.

Note: this will check for the file modification date – so it works for files recently created or modified – so take that in mind.

Hope it helps!

10 Likes

Thanks Hugo,
This have been a game changer :slight_smile: Thanks a lot.
Does google charge for checking the files. If it is I’ll change the time from every 5min to longer.
Thanks again. Great post.

1 Like

No, but there are limits, although you are unlikely to hit them with just a single script.

2 Likes

@samliew already got it – so there are limits.
The code is with 1 minute interval, I hardly think you need this much checking (I’ve set it with 1 minute only to test, now I’m using with 10 minute interval).

In any case, the idea here is to save some operations, and this will definitely do the trick!
Glad it helped!

1 Like

This is amazing thank you soooooo much for sharing!!

Where is this section “Then, select the function “main” on the menu at the top and click “Execute” to run it. You’ll first will be prompted to authorize the script with your credentials, then click “Execute” again to create the trigger.” ? I don’t seem to have this menu?

EDIT - I think I found it. This is amazing thank you! :slight_smile:

2 Likes

Glad you found, but just in case anyone else need it… it’s at the top of the Google Apps Script interface. Is just to start the function, in order to be prompted to allow the script to run – Google always need this authorization first.

Is this script return parent folders also ?

It’s getting files only for the folder ID you enter, not the parents.
I believe it will return files for children folders – but haven’t tested for that.

1 Like

Thank you so much, been trying to figure this out! Where should I get the webhook url from?

[EDIT] I think I should create a new one at the start of my sequence.

Also, I am getting this error when running it in Scripts (image attached)

There are these two parameters that you must set on the first two lines of the script.

The webhook URL you get from your scenario. Create a new scenario, add a webhook as first module and get the URL from there.

You should also assign the ID of the folder in Google Drive to the folderId variable.
Just access the folder in your browser and grab the last part of the url, like:
https://drive.google.com/drive/u/0/folders/YourFolderIdIsThisPart

If you didn’t set that variable you’ll get that error, since the script can’t reach any file. So set those and give it a go.

hello Hugo thanks i did the steps you described it’s working but i have a question after my webhook (that was before a watch folder module) i have a search for files/folders how do i reference the folder because it’s now a webhook and i also have later in my scenario a module where i was using the name and the link of the folder how do i get that now ?

thank you


You can use either the “Get a Share Link” or “Download a File” module.

Both should give you the name and url of the file.

2 Likes

The webhook is receiving the file ID of the recently modified file, so just add a Download File and reference the fileID you just got at the webhook payload.

1 Like

thank you very much it solved the problem

I don’t know why but my scenario is endlessly charging

That’s because it’s a webhook trigger, it is waiting for a webhook request.

If you did not use the right webhook URL in the script, the webhook will never receive any data.

1 Like

Any idea why I would get this error?
" Error Attempted to execute checkForNewFiles, but could not save."

Maybe you’ve tried to execute the function in the Google Apps Script without declaring the “folderId” and “webhookUrl” variables, on lines 2 and 3.

Have you checked that?

hi hugo,

I have followed all the steps but my webhook is not getting the data. Even on the script, everytime I upload a file, it is not being read. When I ran it to check new files, it is not reading anything.

not found

Here is the folder ID
image
and here is the code

and here is my webhook
image

can you help me please?