google-apps-scripttriggersgoogle-drive-apigoogle-docsgoogle-docs-api

Google Apps Script (Google Docs) - trigger on comment add or change?


I am searching thorugh Google Apps Script documentation and I don't find how to make a trigger if comment is added or changed in a google document. Under ElementType section (https://developers.google.com/apps-script/reference/document/element-type) I can see a property COMMENT_SECTION but also there is CommentSection element crossed in the description of the property. Does this mean that CommentSection class doesn't exist anymore?


Solution

  • To get the comments of a document you need to use the Advanced Drive Service (which you should enable in the Script Editor by selecting Resources > Advanced Google services... and then enable it in the Google Developers Console. Official Documentation)

    Once enabled, you can retrieve the comments with the Drive.Comments.list. The list of properties of the comments can are documented here.

    Here's an example:

    function retrieveComments() {
      var comments;
        comments = Drive.Comments.list('docId');
        if (comments.items && comments.items.length > 0) {
          for (var i = 0; i < comments.items.length; i++) {
            var comment = comments.items[i];
            Logger.log('%s on %s by %s', comment.content, comment.createdDate, comment.author.displayName);
          }
        } else {
          Logger.log('No comments found.');
        }
    }
    

    Depending on your use case, you can store the commentId, createdDate and modifiedDate to evaluate if the have changed