calling methods that get values from a spreadsheet from other scripts [closed] - google-apps-script

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have two scripts, each one bounded to different spreadsheets. Just script one is bounded to a cloud project while script two is not. I saved the first script version with identifier: "scriptOne"
This is the function in script 1 (which does return the value I want when using the log):
var ss = SpreadsheetApp.getActive().getSheetByName("someSheet");
var one = ss.getRange(2, 1).getValue();
function scriptOneFunction() {
return one;
}
I have a second script and i made sure to select scriptOne.v1 within libraries (development mode "on") and now I am trying to call this function from the second script as follows:
function callScriptOne() {
var two = scriptOne.scriptOneFunction();
Logger.log(two);
}
The error I get:
TypeError: Cannot read property 'getRange' of null
at [scriptOneFunction](callScriptOne:2:17)
What am i doing wrong?

There are two possible issues with your approach:
Your second script is not bound to a google spreadsheet.
If 1) is not the issue, then check if the spreadsheet has indeed a sheet with the name someSheet.
Related:
TypeError: Cannot call method "getRange" of null. (line 9, file "Code")
TypeError: Cannot call method "getRange" of null. (line 4, file "Code"

Related

Google Apps Script - Set Values randomly failing

Someone on stack overflow from 2016 reported this issue happening in debug mode only but this isn't debug mode, it is happening in my live code (run from webapp) running in backend AND debug mode.
The frustrating thing is that this isn't every call to setValues. There is one array call to setvalues that does work (writes to the spreadsheet) higher in the script.
This code has not been modified in more than a month and was working until at least 10-26 (first failure reported 11-2).
Here is a small example:
function setValuesIsFailing(sheet, array, row, column){
//newIDR_SHEET.getRange(3, 9, formulaColumns.length, 2).setValues(formulaColumns);//old command this function replaces
const targetRange = sheet.getRange(row,column,array.length,array[0].length);
console.log(139,targetRange.getA1Notation());
sheet.getRange("C5").setValue("UGH");
targetRange.setValues(array);
console.log(sheet.getRange("C5").getValue());
}
The result of this code is the expected console log of :
10:46:10 AM Info 139 'I3:J49'
10:46:11 AM Error
Exception: Service Spreadsheets failed while accessing document with id 12shsTE-Mxxx
setValuesIsFailing # Code.gs:143
So line 139 implies that it does have the sheet it is writing to and then it
doesn't throw an error when told to write to those two locations (but it does
not succeed in writing to them) and after that it throws an error when asked
to read from one of the locations.
To recap:
code was working just fine. Had not been modified for a month and was working correctly most of that month.
setValue / setValues commands fail silently without throwing an error (nothing is written to target)
service spreadsheet error occurs later when trying to read from places that should have been modified by the script but were not
Moving the problem to a new function obviously didn't fix it.
Other things I tried, logging the sheet name, reassigning a new variable to the sheet (originalyl concerned that somehow the function was losing the sheet but debugging shows that isn't the case), moving the failing piece of code to a new function for easier logging, waiting for the problem to resolve itself.
Any ideas?
=====
Solved:
It turned out that the weird behavior was caused by a failed attempt to apply data validation to the sheet.
Unlikely that anyone else will have this behavior, but I was pulling my data validations down from a sheet a single column at a time.
Either it was accepting a 2d array of one column as acceptable to the data validation setup command OR it was automatically flattening the array since it was only one column. This has changed. Manually flattening my column data with a .flat() fixed the issue. I would really have expected the bad validation setting call to throw an error though.
I discovered that a bad validation application was causing the spreadsheet to basically stop being able to be updated.
It was reading a 2d array (one column) and applying that as a validation list. When I flattened the validation list it worked.

Has my self-invoking workaround worked or is it coincidence?

I've been having an issue with a Google Apps Script I'm running that kept throwing the following error when ever I triggered the code onChange. No such errors were returned when I manually ran the code.
Exception: Service Documents failed while accessing document with id XXXX
The error was happening on the same line of code each time and I've subsequently found that this is a relatively common error and is perhaps happening because my script is quite lengthy and perhaps not as efficient as it should be (I'm very much an Apps Script and JS novice). Interestingly I have a very similar script (with perhaps 20% less variables) running in another file that executes as expected every time.
I had no naming or scoping issues with the variable that was being used to call the document but I thought that perhaps wrapping the troublesome part of the script into a self-invoking function within the larger function would minimise hoisting and improve the efficiency of the script - at least enough to let it run consistently without errors. My understanding of JS is that when a script initiates variable declarations are hoisted within their scope and therefore by creating a self-invoking function I could reduce the hoisting within the main function which contains in excess of 100 variables and therefore reduce the initial demand.
So far the script does appear to be running more quickly and avoiding the error that I'd previously being seeing - the last run was just over 63 seconds whereas the previous successful manual run without the self-invoking function was just under 103 seconds.
I do believe this can be an intermittent error and I'm trying to find a robust, longer term fix without having to rewrite all of my code.
I have detailed the self-invoking code below with any IDs redacted. The part that was causing the error within the script was "var docFinal = DocumentApp.openById(docFinalId);
Do you think this could be a genuine fix or has the code started to work coincidently because of the intermittent nature of this error?
var docTempId = "XXXX";//Template File Id
var docFinalId = "XXXX"; //Final File Id
var sheetId = "XXXX";
(function () { // self-invoked within larger function to minimise hoisting
var docTemp = DocumentApp.openById(docTempId);
var docFinal = DocumentApp.openById(docFinalId);
docFinal.getBody().clear();
var templateParagraphs = docTemp.getBody().getParagraphs();
createMailMerge(Company,Branch,PropertyID,PropertyAddress,ApplicantName,Dateofbirth1,EmailAddress,PhoneNumber,Nationality,PassportNumber,NationalInsuranceNumber,Currentresidentialstatus,LeaseRequested,RentOfferedPCM,TotalNumberofAdultOccupants,Proposedleasecommencementdate1,TotalRentPayers,RentPayer2Name,RentPayer2Phone,RentPayer2Email,RentPayer3Name,RentPayer3Phone,RentPayer3Email,Relationshipwithadultoccupants,Numberofchildren,Ageofchildchildren,Currenteconomicstatus,Applicantoccupation,Applicantemployedorselfemployed,ApplicantDeclaredIncome,SelfEmployedDocuments,EmploymentPartorFullTime,EmploymentContractorPermanent,MainEmploymentCompany,Mainemploymentaddress,Mainemploymentstartdate1,Mainemploymemtpensionpayrollnumber,MainEmploymentManager,ManagerEmail,ManagerPhoneNumber,ApplicantPaymentType,ApplicantHourlyRate,Applicantprimaryaveragehourspermonth,Applicantsalary,ReceivesHousingBenefit,HousingBenefitAmount,Anyadditionalincome,Typeofadditonalincome,Secondemploymentcompany,Rolewithin2ndCompany,ndEmployeraddress,ndEmploymentstartdate1,ndEmployerpensionpayrollnumber,ndEmploymentContact,ndEmploymentEmail,ndEmploymentphonenumber,Additionalincomeamount,Additionalincomedetails,TotalDeclaredGrossIncome,Applicansavingsdeclared,MostRecentAddress,DateStartedlivingincurrentaddress1,Liveanywhereelseinlast3years,Applicant2ndresidingaddress,Applicant2ndaddressmoveindate1,Applicant2ndaddressmoveoutdate1,Applicantadditionaladdressdeclared,Applicantadditionaladdressdetails,Applicantadditonaladdressmoveindate1,Applicantadditionaladdressmoveoutdate1,Applicantpreviouslandlordreference,Landlordreferenceaddress,referencefromlandlordoragent,LandlordAgentName,lengthoftimeatproperty,LandlordAgentphonenumber,LandlordAgentemailaddress,Previouslandlordreferencepreventionreason,Anypets,Petdetails,Applicantsmoke,Applicantsmokeinside,Applicantadversecredit,Adversecreditdetails,Applicantprovidecurrentaccount,Applicantcurrentaccountname,Applicantcurrentaccountbank,Applicantcurrentaccountnumber,Applicantcurrentaccountsortcode,UKbasedguarantor,GuarantorName,GuarantorEmail,GuarantorPhoneNo,Noguarantorreason,NextofKinName,NextofKinrelationship,NextofKinEmail,NoNextofKinPhoneNo,Applicantadditionalinfo,Applicantdocuments,Applicantaccurateinformationdeclaration,Applicantaccepttermsandconditions,submittedatt,Token,maidenname,ApplicantReferencingChoice,Applicantcanprovide,Applicantdocumentlink,ApplicantacceptsHomelet,ApplicantallowsHomelettocontactreferences,ApplicanthappyforHomelet,templateParagraphs,docFinal);
docFinal.saveAndClose();
createPDF(); // calls the next function
}) ();
The script has just failed again. After working on a number of occasions which hadn't been happening, it has now failed and return the same error as before. I can therefore only assume that creating a self-invoking function within the main function has made no material difference to the efficiency of the script.
The error you are receiving does not seem to be the expected one.
I think the best solution in this situation is to file a bug on Google's Issue Tracker by using the template here.

Using events.patch in Google Apps script [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm writing a Google apps script to update an event. I tried using the path API like below:
event_ins.setVisibility('private');
Logger.log('Making event %s %s private %s',calendarId, event_ins.summary, event_ins);
Calendar.Events.patch(event_ins,calendarId, eventID_ins);
I get the following error message:
11:28:30 AM Error HttpResponseException: Response Code: 404. Message: Not Found.
I tried using the update method instead
Calendar.Events.update(event_ins,calendarId,eventID_ins);
I'm still getting the same error.
The examples in Google's API documentation does not use Google script. I tried searching example code and I found similar usage. For instance this is from here :
event = Calendar.Events.patch(event, calendarId, eventId, {
sendNotifications: true
});
I would appreciate any help to get this working.

Get email using Hunter IO API with Google Apps Script [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Hello fellow developers,
I am trying to get the email count for any website using Hunter IO free API with Google Apps Script.
Hunter IO API reference : https://hunter.io/api/v2/docs#email-count
Here is my code.
function checkDomain() {
var domain = 'stripe.com';
var url = 'https://api.hunter.io/v2/email-count?domain='+domain;
var response = UrlFetchApp.fetch(domain);
var result = response.getContentText();
Logger.log(JSON.parse(result)); // <-- Line 56
}
I get this Error : SyntaxError: Unexpected token: < (line 56, file "Code")
Can anyone please help me understand this error and tell me how to retrieve a JSON response from this Hunter IO.
You need to pass url and not domain variables.
var response = UrlFetchApp.fetch(url);
I would also recommend the use of string constructors. Its increase readability and understanding of the code.
var domain = 'stripe.com';
var template = 'https://api.hunter.io/v2/email-count?domain=%s';
var url = Utilities.formatString(template, domain);

Import JSON document array / object to a Meteor Collection with correct _ids [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
What is the best way to import a 15,000 document json file of a format (but with a +30 foo fields)
[{"foo1":"foo1data1", "foo2":"foo2data1"}, {"foo1":"foo1data2", "foo2":"foo2data2"}...
{"foo1":"foo1dataN", "foo2":"foo2dataN"}])
to a Meteor collection?
I tried with mongoimport but that created ObjectID's instead of _id's and I could not make it work without autopublish, although other collections, created with Meteor, work just fine on client side.
Supposing the file is located on the server under pathToFile you can do something like this:
var fs = Npm.require("fs");
var Fiber = Npm.require("fibers");
fs.readFile(pathToFile, 'utf8', function (err, data) {
// handle error if there is some
data = JSON.parse(data);
Fiber(function () {
_.each(data, function (document) {
SomeMeteorCollection.insert(document);
});
}).run();
});
Please note that Fiber wrapper is required if you want call any meteor specific routines, for example collections API, within some nodejs asynchronous code.