Google sheets scripts function UrlFetchApp.fetch does not run from .onEdit(e) but works from editor - javascript

I have created a google sheet with a lot of info for a beach volleyball cup and I want to call an API I have created when a checkbox is checked in this sheet.
function onEdit(e){
const ui = SpreadsheetApp.getUi();
const spreadsheets = SpreadsheetApp.getActive();
const configSheet = spreadsheets.getSheetByName("Config")
var tourneyId = String(configSheet.getRange(2,4).getValue())
var tourneyTitle = String(configSheet.getRange(2,5).getValue())
var sheet = spreadsheets.getActiveSheet()
if (sheet.getName() == "LiveScore"){
var actRng = sheet.getActiveRange();
var editColumn = actRng.getColumn();
var rowIndex = actRng.getRowIndex();
actRng = actRng.getCell(1, 1);
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
if(editColumn == 7 && rowIndex != 1){
onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle);
}
}
}
There is never any problems with this part as I see it. But when i get into the function onStartBroadcastClicked:
function onStartBroadcastClicked(actRng, ui, sheet, rowIndex, editColumn, tourneyTitle){
var homeTeam = String(sheet.getRange(rowIndex, 14).getValue());
... // more setting variables
var endTime = new Date(startTime.getTime() + MILLIS_PER_MATCH);
if(actRng.isChecked()){
var response = ui.alert("You are about to start a new broadcast. Are you sure?" +
"\n Title: " + title, ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
var httpRequest = "https://someUrl";
var options =
{
'method':'POST',
'contentType': 'application/json',
'payload' : JSON.stringify({
"title" : title,
... // setting all variables
"description" : description
}),
'muteHttpExceptions' : true,
'headers' : {
"Authorization": "Basic " + Utilities.base64Encode(USERNAME + ":" + PASSWORD)
}
};
ui.alert("Waiting.......")
var result = UrlFetchApp.fetch(httpRequest, options);
ui.alert(result.getContentText())
The issue is that it always gets to the line ui.alert("Waiting......."), but when triggered from the checkbox, it never succeeds the http POST request. If I click play inside the editor, it succeeds and I got the response in the alertbox.
Could it be some timeout or some autosave issues? Does anyone have any idea if where to keep looking? I've been stuck here for some time now and I would be really happy if anyone can point me to the correct direction.

The modification point of your issue is to use the installable trigger of OnEdit event. When the methods which are required to authorize used at the simple trigger, the error occurs. This situation makes us think that it seems the script doesn't work.
In order to avoid this error, please use the installable triggers of OnEdit event trigger.
As an important point, before you install the trigger, please rename the function name of onEdit() to other name. And install the renamed function name as the OnEdit event trigger. By this, the duplicate run of onEdit() can be prevented. If onEdit() function is installed as the installable trigger, when a cell is edited, the function is run 2 times. Ref.
By above settings, when the cell is edited, UrlFetchApp.fetch() works.
References:
Simple Triggers
Installable Triggers
Asynchronous Processing using Event Triggers

I was able to get a script to work with a trigger if I created the script from script.google.com and call the Google Sheet and tab from the script. I'm manually entered in my API calls per cell within a specified Row:
function fetchUrls() {
var spreadsheetId = "ENTER GOOGLE SHEET ID";
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
var sheet = spreadsheet.getSheetByName("ENTER SHEET NAME");
var range = sheet.getRange("ENTER RANGE OR FULL COLUMN"); // specify the range of cells in column B
var urls = range.getValues(); // get the values of the cells and store them
in an array
var cache = CacheService.getScriptCache();
for (var i = 0; i < urls.length; i++) {
if(urls[i][0] != "") { // check if the current cell is not empty
var url = urls[i][0];
var result = cache.get(url);
if(!result) {
var response = UrlFetchApp.fetch(url);
result = response.getContentText();
cache.put(url, result, 21600);
}
sheet.getRange(i+1,3).setValue(result); // set the value of the current cell to the result of the API call in column C
}
}
}

Related

How do I get Snipe-IT API to retrieve data using a Google App Script and populate it on a Google Sheet?

I am attempting to create a visualization of the data we have on Snipe-IT Asset Management on Google Data Studio. To do so, I am creating a Google Sheets spreadsheet with an App Script extension that will communicate with the Snipe-IT API, retrieve the data, and populate it on the Google Sheet. So far, I've been able to get the API to populate some of our data on the terminal but not on the spreadsheet itself.
I wrote a simple script that should list out the assets assigned to one particular user, for testing purposes. Again, the script works fine, it populates the data I need on the terminal but not on the Google Sheet. Here is my exact code (excluding SETUP section details):
//SETUP
serverURL = 'SERVER-URL'; (ignore)
apiKey = 'API-KEY' (ignore)
function onOpen(e) {
createCommandsMenu();
}
function createCommandsMenu() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Run Script')
.addItem('Get Assets By Department', 'runGetAssetsByDepartment')
.addToUi();
}
function testGetAssetsByUser(){
getAssetsByUser("1745")
}
//Get assets for a user by id
//Returns a list of assets by id
function getAssetsByUser(userID) {
var url = serverURL + 'api/v1/users/' + userID + '/assets';
var headers = {
"Authorization" : "Bearer " + apiKey
};
var options = {
"method" : "GET",
"contentType" : "application/json",
"headers" : headers
};
var response = JSON.parse(UrlFetchApp.fetch(url, options));
var rows = response.rows;
var assets = []
for (var i=0; i<rows.length; i++) {
var row = rows[i];
if (row.category.name == "Laptop" || row.category.name == "Desktop" || row.category.name == "2-in-1") {
var asset = row.id
assets.push(asset)
}
}
return assets
}
console.log(getAssetsByUser(1745));
There are several ways to write values into an spreadsheet
The basics
Grab the spreadsheet
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
This works in bounded projects and add-ons
Grab the destination sheet
var sheet = spreadsheet.getSheetByName('put here the sheet name');
You might use SpreadsheetApp.getActiveSheet() if your spreadsheet has only one sheet, but for functions being called from a custom menu this one is risky.
Write values into the destination sheet
Preparation: Make a 2D Array
var output = assets.map(v => [v]);
Do: Write values into the destination sheet
sheet.getRange(1,1,output.length, 1).setValues(output);
Resources
https://developers.google.com/apps-script/guides/sheets

Email notification: TypeError: Cannot find function getColumn in object 1

I'm new to javascript and I'm trying to write this function that will be used in google sheet so that whenever a value is changed in a specific cell, it will send an email notification to say that cell has been changed. The problem lies is when I used this code in a google sheet there is an error:
"TypeError: Cannot find function getColumn in object 1"
Im not sure what is causing this and I have attempted to look at other peoples problems similar to this but I just dont understand why it is doing this.
Code:
function onEdit(e)
{
var range = e.range;
if (e.getColumn() == 11)
{
var previous = range.offset(0, -1);
var next = range.offset(0, 1);
var emailAddress = 'myemail#gmail.com';
var message = 'Data Changed';
var subject = 'Test Awareness Mail';
GmailApp.sendEmail(emailAddress, subject, message);
}
}

Export data from Google AppMaker Datasource automatically

Does anyone know how we can generate report from data in datasource in Google AppMaker automatically (e.g generate report at 12a.m.) instead of manually click export data in deployments every time user need the report.
I have seen something similar on Exporting data out of Google AppMaker but also no one tried to answer that.
Really appreciate if there is anyone who know how to solve this :)
This can be achieved by using Installable Triggers.
Say for example, you have a model with students data that has three fields; name(string), age(number) and grade(number). On the server script you can write something like this:
//define function to do the data export
function dataExport() {
//create sheet to populate data
var fileName = "Students List " + new Date(); //define file name
var newExport = SpreadsheetApp.create(fileName); // create new spreadsheet
var header = ["Name", "Age", "Grade"]; //define header
newExport.appendRow(header); // append header to spreadsheet
//get all students records
var ds = app.models.students.newQuery();
var allStudents = ds.run();
for(var i=0; i< allStudents.length; i++) {
//get each student data
var student = allStudents[i];
var studentName = student.name;
var studentAge = student.age;
var studentGrade = student.grade;
var newRow = [studentName, studentAge, studentGrade]; //save studen data in a row
newExport.appendRow(newRow); //append student data row to spreadsheet
}
console.log("Finished Exporting Student Data");
}
//invoke function to set up the auto export
function exportData(){
//check if there is an existing trigger for this process
var existingTrigger = PropertiesService.getScriptProperties().getProperty("autoExportTrigger");
//if the trigger already exists, inform user about it
if(existingTrigger) {
return "Auto export is already set";
} else { // if the trigger does not exists, continue to set the trigger to auto export data
//runs the script every day at 1am on the time zone specified
var newTrigger = ScriptApp.newTrigger('dataExport')
.timeBased()
.atHour(1)
.everyDays(1)
.inTimezone("America/Chicago")
.create();
var triggerId = newTrigger.getUniqueId();
if(triggerId) {
PropertiesService.getScriptProperties().setProperty("autoExportTrigger", triggerId);
return "Auto export has been set successfully!";
} else {
return "Failed to set auto export. Try again please";
}
}
}
Then, to delete/stop the auto export, in case you need to, you can write the following on the server script too:
function deleteTrigger() {
//get the current auto export trigger id
var triggerId = PropertiesService.getScriptProperties().getProperty("autoExportTrigger");
//get all triggers
var allTriggers = ScriptApp.getProjectTriggers();
//loop over all triggers.
for (var i = 0; i < allTriggers.length; i++) {
// If the current trigger is the correct one, delete it.
if (allTriggers[i].getUniqueId() === triggerId) {
ScriptApp.deleteTrigger(allTriggers[i]);
break;
//else delete all the triggers found
} else {
ScriptApp.deleteTrigger(allTriggers[i]);
}
}
PropertiesService.getScriptProperties().deleteProperty("autoExportTrigger");
return "Auto export has been cancelled";
}
You can check the demo app right here.
The reference to the script properties service is here.
The reference to the Time Zones list is here.
I hope this helps!
It seems that you are looking for daily database backups. App Maker Team recommends migrating apps to Cloud SQL if you haven't done this so far. Once you start using Cloud SQL as your data backend you can configure backups through Google Cloud Console:
https://cloud.google.com/sql/docs/mysql/backup-recovery/backups

Google script project trigger not running?

I'm pretty new to Javascript and have been working on this script to take the most recent entry in a spreadsheet (created from a Google form), match the users email address that is collected to a roster in a second sheet, and send an email to parents. I'm a teacher and the idea is to be able to create a google form that compiles the info students enter and email it to their parents once they submit the form/update the sheet.
I know it's pretty messy...there are some extra variables and things, but the script works perfectly/as expected when you "Run" the script. The only thing is, I have tried to have the script run on a trigger when the form is submitted, but it doesn't. Am I missing something with using triggers?
Code is below:
function createEmail() {
// Sets variables for both sheets
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var sheet2 = ss.getSheets()[1];
// This gathers information from the most recent entry and write it to an array called newReflectionValues
var reflectionLastRow = sheet1.getLastRow();
var reflectionLastColumn = sheet1.getLastColumn();
var reflectionLastCell = sheet1.getRange(reflectionLastRow, reflectionLastColumn).getValue();
var reflectionRange = sheet1.getRange(reflectionLastRow, 1, 1, reflectionLastColumn);
var newReflectionValues = reflectionRange.getValues();
var studentEmail = newReflectionValues[0][3];
Logger.log("NEW REFLECTION VALUES")
Logger.log(newReflectionValues);
Logger.log("Email will send to student email:")
Logger.log(studentEmail)
// Makes an array of the parent email addresses
var rosterLastRow = sheet2.getLastRow();
var rosterLastColumn = sheet2.getLastColumn();
var rosterEmails = sheet2.getSheetValues(2, 1, rosterLastRow, rosterLastColumn);
Logger.log("PARENT EMAILS")
Logger.log(rosterEmails);
// Cross check emails - if a match, write emails to variable
var parentEntriesLength = rosterLastRow;
for (i = 0; i < parentEntriesLength; i++) {
var currentRange = rosterEmails[i];
if (currentRange[2] == studentEmail) {
var toParents = String(currentRange[3]) + ", " + String(currentRange[4]);
var studentName = String(currentRange[0]);
var countOfReflections = currentRange[6];
break;
} else {
var toParents = "NO PARENT EMAILS FOUND";
}
}
// FINISH EMAIL BELOW
MailApp.sendEmail({
to: toParents,
bcc: "rdoyle#rafos.org" + ", " + String(studentEmail),
subject: "Behavior Reflection Notification",
htmlBody: "<p>Hello,</p>" +
"<p>Today studentName received a behavior reflection for the following action:</p>" +
"<p>newReflectionValues</p>" +
"<p>They took a short break in class and completed the following reflection:</p>" +
"<p>reflectionInformation</p>" +
"<p>" + String(studentName) + " has recieved " + countOfReflections + " reflections this year." + "</p>" +
"<p>This email has been sent with information that the student completed directly on the reflection form and has been bcc'd to them as well as myself. If you have any questions regarding this behavior or incident, please feel free to ask.</p>"
});
}
You are aware that there are 2 types of trigger simple and installable but I think you are a little confused as to what they actually mean/ do. I'll try to explain the key points from documentation here.
A simple trigger is used by simply naming the function with the trigger name. For example, with Sheets / Forms, the trigger onFormSubmit(e) is fired when the user submits a form. The parameter e contains all the information relating to the submission, you should look into this as it's much more reliable than your current method of getting the submitted information. See here: 'e' parameter
Simple triggers are limited in their functionality since the script doesn't have to be authorised for the trigger to fire. A simple trigger cannot access other files, send emails or perform any action that requires authorisation. See here
An installed trigger is one that is either manually set up by the user or a script. Installed triggers have a lot more functionality but they still have some restrictions. See here
An installed trigger can call any named function and e parameter works in the same way as it does with simple triggers.
From your code above your installed trigger should look like this.
When you click save you should be asked for authorisation, if you are not asked, click the debug/ run button to authorise the script.
If it still doesn't work check the execution transcript in view -> execution transcript, the last line will indicate the error.
Ok, James helped out a lot, but I was seeming to have a lot of problems authenticating the permissions to send emails. I decided in the end to re-write everything more clearly, add some functions so others I work with could use the same script, and keep a record of whether or not emails were actually sent to parents. This final version uses a if statement to look in a column at whether or not an email was sent for each response, then sends an email if needed and records when it was sent. I also added a function to set up that "confirmation" column and create a roster sheet as a single function as well as seperately. Oh, and it also looks for an html template to format the email. I found that info on a Google developers live stream: https://www.youtube.com/watch?v=U9Ej6PCeO6s
Thanks everyone!
function createConfirmationColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var lastColumn = sheet1.getLastColumn();
var lastColumnValue = sheet1.getRange(1,lastColumn).getValue();
// Creates the final column to log the time that emails are sent
if (lastColumnValue != "Email Sent On:") {
sheet1.insertColumnsAfter(lastColumn, 1);
var emailSentOnColumn = sheet1.getRange(1,lastColumn+1).setValue("Email Sent On:");
}
}
function createRosterSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.insertSheet("Roster & Parent Emails", 1);
var rosterSheet = ss.getSheets()[1];
rosterSheet.getRange(1,1).setValue("First Name")
rosterSheet.getRange(1,2).setValue("Last Name")
rosterSheet.getRange(1,3).setValue("Student Email")
rosterSheet.getRange(1,4).setValue("Parent Email 1")
rosterSheet.getRange(1,5).setValue("Parent Email 2")
rosterSheet.getRange(1,6).setValue("Notes")
rosterSheet.getRange(1,7).setValue("Total Reflections")
}
function formSetup() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var lastColumn = sheet1.getLastColumn();
var lastColumnValue = sheet1.getRange(1,lastColumn).getValue();
// Creates the final column to log the time that emails are sent
if (lastColumnValue != "Email Sent On:") {
sheet1.insertColumnsAfter(lastColumn, 1);
var emailSentOnColumn = sheet1.getRange(1,lastColumn+1).setValue("Email Sent On:");
}
ss.insertSheet("Roster & Parent Emails", 1);
var rosterSheet = ss.getSheets()[1];
rosterSheet.getRange(1,1).setValue("First Name")
rosterSheet.getRange(1,2).setValue("Last Name")
rosterSheet.getRange(1,3).setValue("Student Email")
rosterSheet.getRange(1,4).setValue("Parent Email 1")
rosterSheet.getRange(1,5).setValue("Parent Email 2")
rosterSheet.getRange(1,6).setValue("Notes")
rosterSheet.getRange(1,7).setValue("Total Reflections")
}
function sendEmails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss.getSheets()[0];
var sheet2 = ss.getSheets()[1];
var lastColumn = sheet1.getLastColumn();
var lastColumnValue = sheet1.getRange(1,lastColumn).getValue();
var allFormEntries = sheet1.getDataRange().getValues();
var allRosterValues = sheet2.getDataRange().getValues()
for (e = 1; e < sheet1.getLastRow(); e++) {
var formRange = allFormEntries[e];
var studentEmailInForm = formRange[1];
var emailSentOn = formRange[4];
if (emailSentOn == "") {
for (i = 1; i < sheet2.getLastRow(); i++) {
var individualRosterEntry = allRosterValues[i];
if (studentEmailInForm == individualRosterEntry[2]) {
var parentEmails = String(individualRosterEntry[3]) + ", " + String(individualRosterEntry[4]);
var emailTemplate = HtmlService.createTemplateFromFile("emailTemplate");
emailTemplate.studentName = individualRosterEntry[0];
emailTemplate.reflectionCount = individualRosterEntry[6];
emailTemplate.reason = formRange[2];
MailApp.sendEmail({
to: parentEmails,
bcc: "rdoyle#rafos.org" + ", " + String(studentEmailInForm),
subject: "Behavior Reflection Notification",
htmlBody: emailTemplate.evaluate().getContent(),
})
sheet1.getRange((e+1), lastColumn).setValue(new Date());
break;
} else {
sheet1.getRange((e+1), lastColumn).setValue("No valid email found") ;
}
} // for i loop
} //if email sent == ""
} //for e loop
} //function

Error: "Cannot call method getRange of null" in google spreadsheet

I'm trying to insert data to google spreadsheet using GET method. I found the code below, followed the instructions, and created new sheet named "Sheet1", but when I'm trying to insert data through GET method, I get an error says: "Cannot call method getRange of null". What could be the problem? Does anyone have another idea how to insert data to google spreadsheet using GET method?
Thanks!
// Usage
// 1. Enter sheet name where data is to be written below
var SHEET_NAME = "Sheet1";
// 2. Run > setup
//
// 3. Publish > Deploy as web app
// - enter Project Version name and click 'Save New Version'
// - set security level and enable service (most likely execute as 'me' and access 'anyone, even anonymously)
//
// 4. Copy the 'Current web app URL' and post this in your form/script action
//
// 5. Insert column names on your destination sheet matching the parameter names of the data you are passing in (exactly matching case)
var SCRIPT_PROP = PropertiesService.getScriptProperties(); // new property service
// If you don't want to expose either GET or POST methods you can comment out the appropriate function
function doGet(e){
return handleResponse(e);
}
function doPost(e){
return handleResponse(e);
}
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
// loop through the header columns
for (i in headers){
if (headers[i] == "Timestamp"){ // special case if you include a 'Timestamp' column
row.push(new Date());
} else { // else use header name to get data
row.push(e.parameter[headers[i]]);
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
// return json success results
return ContentService
.createTextOutput(JSON.stringify({"result":"success", "row": nextRow}))
.setMimeType(ContentService.MimeType.JSON);
} catch(e){
// if error return this
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
} finally { //release lock
lock.releaseLock();
}
}
function setup() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
SCRIPT_PROP.setProperty("key", doc.getId());
}
Looks like page SHEET_NAME does not exist
and sheet is null here
var sheet = doc.getSheetByName(SHEET_NAME);
I would recommend you to check if sheet was initialized
function handleResponse(e) {
// shortly after my original solution Google announced the LockService[1]
// this prevents concurrent access overwritting data
// [1] http://googleappsdeveloper.blogspot.co.uk/2011/10/concurrency-and-google-apps-script.html
// we want a public lock, one that locks for all invocations
var lock = LockService.getPublicLock();
lock.waitLock(30000); // wait 30 seconds before conceding defeat.
try {
// next set where we write the data - you could write to multiple/alternate destinations
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("key"));
var sheet = doc.getSheetByName(SHEET_NAME);
if(sheet != null) {
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [];
==== code skipped =====
if you doesn't care about sheet name, use
var sheet = doc.getSheets()[0];

Categories