Need help setting up a Google Drive folder watcher using appscript and Drive API

1,315 views
Skip to first unread message

Arquivos Mídia

unread,
Feb 16, 2023, 9:51:27 AM2/16/23
to Google Apps Script Community

Hi there,

I am currently trying to set up a Google Drive folder watcher using appscript and the Drive API's drive.files.watch function. My goal is to create a web application that will send an email notification whenever an event occurs in a specific folder.

Here is the logic I have attempted to use so far:

First, I included the service directly in the DRIVE API appscript and ran it once to authorize. Then, I created a monitorFolderChanges() function that calls the Drive.Files.watch function, passing in the ID of the folder I want to monitor and a watchResource object that contains a unique ID, a web hook type, and the address of my webhook URL.

Secondly, I created a doPost(e) function that receives data from Drive.Files.watch and sends an email with information about the event that occurred in the folder. The function uses e.postData.getDataAsString() to get the data from the webhook, and then uses JSON.parse() to parse the data. It then retrieves the name, URL, and ID of the file that triggered the event, and sends an email notification to a specified recipient.

However, I have been unsuccessful in getting this logic to work. I am wondering if anyone has any ideas on how I can successfully set up this folder watcher in appscript.

Thank you in advance for your help!


// Part 1: Drive.Files.watch is triggered when an event occurs in the folder, and sends the data to the url of the web application.
function monitorFolderChanges() {
  var folderId = 'ID-FOLDER';
  var watchResource = {
    id: 'unique_id_exclusive',
    type: 'web_hook',
    address: 'my_url_for_webhooks'
  };
  Drive.Files.watch({fileId: folderId, resource: watchResource});
}

// Part 2: function doPost(e) receives data from Drive.Files.watch and sends email with information about the event that occurred in the folder.
function doPost(e) {
  var jsonString = e.postData.getDataAsString();
  var data = JSON.parse(jsonString);
  var fileId = data.resourceId;
  var file = DriveApp.getFileById(fileId);
  var fileName = file.getName();
  var fileUrl = file.getUrl();

  var recipient = "exa...@example.com"; // Recipient email address
  var subject = "File added to watch folder"; // Email Subject
  var body = "The file '" + fileName + "' has been added to the watched folder. You can access it through the link: " + fileUrl; // Email body

  GmailApp.sendEmail(recipient, subject, body);

  return ContentService.createTextOutput('Success');
}

Arquivos Mídia

unread,
Feb 16, 2023, 10:44:39 AM2/16/23
to Google Apps Script Community

I found this excellent discussion thread, it looks like there is an impediment unfortunately.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages