Script Can't Open Document (Inaccessible, Please Try Again) - google-apps-script

I'm trying to create a copy of a document and populate it with data from a spreadsheet. I can successfully create the copy but the script can't seem to access it to edit its contents. Here's the code:
var file = DriveApp.getFileById('1mWFhZpZVJpYJleg9n5qq3tr7EHwUIlbM');
var copy = file.makeCopy('SKPembimbing_' + nim, folder).getId();
var doc = DocumentApp.openById(copy);
var body = doc.getBody();
It always gives me an error at the 3rd line when it tries to open the document for editing.
(Exception: Document is inaccessible. Please try again later.)
I saw another thread from last year with the same exact question but without a solution. I've been working all night trying to get this darn thing to work. Does it have to do with my scope? I'm running it on a trigger on edit.

I found the solution:
The template document I was copying was a .docx file, NOT a Google Doc. The copied file was thus also a .docx file so was inaccessible from the DocumentApp. All I had to do was convert it to a Google Document.

Related

Downloading a webpage as a PDF in Google Drive using Google Apps Script

I am working on a Google apps script that is supposed to save web pages as pdf files in a folder inside my google drive. Here is my code for now:
function downloadFiles(){
var fileName ="";
var fileSize ="";
var response=UrlFetchApp.fetch("https://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Accueil_principal");
var rc=response.getResponseCode()
if(rc==200){
var fileBlob=response.getAs('application/pdf');
var folder= DriveApp.getFolderById("ID")// folder where the files to compare will be stored
if (folder!=null){
var file=folder.createFile(fileBlob)
fileName= file.getName()
fileSize= file.getSize()
}
}
var fileInfo={'rc':rc, "filename":fileName,"filesize":fileSize}
}
for some reason, when I run my script I get this error:
Exception: Conversion from text/html to application/pdf failed.
I read on some websites that it could be related to a limitation or something like that... Do you know how I can solve this issue?
From what I understand the problem might come from the getAs() that fails to do the conversion.
I tried with the following version
var page = response.getContentText();
var fileBlob = Utilities.newBlob(page,"application/pdf");
fileBlob.setName("name");
And it manages to create a pdf, but the content is corrupted beyond the first page. I'll keep looking
That conversion service seems to be failing in the last 24 hours (I've been trying to fix my script since then). The script was running for 2 years and is failing since yesterday.
Someone else opened this stackoverflow issue:
Google App Script convert HTML to PDF not working but it was flagged (wrongly) as duplicate.
My bet: Something wrong on Google App's side, but I'll subscribe to this question just in case.

Modify Google App Script - Gmail to Google Drive

I'm trying to modify this script found here:
https://github.com/ahochsteger/gmail2gdrive
I need the script to check if the file already exists on Google Drive and if not, create it. Currently, the script just creates the file into Google Drive, without checking to see if an existing file with the same name already exists or not.
I'm not a programmer, I know nothing about Google App Script (although I have managed to set it up and got it running) and I know nothing about JavaScript. I'm just wondering if someone could either point me in the right direction or help me code this one feature that I need?
From what I understand (I could be wrong), the attachment is created based on this line in the code:
var file = folder.createFile(attachment);
So then I tried add this before the createFile:
var file = folder.removeFile(attachment);
My logic here is that if the file exists in the folder, then remove it first before creating it (therefore avoiding duplicate files). But that didn't work.
From the script of GitHub in your question, it is found that attachment is blob. So how about using this filename? I think that there are several solutions for your situation. So please think of this as one of them. The flow of sample script is as follows.
Retrieve the filename of blob.
Retrieve FileIterator using getFilesByName().
If the FileIterator has values, it means that the file with the same filename has already been existing.
If the FileIterator has no values, it means that the file with the same filename is not existing.
The sample script is as follows.
Sample script 1:
If you want to create new file only when the file of same filename is not existing, you can use the following script.
var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file = f.hasNext() ? f.next() : folder.createFile(attachment);
Sample script 2:
If you want to do something when the file of same filename is existing, you can use the following script.
var fileName = attachment.getName();
var f = folder.getFilesByName(fileName);
var file;
if (f.hasNext()) {
// If the file has already been existing, you can do something here.
} else {
// If the file is not existing, you can do something here.
file = folder.createFile(attachment);
}
Note:
From your question, the file is searched from the folder. If you want to search the file from all files, please tell me.
References:
getName()
getFilesByName(name)
FileIterator
If this was not what you want, please tell me. I would like to modify it.

How to use Universal Find and Replace? (ELI5)

I'm working on a project in a shared Google Drive folder where we recently learned we need to change some strings, that are found in all the documents, with slightly different strings. There are hundreds of files, and it'd be impossible to go through them all one by one, and after some looking I found a Universal Find and Replace script.
https://ctrlq.org/code/19926-universal-find-replace-in-google-drive
Problem is, I have little to no experience with code and even with the instructions given on the site, I have no clue what I have to do with the script. All of it is gibberish to me, and I'd be unbelievably grateful if someone could walk me through all of it.
Questions:
Where in the script do I specify the Drive folder in question and how do I specify it? The "folder path" thing has me even more confused, so if you can let me know where exactly I can find the needed info, that would be great.
Where do I specify the strings I need to replace? I can obviously tell that doc.replaceText has something to do with it, but the fact that it says "You can use regex too" makes me curious if there's anything else I need to change before that?
How should I make a copy of the script code and where in my Google Drive do I place the file?
If there's any other steps I might be overlooking, please mention those as well.
Also, will it be possible to replace more than one string in a single script? (i.e change all "red" to "blue" and change all "black" to "white")
Thank you all in advance, this might end up being a lifesaver?
You might want to look at Apps Script's Drive Service and Document Service to help you be more familiar about the classes and functions to be used.
Drive Service
This service allows scripts to create, find, and modify files and folders in Google Drive.
Document Service
This service allows scripts to create, access, and modify Google Docs files.
Creating a Folder
Using the sample code :
// Log the name of every folder in the user's Drive.
var folders = DriveApp.getFolders();
while (folders.hasNext()) {
var folder = folders.next();
Logger.log(folder.getName());
}
You can set
var newFolder = DriveApp.createFolder('My New Folder');
//To check if you successfully created a folder
Logger.log(newFolder.getId())
//To set sub folder under "My New Folder"
var id = newFolder.getId()
var subFolder = newFolder.createFolder('New Sub Folder')
2. Where do I specify the strings I need to replace? I can obviously tell that doc.replaceText has something to do with it, but the fact that it says "You can use regex too" makes me curious if there's anything else I need to change before that?
You can use findText(searchPattern, from)
Searches the contents of the element for the specified text pattern, starting from a given search result.
A subset of the JavaScript regular expression features are not fully supported, such as capture groups and mode modifiers.
The provided regular expression pattern is independently matched against each text block contained in the current element.
3. How should I make a copy of the script code and where in my Google Drive do I place the file?
You can use Apps Script Console to create your codes, this will be placed in you drive folder.
Lastly, here is a sample code that will change the color of the text:
var body = DocumentApp.getActiveDocument().getBody();
// Use editAsText to obtain a single text element containing
// all the characters in the document.
var text = body.editAsText();
// Insert text at the beginning of the document.
text.insertText(0, 'Inserted text.\n');
// Insert text at the end of the document.
text.appendText('\nAppended text.');
// Make the first half of the document blue.
text.setForegroundColor(0, text.getText().length / 2, '#00FFFF');
Hope it helps!

Import HTML into Google Spreadsheet, programmatically

I'm developing a Google Script to import an HTML file into a new Spreadsheet.
To do so, my script works like that :
initialize an upload form
save the new file into Google Drive, in a public folder.
create a new spreadsheet
set a formula into the first cell : =IMPORTHTML, to import the html file, via the googledrive public URL (FYI, it only works with a public folder)
Here is my issue : I'd like to unlink the new spreadsheet from the html file, in order to be able to remove the HTML file, for security reason. To do so, I tried to :
copy the values and paste them with contentsOnly=true option, to a new sheet => ERROR
add a "Utilities.sleep" before that to be sure the HTML is well imported (just for paranoia, it doesn't change anything...)
It works only if I copy and paste without contentsOnly=true.
Here is my script : https://script.google.com/d/1NH3S3-TT-Yq43gqN4gkVwyTfhm9ZLz6aDVEB_w6gvvjFd3Xwdn0b0-Cg/edit?usp=sharing
Try this script removing the {contentsOnly:true} on line 58, it should work.
If you leave it, it generates this error : "An error occurred on the server(...)"
Could you help me ?
many thanks
I've found another way to do my copy :
I replaced
sourceAllData.copyTo(sheet2.getRange('A1'), {contentsOnly: true});
by :
sheet2.getRange(sourceAllData.getA1Notation()).setValues(sourceAllData.getValues());

Searching current folder for spreadsheets and changing value in specific cell of each file found

New to Google Apps script here, but have some coding experience. I want to scan current folder for spreadsheets. For each spreadsheet found, I want to change the value in a specific cell (say cell F16 in "Sheet1") to "Q1 FY16". Here is what I have so far:
function myFunction() {
var folderID ="0BxfGszImm3D9flpVlWXd4bjQ";
var topFolder = DriveApp.getFolderById(folderID);
Logger.log(topFolder.getName());
var filesList = topFolder.getFiles();
while (filesList.hasNext()) {
var file = filesList.next();
Logger.log(file.getName());
file.getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
}
}
There are two main problems:
I have to specify a folder ID in this and I don't want to. I want the code to run in the current directory (and eventually I will make it recursive to scan all subfolders as well).
The File class doesn't have the "getSheetByName()" or "getRange()" methods, but I don't know how to cast the files into Spreadsheets.
Any help with this would be greatly appreciated.
Cheers
Where will you be launching this script from? They are no way of launching script directly from google drive.
to Be able to use the getSheetByName() and the getRange() you need to open the file as a spreadsheet.
instead of using this line:
file.getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
You should use something like this :
try {
SpreadsheetApp.openById(file.getId()).getSheetByName("Sheet1").getRange("F16").setValue("Q1 FY16");
}
catch(e){}
you need to use the try - catch since some of the files won't be spreadsheet and give and error when trying to use the SpreadsheetApp.openById().
I hope this helps you a bit, I'll try to update this answer once I get more information for the first part.
Best of luck.