Skip to content

Instantly share code, notes, and snippets.

@leoherzog
Created September 19, 2023 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leoherzog/07eaf6fd0b374d5d01df85b124fb391b to your computer and use it in GitHub Desktop.
Save leoherzog/07eaf6fd0b374d5d01df85b124fb391b to your computer and use it in GitHub Desktop.
Google Doc Change Notifier
/**
* 1. Go to script.google.com, and when logged in as the user that you want to do the "checking", click "➕ New Project" in the top right
* 2. Copy/Paste all of this code into your new project, and give it a name (e.g. Google Doc Change Notifier)
* 3. Change the `const docs = []` line to include all of the Docs you want to check. For example, `const docs = ["https://docs.google.com/document/blah", "https://docs.google.com/document/foo"];
* 4. Click "▷ Run" in the toolbar and authorize the script to run.
* 5. You're done!
*/
const docs = ["https://docs.google.com/document/d/1Gwt56BiconMLg_u-hdo0asdff27U7DlqLOzHVVgNnoM/edit"];
function check() {
let properties = PropertiesService.getScriptProperties();
for (let id of docs) {
let document;
try {
document = DocumentApp.openById(id);
} catch(e) {
try {
document = DocumentApp.openByUrl(id);
}
catch(e) {
console.error('Cannot open the document "' + id + '" (' + e.message + '). Are you sure that\'s a doc? Do you have access to view it?');
continue;
}
}
let body = document.getBody().getText();
console.log(body);
let lastcheck = properties.getProperty(document.getId());
let b64 = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, body, Utilities.Charset.UTF_8).reduce(function(str,chr){
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length==1?'0':'') + chr;
},'');
if (lastcheck !== b64) {
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'Document Has Changed', 'The Google Doc "' + document.getName() + '" has been edited. Check the Doc\'s Version History for more details. ' + document.getUrl());
properties.setProperty(document.getId(), b64);
}
}
verifyScheduled_();
}
function verifyScheduled_() {
let triggers = ScriptApp.getProjectTriggers();
if (!triggers.length || triggers.length >= 2 || triggers[0].getHandlerFunction() !== 'check') {
console.warn('Deleting all existing triggers and rescheduling hourly trigger.');
for (let trigger of triggers) {
ScriptApp.deleteTrigger(trigger);
}
ScriptApp.newTrigger('check').timeBased().everyHours(1).create();
console.info('Scheduled to run every hour!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment