Apps Script (Error Exception: The document is inaccessible. Please try again later. Creator # Code.gs:10) - google-apps-script

I wrote a script to automatically create and fill in the required fields in the file, but an error
Error Exception: The document is inaccessible. Please try again later. Creator # Код.gs:10
Please look at the code, tell me where I was wrong.
function Creator() {
const docFile = DriveApp.getFileById("1DhHBAd3ssYMgbbxJatK6_URxBPdoPk2K");
const tempFolder = DriveApp.getFolderById("16keE-_Dm0gglO42Lw0IphiPHYK-_TFXH");
const pdfFolder = DriveApp.getFolderById("1ZsmW9UPNaqgjt8kFh3y9h8tdBLAtj7gC");
const tempFile = docFile.makeCopy(tempFolder);
const tempDocFile = DocumentApp.openById(tempFile.getId());
const body = tempDocFile.getBody();
var list = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var l=list.getLastRow();
for (var i=2; i <= l; i++) {
var a1 = list.getRange(i, 3).getValue();
var a2 = list.getRange(i, 4).getValue();
body.replaceText("{ПІБ}", a1);
body.replaceText("{Назва структури}", a2);
tempDocFile.saveAndClose();
const pdfFile = tempDocFile.getAs(MimeType.PDF);
pdfFolder.createFile(pdfFile).setName(a1);
tempFolder.removeFile(tempFile);
}
}

Assuming that the code line having the error is
var l=list.getLastRow();
It's very likely that you faced a Google environment glitch (I have faced the same error this weekend). In situations like this there is nothing else to do than to wait a bit and try again.
If you are developing a script / add-on / web-app to be used by others or you would like to handle this automatically you could use an algorithm like exponential backoff
If the error occurred on the previous code lines calling the Document Service, the problem might be caused for trying to open non Google Document file i.e. Microsoft Word file (.docx). In this case you should first convert the file to Google Document format and use the converted document instead of the original.
Related
Error message: "Cannot connect to Gmail" (Google services having glitches)
Google Script Document Inaccessible Error - creating and attempting to open document in code
Exception: The document is inaccessible. Please try again later. Google Scripts
Resources
Scripts implementing the exponential backoff algorithm in Google Apps Script
https://gist.github.com/peterherrmann/2700284
https://github.com/RomainVialard/ErrorHandler

Related

Google App Script Randomly Stopped Working - TypeError: Cannot read properties of undefined (reading 'streams') (line 6)

This Google Apps Script code to scrape press release news from Yahoo Finance randomly stopped working today.
It suddenly gives the following error -
TypeError: Cannot read properties of undefined (reading 'streams') (line 6)
function pressReleases(code) {
var url = 'https://finance.yahoo.com/quote/'+code+'/press-releases'
var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/);
if (!html || html.length == 1) return;
var obj = JSON.parse(html[1].trim());
var res = obj.context.dispatcher.stores.StreamStore.streams["YFINANCE:"+code+".mega"].data.stream_items[0].title;
return res || "No value";
}
Code in Cell (with the stock symbol in cell A6)
=pressReleases(A6)
I can still retrieve JSON using python and the format of the data in the JSON is the exact same so I'm guessing it's a problem with Google Apps Script but I'm having no luck in fixing it.
The JSON output is here: https://privatebin.net/?4064ef5520f5b445#FDiJS868e3xSsgzh3y8LsF72LsefyoZ635kqCx62ZtwH
Any help as to why it suddenly stopped working would be appreciated.
Your showing script is from this answer? When I saw the HTML, it seems that in the current stage, the data is converted with the salted base64. In this case, I would like to propose an answer by reflecting on the method of this answer.
Usage:
1. Get crypto-js.
Please access https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js. And, copy and paste the script to the script editor of Google Apps Script, and save the script.
2. Modify script.
function pressReleases(code) {
var url = 'https://finance.yahoo.com/quote/' + code + '/press-releases'
var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/);
if (!html || html.length == 1) return;
var obj = JSON.parse(html[1].trim());
// --- I modified the below script.
const { _cs, _cr } = obj;
if (!_cs || !_cr) return;
const key = CryptoJS.algo.PBKDF2.create({ keySize: 8 }).compute(_cs, JSON.parse(_cr)).toString();
const obj2 = JSON.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.AES.decrypt(obj.context.dispatcher.stores, key)));
var res = obj2.StreamStore.streams["YFINANCE:" + code + ".mega"].data.stream_items[0].title;
// ---
return res || "No value";
}
When this script is used and code is PGEN, the value of Precigen to Present at the 41st Annual J.P. Morgan Healthcare Conference is obtained.
Note:
If you want to directly load crypto-js, you can also use the following script. But, in this case, the process cost becomes higher than that of the above flow. Please be careful about this.
const cdnjs = "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js";
eval(UrlFetchApp.fetch(cdnjs).getContentText());
I can confirm that this method can be used for the current situation (December, 21, 2022). But, when the specification in the data and HTML is changed in the future update on the server side, this script might not be able to be used. Please be careful about this.
Reference:
crypto-js
I believe match returns an array so perhaps you need
var html = UrlFetchApp.fetch(url).getContentText().match(/root.App.main = ([\s\S\w]+?);\n/)[index];
Oh I missed the fact that your using it in a conditional on the very next line and then in the next line you're using the index of one.
var obj = JSON.parse(html[1].trim());
so the problem must be either in a data variation or this line var res = obj.context.dispatcher.stores.StreamStore.streams["YFINANCE:"+code+".mega"].data.stream_items[0].title;

Exception: Service unavailable: Documents Error in Google Doc Apps Script

I have an odd issue with a Google Doc Apps Script. It's been working for months without any issues. Then yesterday I get the Error Message: "Exception: Service unavailable: Documents" whenever I try to position an image blob (either from a URL Fetch or from getFileById). I simplified my code to this, and no matter what image I use, I always get the error.
function debugProc () {
var rLlogoborderlessId = '1ZhOX_aneaAhM0XJV4oQHGfNPUzaVETgu';
doc = DocumentApp.getActiveDocument();
curBody = doc.getBody();
var addlines = curBody.appendParagraph('');
var imgpara = curBody.appendParagraph("");
imgpara.setAlignment(DocumentApp.HorizontalAlignment.CENTER);
var logoimage = DriveApp.getFileById(rLlogoborderlessId).getBlob();
var addlineslogo = curBody.appendParagraph('');
var k2nplogo = addlineslogo.addPositionedImage(logoimage);
// Error: Exception: Service unavailable: Documents
}
I tried multiple different computers and browsers. Nothing works. No workaround that I can find. How can I resolve this?
By reading your new comments I understand that the case isn't reproducible on new documents. The issue may have originated from a problem with your project or a bad configuration. To fix it, you only need to create a new Doc and copy all the data there. Feel free to leave a comment below if you need help with the migration.

DriveApp.getFileById() throwing a server error [duplicate]

This question already has answers here:
DriveApp Error: "We're sorry, a server error occurred. Please wait a bit and try again."
(4 answers)
Closed 1 year ago.
I have a script that I am using to export a google sheet to a PDF. It has been working no problem up until now. I deployed it as a Web App so that it could be used by anyone. Since I deployed it, it has not worked. I tried archiving the Web App and that did not help.
The issue seems to be with the DriveApp.getFileById() function. I inserted numerous console.log() functions along the way of my code to try to narrow down where it actually fails and why. The execution log shows that the error is happening at the same spot that I derived, but the console.log() functions did not help me figure out why. The error I receive is:
Exception: We're sorry, a server error occurred. Please wait a bit and try again.
I have tried researching this for quite some time now, and have tried suggestions that I found. I double checked all my variables and code syntax. I also know that the pdfid is being pulled correctly, as verified by logging it. I have not altered this part of the code, or any part that it depends on, at all since it has been working. I believe the Web App deployment is the issue, but I'm not sure why or how I could fix it. It could also be something else I'm missing, as it still does not work even after archiving the Web App.
Here is the code, the last line shown is where it fails:
function exportLog(type) {
console.log('Starting Export');
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var realExp = sheet.getSheetByName('exportThis');
var newSpreadsheet = SpreadsheetApp.create("Spreadsheet to export");
//console.log('Spreadsheet created');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var sheet = realExp.copyTo(newSpreadsheet);
//console.log('Copied');
SpreadsheetApp.getActiveSpreadsheet().toast('Beginning export...','Loading...',-1);
//console.log('using new sheet');
newSpreadsheet.getSheetByName('Copy of exportThis').showSheet();
//console.log('successfully used new sheet');
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
//console.log('deleted');
var pdfid = newSpreadsheet.getId();
console.log(pdfid); // Correctly logs ID
var pdf = DriveApp.getFileById(pdfid);
function exportLog(type) {
const ss1 = SpreadsheetApp.getActive();//this returns the active spreadsheet
const xsh = ss1.getSheetByName('exportThis');
const ss2 = SpreadsheetApp.create("Spreadsheet to export");
const nsh = xsh.copyTo(ss2);
nsh.showSheet();//you can't really show the sheet because ss2 is not the active spreadsheet
ss2.getSheetByName('Sheet1').activate();//again you can't activate this sheet because ss2 is not the active spreadsheet
ss2.deleteActiveSheet();//This is not the active spreadsheet
const pdfid = ss2.getId();//I don't know why you call this a pdf it's a spreadsheet
const pdf = DriveApp.getFileById(pdfid); //again ss2 is a newly created spreadsheet
}
//Input parameter is never used
You should get in the habit of referring to the documentation while you write your code and pay special attention to the types that are returned by methods.

While updating google spreadsheet from google app script I am getting error message "You do not have permission to access the requested document."

I have two environment for single google-app-script project. One with Sandbox and one with Production. Both have same code because, I copied Sandbox code into Production environment project.
Both are reading and writing same spreadsheet file with id 13vlLM5Tc7z4m-XXXXX-Kdjg. Below is the sample code.
While I run my 'google-app-script' project as web application, update work fine with Sandbox env but it gives below error for production env.
You do not have permission to access the requested document.
I check everything. I have full access of both 'google-app-script' project as well spreadsheet.
This is the code I used to find and update spreadsheet data.
var wb = '13vlLM5Tc7z4m-XXXXX-Kdjg';
var sheet = SpreadsheetApp.openById(wb);
var sheetData = sheet.getDataRange().getValues();
sheetData.shift();
var key = 'XYZ';
for(var i=0; i<sheetData.length; i++){
if(key!=undefined && key!='' && key == sheetData[i][21]){
resetPassUser = techSheetData[i];
var values = [['Yes']];
var nextRow = index+2; // get next row
sheet.getRange(nextRow, 23, 1, 1).setValues(values);
break;
}
}
It should update spreadsheet data using production env project also. Because code and permission are same. But instead it is giving me error.
You do not have permission to access the requested document.
I think your authorization is confused. Try adding this to your app code
/**
* #NotOnlyCurrentDoc
*/

How to resolve "Too much calls for this service today : gmail" error in Google Apps script?

My question is about an error in Google's spreadsheet using gmail service in a function.
Since a while, an error occur when I run a function (On Google Spreadsheet) for retrieve mails on a label founded in the MailBox (Gmail).
The error message is : "Too much calls for this service today : gmail".
I want to specify that function worked fine before and it hasn't been modified.
The function is launched one time per month (Except in exceptional case)
I did some research on the error message, and the answers found confirmed what I thought,
daily quotas for Google's gmail services are exceed and can not be used until 24 hours.
However, it's the only one that has not worked, while others are working properly with these services without any errors.
Following this, I created a copy of the spreadsheet with the function to test if it isn't the sheet that does not work, but it has not changed.
And I launched it with another Google account, and it worked.
Does anyone know why this message appears please ?
Should we do a special manipulation to make it work again ?
Here is the row that sends an error :
var threads = GmailApp.getUserLabelByName("Label").getThreads();
And the function :
function readMail(){
var threads = GmailApp.getUserLabelByName("Label").getThreads();
var messages = GmailApp.getMessagesForThreads(threads);
for(var i in messages){
var message = messages[i];
for(var j in message){
var mess = message[j];
var sub = mess.getSubject();
if(mess.getTo().indexOf("email#gmail.com") > -1)
continue;
var attach = mess.getAttachments()[0];
var file = {
title: attach.getName()
};
var fileDoc = Drive.Files.insert(file, attach, {convert: false}); // Use Drive API
mess.markRead();
}
}
}