How to add a doc to a folder - google-apps-script

I am generating a document using Google App Script (specifically a document, not a spreadsheet) and I need to be able to add it to a folder I have called "Test Documents".
I have tried
doc.addToFolder("Test Documents");
However, in debug mode I get the error that the method addToFolder is not found. I'm trying to use this functionality: https://developers.google.com/apps-script/class_file#addToFolder
Could someone give me an example of how I might do this?

The method addToFolder is part of DocsList service, here is an example :
var Doc = DocsList.getFileById('1INkRIviwdjMC-PVT9io5LpiiLW8VwwIfgbq2E4xvKEo');
var gas = DocsList.getFolderById('0B3qSFd3iikE3NWY0dndsMTFZMDQ')
Doc.addToFolder(gas)

Related

TypeError: Cannot read property 'getBody' of null

I'm trying to teach myself to use Google Apps Script, but somehow every function I try returns this error immediately. And since I'm a huge beginner, I don't know what I'm doing wrong.
Here's a simple example of a code I tried to run:
function myFunction(){
//application
//file
var ad = DocumentApp.getActiveDocument();
var docBody = ad.getBody () ;
var paragraphs = docBody.getParagraphs();
//paragraphs[0]. setText ("MY NEW TEXT"):
//var attr = paragraphs[0].getAttributes() ;
//Logger.log(attr);
paragraphs[0].setAttributes({FONT_SIZE:40});
}
Yet no matter what I'm running really, I get this:
TypeError: Cannot read property 'getBody' of null
myFunction # Code.gs:5
What am I doing wrong?
I have an open Google Doc, I've allowed permissions to run the script project. What else should I try? Thanks.
In order to get getActiveDocument() working you need to use it in a script that is container-bound:
Create a new Google Document
Go to Extensions > Apps Script
Run your function inside of it.
If your script is not container-bound, you need to use the openById(id) or openByUrl(url) methods, in order to retrieve a Document
Adblock software was preventing the running somehow. Disabled it and runs fine now. Disregard!

How to use 'getBody()' on a Google document with a standalone script?

I want to do some text/paragraphs replacement in Google Docs that are automatically created by an add-on (autoCrat). I tried this successfully on a bound script but now that I want to try it on a standalone script, I get this error:
TypeError: Function getBody not found in the DOCUMENT-NAME object.
I don't understand.
Do I need to call a bound script from the standalone script or something like that?
(I hope not.)
The GAS documentation is not helping at all with this, at least with my understanding of what a standalone script is. Maybe it's a trivial error, but all the examples I found here are for bound scripts, which are not what I'm doing (I've already done a bound script and it's working fine).
This very simple code won't work for a standalone script and I don't understand why :
function Myfunction() {
var file = DriveApp.getFileById('doc-id');
var body = file.getBody();
Logger.log(body);
}
You are getting that error because the class returned by getfilebyID is of type File, not Document.
Try something like this:
let LogFile = DriveApp.getFileById('doc-id');
let LogDoc = DocumentApp.openById(LogFile.getId());
LogDoc.getBody()

Inserting Image into Google Sheets from Google Drive using Apps Script

I have been trying for 9 days to add an image that is uploaded to my drive (via the use of a google form) into my Google sheet using Apps Script, but it isn't working and I have no idea why, this is my code below:
function getImage(){
var folderImage = DriveApp.getFolderById("0B7gxdApLS0TYfm1pRHpHSG4yTm96bm1PbTZQc1VmdGpxajY4N1J4M1gtR1BiZ0lOSl9NMjQ");
Logger.log(folderImage.getFiles().next().setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW));
Logger.log(folderImage.getFiles().next().getSharingAccess());
Logger.log(folderImage.getFiles().next().getSharingPermission());
var imageFile = folderImage.getFiles().next().getBlob();
detailSheet.insertImage(imageFile, 1, 13);
}
I have even tried making the sharing and access permissions of the to be as open as possible but I keep getting this error message:
"We're sorry, a server error occurred. Please wait a bit and try again"
I find the error message ambiguous which leads me at a dead end. Usually the message gives me a good idea of where I have gone wrong.
I believe my code is correct, and during my research I have found no definitive reason this shouldn't work. Does anybody know where I am going wrong?
A solution would be great but preferably a critique on my code so I can learn :)
Couple of issues with your script:
You never bind to a specific file, so to work with the same file you have to reinitialize the iterator each time.
You don't verify its mimetype prior to using it as an image
An example that resolves those issues:
function addFolderPNGs_(sheet, folderId) {
const folder = folderId ? DriveApp.getFolderById(folderId) : DriveApp.getRootFolder(); // scope only to the root or given folder.
const imgs = folder.getFilesByType(MimeType.PNG);
var targetRow = sheet.getLastRow();
while (imgs.hasNext()) {
var img = imgs.next();
Logger.log(img.getName())
sheet.insertImage(img.getBlob(), 1, ++targetRow);
}
}
References
getFilesByType is either folder-specific (above) or operates on all of Google Drive
DriveApp
Folder
MimeTypes
Sheet#insertImage

Autocomplete Not Working - Google App Script

I'm having trouble with the autocomplete feature in Google App Script.
Built-in methods like SpreadsheetApp. will provide an autocomplete menu with methods to choose from.
However, if I create my own child object, autocomplete works for a little while, and then it just stops working.
for example:
var skywardRoster = SpreadsheetApp.getActiveSheet();
skywardRoster. will produce method options for a while, and then it stops.
However, the code still functions, and methods work if I type them out manually, so I know the declarations must be right. The menu simply won't appear, and it's just very inconvenient to have to look up each method individually as I go.
I have tried: breaking the variable and retyping that line; copy and pasting the code back into the editor; using different browsers; copying the gs file itself and working within the copy; and signing out completely and signing back in. Nothing seems to get it back to work.
I'm really new to coding, and I'm not sure what can be causing this.
Does anyone know how to fix this issue?
You might want to check Built-in Google Services:Using autocomplete:
The script editor provides a "content assist" feature, more commonly called "autocomplete," which reveals the global objects as well as methods and enums that are valid in the script's current context. To show autocomplete suggestions, select the menu item Edit > Content assist or press Ctrl+Space. Autocomplete suggestions also appear automatically whenever you type a period after a global object, enum, or method call that returns an Apps Script class. For example:
If you click on a blank line in the script editor and activate autocomplete, you will see a list of the global objects.
If you type the full name of a global object or select one from autocomplete, then type . (a period), you will see all methods and enums for that class.
If you type a few characters and activate autocomplete, you will see all valid suggestions that begin with those characters.
Since this was the first result on google for a non-working google script autocompletion, I will post my solution here as it maybe helps someone in the future.
The autocompletion stopped working for me when I assigned a value to a variable for a second time.
Example:
var cell = tableRow.appendTableCell();
...
cell = tableRow.appendTableCell();
So maybe create a new variable for the second assignment just during the implementation so that autocompletion works correctly. When you are done with the implementation you can replace it with the original variable.
Example:
var cell = tableRow.appendTableCell();
...
var replaceMeCell = tableRow.appendTableCell(); // new variable during the implementation
And when the implementation is done:
var cell = tableRow.appendTableCell();
...
cell = tableRow.appendTableCell(); // replace the newly created variable with the original one when you are done
Hope this helps!
I was looking for a way how to improve Google Apps Script development experience. Sometimes autocomplete misses context. For example for Google Spreadsheet trigger event parameters. I solved the problem by using clasp and #ts-check.
clasp allows to edit sources in VS Code on local machine. It can pull and push Google Apps Script code. Here is an article how to try it.
When you move to VS Code and setup environment you can add //#ts-check in the beginning of the JavaScript file to help autocomplete with the special instructions. Here is the instructions set.
My trigger example looks like this (notice autocompletion works only in VS Code, Google Apps Script cloud editor doesn't understand #ts-check instruction):
//#ts-check
/**
* #param {GoogleAppsScript.Events.SheetsOnEdit} e
*/
function onEditTrigger(e) {
var spreadsheet = e.source;
var activeSheet = spreadsheet.getActiveSheet();
Logger.log(e.value);
}
I agree, Google Script's autocomplete feature is pretty poor comparing with most of other implementations. However the lack is uderstandable in most cases and sometimes the function can be preserved.
Loosing context
The autocomplete is limited to Google objects (Spreasheets, Files, etc.). When working with them you get autocomplete hints, unless you pass such object instance to function as an argument. The context is lost then and the editor will not give you suggestions inside the called function. That is because js doesn't have type control.
You can pass an id into the function instead of the object (not File instance but fileId) and get the instance inside of the function but in most cases such operation will slow the script.
Better solution by Cameron Roberts
Cameron Roberts came with something what could be Goole's intence or a kind of hack, don't know. At the beginning of a function assign an proper object instance to parameter wariable and comment it to block:
function logFileChange(sheet, fileId){
/*
sheet = SpreadsheetApp.getActiveSheet();
*/
sheet.appendRow([fileId]); // auto completion works here
}
Auto completion preserved

Script to automatically make a copy of a Google Document for editing

I feel like a total noob posting here. I know CSS, HTML, and XML pretty well but have always avoided JS. I know very little javascript and recently started a Lynda.com course to catch up. Sorry for my ignorance. As such, I am really struggling learning Google Apps Script. Obviously, I need to learn JS before I can make sense of any of it.
The school I work for (5000 students) has set up an online curriculum. I created the curriculum in the form of thousands of google document worksheets. These worksheets are linked on various websites.
The problem we are facing is that when students open the documents, they have to make a copy of them before they can edit them (I of course don't want them to be able to edit the originals). This really sucks for students using mobile browsers on their tablets as making a copy in Google Docs doesn't really work well when using the desktop UI on mobile devices.
I know this kind of thing can be automated with script. I've looked here, and low and behold, it works! I'm pissing my pants with joy as I've been searching for such functionality for three years. (Yes, I know that's sad).
So, what I'm asking is, would anyone be willing to help a noob figure out how to adapt this code so that students click a button on a website lesson and it automatically makes and opens a copy of the worksheet in a new tab?
/**
* Copy an existing file.
*
* #param {String} originFileId ID of the origin file to copy.
* #param {String} copyTitle Title of the copy.
*/
function copyFile(originFileId, copyTitle) {
var body = {'title': copyTitle};
var request = gapi.client.drive.files.copy({
'fileId': originFileId,
'resource': body
});
request.execute(function(resp) {
console.log('Copy ID: ' + resp.id);
});
}
Spending all day yesterday learning Javascript, I've still got a long way to go. Not sure how long it'll take for me to be able to figure this out on my own.
You can certainly do this with Apps Script. Only takes a couple of lines. In fact, you can use just the version I wrote below.
Here is how I would do it -
Ensure you original document is at least read enabled for the folks that will be accessing it.
Grab the fileId from the URL -
Write a web app in Apps Script with the following code -
function doGet(e) {
//file has to be at least readable by the person running the script
var fileId = e.parameters.fileId;
if(!fileId){
//have a default fileId for testing.
fileId = '1K7OA1lnzphJRuJ7ZjCfLu83MSwOXoEKWY6BuqYitTQQ';
}
var newUrl = DocsList.getFileById(fileId).makeCopy('File copied to my drive').getUrl();
return HtmlService.createHtmlOutput('<h1>Open Document</h1>');
}
Deploy it to run as the person accessing the app.
One key thing to remember is that a web app built by Apps Script cannot force open a new window automatically. Instead we can show a link which is clickable into the document in edit mode.
You can see it in action here (will create some dummy file) -
https://script.google.com/macros/s/AKfycbyvxkYqgPQEb3ICieywqWrQ2-2KWb-V0MghR2xayQyExFgVT2h3/exec?fileId=0AkJNj_IM2wiPdGhsNEJzZ2RtZU9NaHc4QXdvbHhSM0E
You can test this by putting in your own fileId.
Since DocsList is deprecated, currently you can make a copy of a file using the following code:
File file=DriveApp.getFileById(fileId).makeCopy(fileName, folder);
where fileId can be obtained as explained in the answer by Arun Nagarajan.
Update as of 2015, Google Script removed the fileId for reasons unknown. The previous method of appending "/copy" to the URL of the Google doc has been re-enabled. Ex) https://docs.google.com/document/d/1GTGuLqahAKS3ptjrfLSYCjKz4FBecv4dITPuKfdnrmY/copy
Here is the code to do it properly (works in 2019,2020,2021):
/**
* Create custom menu when document is opened.
*/
function onOpen() {
DocumentApp.getUi()
.createMenu('For Students')
.addItem('Make a copy', 'makeACopy')
.addToUi();
}
function makeACopy() {
var templateId = DocumentApp.getActiveDocument().getId();
DriveApp.getFileById(templateId).makeCopy();
}
Here is the code I use to make an auto copy of my google Docs.
function makeCopy() {
// generates the timestamp and stores in variable formattedDate as year-month-date hour-minute-second
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd' 'HH:mm:ss");
// gets the name of the original file and appends the word "copy" followed by the timestamp stored in formattedDate
var name = DocumentApp.getActiveDocument().getName() + " Copy " + formattedDate;
// gets the destination folder by their ID. REPLACE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx with your folder's ID that you can get by opening the folder in Google Drive and checking the URL in the browser's address bar
var destination = DriveApp.getFolderById("16S8Gp4NiPaEqZ0Xzz6q_qhAbl_thcDBF");
// gets the current Google Docs file
var file = DriveApp.getFileById(DocumentApp.getActiveDocument().getId())
Add a trigger and enjoy!
The same code works for google Sheets. Only you need to replace
DocumentApp.getActiveDocument().getName()
with
SpreadsheetApp.getActiveSpreadsheet()
You can find more details here.