Is it possible to add a comment attributed to specific text within Google Docs using Apps Script? - google-apps-script

Google docs comment:
My goal is to add a text-specific comment using Google Apps Script as seen in the picture above. Right now I have this working code, but it only adds a general comment for the whole document.
function myFunction() {
var fileId = '{FILE_ID}';
var resource = {'content': 'comment body text'};
Drive.Comments.insert(resource, name);
}

Not possible. In this video -- Google Drive SDK: Announcing the Comments API (5:30 - 5:39) -- it is mentioned that:
..We do have a proprietary anchoring scheme, which does make it difficult for, or actually rather impossible for you to create comments that are anchored to text in our document formats...
"in our document formats" refers to Google Docs and Sheets.
This is also mentioned in this answer. For more details regarding Comments, you can check the Manage Comments and Discussions documentation.

Related

How to detect comments related to deleted content with Google Docs API

Google API provides very usefull calls to list comments made in a document.
Each comment has a status: opened or closed
In some situations, the content to which the comment was refering has been deleted by the author. The status would still be considered as opened.
{author= {displayName=XXX, kind=drive#user, picture=url=//lh3.googleusercontent.com/a-/xxx}, isAuthenticatedUser=false},
modifiedDate=2022-11-15T13:38:38.830Z,
content=please specify,
fileTitle=My Doc,
replies=[],
fileId=sclg_xxx,
status=open,
kind=drive#comment,
anchor=kix.zdfriprq7z5o,
commentId=AAAAkFW0Fy8,
htmlContent=please specify,
createdDate=2022-11-15T13:38:38.830Z, deleted=false,
context={value=25 MD, type=text/html}
}
How could I detect comments made on deleted content?
I see that each comment has an anchor attribute : eg. anchor=kix.zdfriprq7z5o. Is there a way to check if this anchor still exists in the document?

Google Apps Script Gmail getPlainBody Line Breaks

With the Google Apps Script Gmail library, when I use the function GmailMessage.getPlainBody(), the API seems to take what used to be one paragraph and break it up into multiple, potentially by using a character limit. For instance, a paragraph of my email reads:
From the link you sent me, I gleaned that Gmail refers to their secure email as confidential.
But when I call this function on the email, it becomes:
From the link you sent me, I gleaned that Gmail refers to their
secure email as confidential.
And, when I split the email text on a new line delimitor and do a bit of cleanup to create an array with my output, I end up with:
['From the link you sent me, I gleaned that Gmail refers to their', 'secure email as confidential.']
I viewed this Reddit post, which seemed to deal with the similar problem. But, I tried the resolution suggested by the person who posed the question:
body = message.getPlainBody().replace(/\r\n\r\n/gm,'aaaLINEBREAKERaaa').replace(/\r\n/gm,' ').replace(/aaaLINEBREAKERaaa/gm, '\r\r').replace(/ /gm,' ')
And it didn't quite give me what I need. Has anyone else encountered this problem, and if so, do you have a suggested workaround? Thanks!
I had the same issue. In that case, I used a workaround.
When I checked the email, I noticed that the HTML body is included in the message body and the HTML body has the original paragraph, and I used this situation. So, in this workaround, the original text is retrieved from the HTML body and the HTML is converted to a text. By this, the original paragraph is obtained. The sample script is as follows.
Sample script:
This script uses Drive API for converting HTML to text. So pelase enable Drive API at Advanced Google services.
var message = // Here, please use your "message".
var html = message.getBody();
var id = Drive.Files.insert({title: "temp", mimeType: MimeType.GOOGLE_DOCS}, Utilities.newBlob(html, MimeType.HTML)).id;
var text = DocumentApp.openById(id).getBody().getText(); // or DocumentApp.openById(id).getBody().getText().trim();
DriveApp.getFileById(id).setTrashed(true);
console.log(text)
References:
getBody()
Files: insert

How do I use Google Apps Script on a single question in Google Forms?

I've started doing a Google Form, however I'd like to use G.A.S to do some custom questions, lists, etc. I have found the code to try and I've entered it into the Script Editor, but I don't see how to set the code to specific sections or questions. How do I specify where the code should run?
This will add a short answer question to a form.
function addAQuestionToAForm() {
const form=FormApp.getActiveForm();
form.addTextItem().setTitle('Phone Number');
}
Here's the form:

Retrieving HTML code used in google docs using google app scripts

Is it possible to use Google app scripts to get the html code in Google docs i.e if text in the document was say bold,i could get the html code for that.
What i have so far :
function getHtml(id) {
var doc1=DocsListExtended.getFileById("1ta7zJ6SDFgzgp-UprjehxR8Tx3-4-wtJwTYqWbol1SU").getAsHTML();
var body=HtmlService.createHtmlOutput(doc1);
var cont=body.getContent();
return cont;
Logger.log(cont);
}
I don't know a simple way for that. You can navigate the elements of the document using DocumentApp API, and converting it block by block to HTML.
I already tried
DocumentApp.getActiveDocument().getAs(MimeType.HTML).getDataAsString()
but the error says doc can't be converted to html mimetype.

How can I create superscript/subscript characters in a document?

I'm working on a script to convert some documents in a proprietary format over to google docs. I've been able to handle most of the various formatting options (fonts, point sizes, bold, etc.) but I'm stuck on subscript and superscript.
I've tried creating a new google doc with a paragraph in subscript. I then wrote a script to look at the paragraphs and children and in both cases didn't see an attribute that was set as I could for underline.
I've tried wrapping the text in st but that only added that exact text to the document. Here is a bit of the code I'm currently using:
if (superscript == true ) {
paragraph.appendText(txt.sup()).setAttributes(style);
} else if (subscript == true) {
paragraph.appendText(txt.sub()).setAttributes(style);
} else {
paragraph.appendText(txt).setAttributes(style);
}
Anything else to try?
There's currently no way to do this — it would exist somewhere in the Text class API (https://developers.google.com/apps-script/reference/document/text) if it were possible.
I filed a feature request for superscript / subscript here https://code.google.com/p/google-apps-script-issues/issues/detail?id=2885 . Feel free to star the issue to register your support.
For the benefit of anyone looking for this, it's been implemented since this question was asked as a TextAlignment class - it's not explicit in the documentation*, but thankfully these create indices on text elements observed with the getTextAttributeIndices method.
* as in, it's not an attribute listed by getAttributes but is indexed with getTextAttributeIndices()
I've just modified a Docs-to-markdown processing script I'm working on to incorporate sub- and superscript alignment handling which may be useful as an example (see commit diff).
Note that if applied across paragraphs the getTextAlignment method returns null.
You want to put the superscript and subscript characters to Google Document using Google Apps Script.
If my understanding is correct, how about this sample script? Unfortunately, even in the current stage, there are still no methods for putting the superscript and subscript characters using Document Service.
But when Google Docs API which was added at early 2019 is used, those can be achieved. Such function might be added to Document Service in the future. So as a current workaround, I would like to propose the method using Docs API. The sample script is as follows.
Before you use this script, please enable Google Docs API at Advanced Google services.
Sample script:
function myFunction() {
var documentId = "###"; // Please set document ID here.
var resource = {requests: [
{insertText: {text: "SampleSuperscriptSubscript", location: {index: 1}}},
{updateTextStyle: {range: {startIndex: 7, endIndex: 18}, textStyle: {baselineOffset: "SUPERSCRIPT"}, fields: "baselineOffset"}},
{updateTextStyle: {range: {startIndex: 18, endIndex: 27}, textStyle: {baselineOffset: "SUBSCRIPT"}, fields: "baselineOffset"}}
]};
Docs.Documents.batchUpdate(resource, documentId);
}
Result:
When above script is run for new Google Document, the following result is obtained. At first, a text of SampleSuperscriptSubscript is put. Then, the text style is modified. These are run using the batchUpdate method. If you want to put those values for the existing Document, please modify above object of resource.
References:
Document Service
Google Docs API
Advanced Google services
Method: documents.batchUpdate
TextStyle
BaselineOffset
If this was not the direction you want, I apologize.