Trigger webhook on new file upload on Google Drive

You must remember that this code takes into account the time of the last modification of the file – which means that if you upload a file that has been created/last modified a long time ago, it won’t fire the automation.

Try to open the file, do a minor change and save it, so the last modified time is updated – and then upload it to the folder.
You can also edit this time range, modifying the time on the isRecentlyCreated() function.

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;
}

Try this out and see if it works.

Hi Hugo,

I believe I did everything correctly.

From the drive folder ID to the Make webhook URL till the new creation and modification of the file, but still I’m receiving the error

It seems that you are trying to execute the isRecentlyCreated() function manually there – that’s not necessary.

Go to the triggers section (the stopwatch icon, on the left bar) and check whether you have the triggers created or not. If you don’t, then go back to the code section and select the function main() and execute it. Then check back if the triggers are there.

With the triggers in place your project should start monitoring the folder for recently created files (and as I said before, you can adjust the threshold of how much time is “recently” for you case).

Check that and see if that solve it.

1 Like

Hi @hugoassuncao thank you for this script, I know it will be so useful. I am close but not getting data to the webhook and think maybe I am missing a step.

Things I’ve done

  • entered folder ID

  • updated files in that folder

  • added webhook url

  • I can’t see a ‘Resources’ section in my Scripts interface but I did receive a pop up to link my Google account which I accepted

What isn’t working

  • ‘Triggers’ is empty

  • I’ve run the script many times, and received one webhook response at one point (maybe the permission?) but it was empty

  • No specific errors are showing, but no data is getting to the webhook

I attach a couple of screenshots and would be grateful if you can see what I am doing wrong!


Thank you :pray:

Did you executed the funciton main(), in order to enable the trigger that will make the script run?
See on your screencapture the “myFunction” dropwdown menu?
Select the “main” function and click “Run”.

Then go to the left side panel, on the “Triggers” section and check if there is a trigger created.
Google Apps Script needs to run this script on a time basis in order to send the new files payload to your webhook.

And keep in mind that the script consider the last update on the file – so if it’s an old file - not updated recently, won’t work.

Hi @hugoassuncao thank you, although yes, I have done all those things:

  • the ‘Execution log’ in my first original screenshot shows after I have Run the function (called ‘myfunction’ not ‘main’)

Screenshot 2024-06-24 at 15.35.01

  • I have added recent files to the folder - both new and updated
  • Triggers is still blank
  • I have checked the Folder ID
    I can’t think why it’s not working?!
    Is there anything else I’m missing?
    Thank you
    Sarah

It’s strange that you have a function named “myFunction” at this point.
I suspect you kind of encapsulated the code in that original function (that is created automatically, when you create a new project).

Do this: copy the original code again, erase everything you have and replace the folder ID and webhook URL again.

Then run the “main” function and go to the “Triggers” section to see if the trigger has been created. You should see a trigger to run the function “checkForNewFiles”.

1 Like

@hugoassuncao thank you for your help.
I’ve found that the script has been working successfully with the webhook in Make, even though I still can’t see any triggers!

It also works whether or not it’s called myfunction or main - both are good.

So thank you, great that it is working!
Sarah

1 Like

Hi @hugoassuncao, Thank you very much for all this help. I followed the instructions as explained above and managed to get the triggers. I also activated the deploy button through a website. The problem is that the Webhook in Make does not activate when I upload a document in the folder. Can someone please help me? Making a video on how to do it would be very interesting. I will be attentive to the help that someone can provide me. Thank you very much!

You must take into account that by default this code consider “new file” those with date of creation on the last minute (refer to this answer).
If you are uploading a file with time of creation longer than that, it won’t be caught by the function.

Do this: test with a newly created file or adjust the timer to your liking and see if the function fires correctly.

Hello @hugoassuncao, if we add a file inside the folder, this don’t update the modification date of the parent folder how can i do ?

The trigger is not the modifications date of the parent folder, is the modification date of the files within the target folder – so there is nothing to worry about the folder modification time.

This is EPIC. Exactly what I was looking to find - they should make this a native module!!!

Thanks @hugoassuncao . Everyone needs to see this.

I was hoping you could assist, having a little issues getting this to pull the payload and not just the json format.

Here is the output screenshot and the codebase I’m using for watching folders.

// Replace 'myFolderID' with the actual ID of your parent folder and 'https://mysample.webhook.com' with your webhook URL
const folderId = '1lERb2UgMfb3cMLWtiFX5H2YxCXXXXXXXX';
const webhookUrl = 'https://hook.us2.make.com/qtcwtsl7bukvvwi1ubez0gt4hXXXXXXX';

const cache = CacheService.getScriptCache();

function isRecentlyCreated(folder) {
  const now = new Date();
  const threshold = 10 * 60 * 1000; // Check for folders created in the last 10 minutes
  return now - folder.getDateCreated() < threshold;
}

function checkForNewFolders() {
  const parentFolder = DriveApp.getFolderById(folderId);
  const folders = parentFolder.getFolders();

  let newFoldersFound = false;

  while (folders.hasNext()) {
    const folder = folders.next();
    const folderId = folder.getId();

    // Check cache for processed folderId
    if (!cache.get(folderId)) {
      if (isRecentlyCreated(folder)) {
        const payload = {
          folderId: folderId,
          folderName: folder.getName(),
          parentFolderId: parentFolder.getId(),
          parentFolderName: parentFolder.getName(),
        };
        UrlFetchApp.fetch(webhookUrl, {
          method: 'post',
          contentType: 'application/json',
          payload: JSON.stringify(payload)
        });
        cache.put(folderId, 'processed', 24 * 60 * 60); // Cache processed folderId for 24 hours
        console.log(`New folder found: ${folderId}`);
        newFoldersFound = true;
      }
    } else {
      console.log(`Folder ${folderId} already processed`);
    }
  }

  if (!newFoldersFound) {
    console.log('No new folders found');
  }
}

function startMonitoring() {
  // Schedule a function to check for new folders periodically (e.g., every 10 minutes)
  ScriptApp.newTrigger('checkForNewFolders')
      .timeBased()
      .everyMinutes(10)
      .create();
}

function main() {
  startMonitoring();
}

Hello folks, I made small update, I created version that check also in subfolders. I hope it could be useful to someone

const folderId = '<YOUR_FOLDER_ID>';
const webhookUrl = '<YOUR_WEBHOOK>';
let newFilesFound = false;

const cache = CacheService.getScriptCache();

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

function triggerCheckAllFolders() {
  newFilesFound = false;
  const currentFolder = DriveApp.getFolderById(folderId);
  checkForNewFiles(currentFolder);
}

function checkForNewFiles(currentFolder) {
  const folders = currentFolder.getFolders();
  while(folders.hasNext()) {
    checkForNewFiles(folders.next())
  }
  const files = currentFolder.getFiles();
  
  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`);
    }
  }
}

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

function main() {
  startMonitoring();
}

I can’t tell if a) this code send the name of the new file(s) as part of the webhook, or just that the folder has had some new files placed in it. I need the former, as the name of the files being placed in the folder is needed to then act on the file (I know I can poll the folder every 15 mins in Make, but I need something more instant)

The above codes only send the file ids to your webhook. You can modify the script to also send the file names.

You can also use other Google Drive modules like “Download a File” or “Get a Share Link” to fetch additional details about the file using the file id.

Hope this helps! Let me know if there are any further questions or issues.

@samliew

P.S.: Investing some effort into the Make Academy will save you lots of time and frustration using Make.