data query problem with google app script - google-apps-script

Since yesterday I get the problem when I make a query to a sheet to bring information. The code to bring information is the following:
var s_usuario="c123";
var spreadsheetId = 'myid'; // Please set the spreadsheet ID.
var targetSheet = "Usuarios"; // Please set the sheet name.
var usuario =s_usuario.toUpperCase();
var query = 'select B where A = "'+usuario+'"'; // Please set the query for retrieving the values.
var ss = SpreadsheetApp.openById(spreadsheetId);
var sheetId = ss.getSheetByName(targetSheet).getSheetId();
var url = "https://docs.google.com/spreadsheets/d/" + spreadsheetId + "/gviz/tq?gid=" + sheetId + "&tqx=out:csv&tq=" + encodeURIComponent(query);
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
var row = Utilities.parseCsv(res.getContentText());
var maximo=row.length;
for (var i = 0; i < maximo; i++) {
var mostrar =row[i][0].toString();
}
return mostrar
What should I modify so that the query can be given? I think there was an update in the language

Perhaps you want:
var mostrar='';
for (var i=0;i<maximo; i++) {
mostrar +=row[i][0].toString();
}
return mostrar;
or even:
var mostrar=row.map(r=>{return r[0];});
return mostrar.join(',');
Probably everything else is okay since you copied it from here

This is a new bug related to the UrlFetchApp
It seems to already worked on, so hopefully the issue is of temporarily nature.

I don't know the solution, but I can also say that in the past 2-3 days my scripts also all started failing that use var file = UrlFetchApp.fetch(url); My scripts are on a schedule and all of them fail at any line that uses this. I see that you are using UrlFetchApp as well. My first failure happened at Dec 8, 2020, 3:53:50 AM
Hopefully this can help figure out what is going on. Here is the specific error I get on mine:
Exception: Unexpected error: https://...org/..xxxx/..xxx.csv (line 242, file "Code")
I am very interested in the solution that works for you, perhaps it can help me as well.

Related

Exception: Unexpected error while getting the method or property getFileById on object DriveApp

I have a script that I have been using for a long time and it stopped working on monday. No changes were made to the spreadsheet and I don't understand why I'm getting this error now.
Essentially the script sends an email when there is a change on column 16, which is the control column. In the file there is information about orders that get to the warehouse and whether or not they pass quality control. If they don't pass it, we receive an email stating that that specific order did not pass quality control.
Variable Ficha, which is column 23, has the FileID for every order, which is then attached in the email.
I have tried to write the variable "ficha", which seems to be the one causing the problem, in two different ways but I get the same error.
I tried the var ficha you can see in the script and also:
var ficha1 = SpreadsheetApp.getActive().getSheetByName("CONTROL DE CALIDAD").getRange("W3:W").getValues();
var ficha = ficha1.reduce(function(ar, e) {
if (e[0]) ar.push(e[0])
return ar;
}, []);
With both variables I get the FileId (which is in column W) but when I try to get the File by ID it doesn't work. Does anyone know how I can fix this issue?
Thank you so much in advance!
The script is:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var responses = ss.getSheetByName("CONTROL DE CALIDAD");
var mail = ss.getSheetByName("MAIL");
var active_range = responses.getActiveRange();
var control = responses.getRange(active_range.getRowIndex(), 16).getValue();
var prenda = responses.getRange(active_range.getRowIndex(), 5).getValue();
var codigo = responses.getRange(active_range.getRowIndex(), 4).getValue();
var explicacion = responses.getRange(active_range.getRowIndex(), 15).getValue();
var num_taras = responses.getRange(active_range.getRowIndex(), 14).getValue();
var uds_revisadas = responses.getRange(active_range.getRowIndex(), 13).getValue();
var ficha = responses.getRange(active_range.getRowIndex(), 23).getValue();
var attachment = DriveApp.getFileById(ficha);```

Google Scripts - View Log stuck at "Waiting for logs, please wait..."

I'm trying to run a script for my Google Sheet on Scripts, and a function isn't working properly. I have some loggers in place to check why this is happening, but anytime I try to open the Logs tab, I get this:
... and it's just stuck there forever.
Has anyone ever had this problem? Any potential fixes? Thanks
EDIT: My executions window looks like so:
EDIT 2: Here is the code I'm trying to run, with segment = 1. SPREADSHEETS is just a variable that I'm unfortunately not able to share, but it just contains some import segment information that directs to either 1 or 2.
function CopyPasteAllSheets(segment) {
for (x in SPREADSHEETS) {
if (SPREADSHEETS[x].IMPORTSEGMENT != segment) {
// DRR added app which is redundant to intakeSpreadhseet, but keeps logic more readable
app.toast('running loop')
console.log("ID: " + SPREADSHEETS[x].SOURCE.ID + "NO MATCH");
} else {
// Logger.log("x: "+ x) // keep commented out
var intakeSpreadsheet = SpreadsheetApp.openById(SPREADSHEETS[x].INTAKE.ID);
var intakeSheet = intakeSpreadsheet.getSheetByName(SPREADSHEETS[x].INTAKE.SHEET); //confirm formatting conventions
// This is functionally equivlent to the above, except we don't have a reference to intakeSpreadsheet anymore
// Access the Spreadsheet and sheet you want to copy the data TO
console.log("ID: "+ SPREADSHEETS[x].SOURCE.ID)
var sourceSpreadsheet = SpreadsheetApp.openById(SPREADSHEETS[x].SOURCE.ID);
var sourceSheet = sourceSpreadsheet.getSheetByName(SPREADSHEETS[x].SOURCE.SHEET);
var sourceStartRow = SPREADSHEETS[x].SOURCE.STARTROW;
var sourceStartCol = SPREADSHEETS[x].SOURCE.STARTCOL;
var sourceRangeCol = SPREADSHEETS[x].SOURCE.ENDCOL - SPREADSHEETS[x].SOURCE.STARTCOL + 1;
// Get the range of the data you want and the range where you want the data to go
var rowsToCopy = sourceSheet.getLastRow()-sourceStartRow+1; // is +1 too conservative, check...
var rangeToCopy = sourceSheet.getRange(sourceStartRow,sourceStartCol,rowsToCopy, sourceRangeCol);
var dataToCopy = rangeToCopy.getValues();
var numRows = rowsToCopy;
var numColumns = sourceRangeCol;
var intakeStartRow = SPREADSHEETS[x].INTAKE.STARTROW;
var intakeStartCol = SPREADSHEETS[x].INTAKE.STARTCOL;
var rangeToPaste = intakeSheet.getRange(intakeStartRow,intakeStartCol, numRows,numColumns); // WAS FORMERLY 1,20, ..,.. ~DRR 7/14
rangeToPaste.setValues(dataToCopy);
}
}
}

Apps Script getEventById() returns null

I am new to Apps Script and struggling with the "getEventById()" function.
My goal is to delete an event entry on Google Calendar via Google Sheets when you press a button.
I already managed to get the event id via Apps Script and it´s Google API V3, but when I hand it over to "getEventById" as parameter, it returns null, even when I "hardcode" the id.
Here´s my code. I removed some parts since those aren´t important I think:
function calDate(){
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var calId = spreadsheet.getRange("N1").getValue();
var calEvent = CalendarApp.getCalendarById(calId);
var ui = SpreadsheetApp.getUi();
var selection = spreadsheet.getSelection();
var selectedRow = selection.getActiveRange().getA1Notation();
var rowRange = sheet.getRange(selectedRow);
var rowNumber = rowRange.getRow();
var colRange = sheet.getRange(selectedRow);
var colNumber = colRange.getColumn();
if (colNumber !== 15){
//wait for showtime
}
else{
// its showtime
var combinedRange = "O" + rowNumber;
var sheetData = sheet.getRange(rowNumber, 3, 1, 15).getValues();
if(sheetData[0][12] == false){
var dateStart = new Date(sheetData[0][7]);
var dateEnd = new Date(sheetData[0][8]);
var KdName = sheetData[0][0];
var BV = event_id[0][4];
var combinedNames = KdName + " - " + BV;
var items = Calendar.Events.list(calId, {
timeMin: dateStart.toISOString(),
timeMax: dateEnd.toISOString(),
q: combinedNames
}).items;
}
else{
var testVar = calEvent.getEventById(/*This is where I would put the htmlLink (the event-id)*/);
console.log(testVar);
}
}
}
Hopefully those informations are enough and if not, feel free to ask for more.
I really hope you guys can help me out!
Kind regards
EDIT & SOLUTION
Okay guys, thanks to Mateo Randwolf, who kindly opened an issue at Google about this, I was able to figure it out. This is the link with an example how to get the the ID from the event and hand that id over to the "getEventById()" function. Or here as a code-block:
function findEventID() {
var now = new Date();
var nextEvent = new Date(now.getTime() + (2 * 60 * 60 * 1000));
var event = CalendarApp.getDefaultCalendar().getEvents(now, nextEvent);
ID = event[0].getId();
Logger.log('EventID: ' + event[0].getId());
Logger.log(CalendarApp.getDefaultCalendar().getEventById(ID));
}
Now it gets funny. This line:
Logger.log('EventID: ' + event[0].getId());
returns the event-id like it should.
But this one:
Logger.log(CalendarApp.getDefaultCalendar().getEventById(ID));
doesn´t show anything except "{}", which is weird.
But if you apply "deleteEvent()" on it, like so:
calEvent.getEventById(ID).deleteEvent(); //calEvent is a CalendarApp, see above
It actually deletes the event from the calendar!
With that, I´d say we found the solution or at least a bypass.
Issue
Hi ! So it seems to me that getEventById() has a bug that returns null instead of the event object as I was getting the exact same behaviour you were reporting in this question. I have filed this behaviour to the public issue tracker, you can find it here with all the discussion on this behaviour.
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)
Using the Calendar API search query to find events in a calendar
function calDate(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sh=ss.getActiveSheet();
var calId=ss.getRange("N1").getValue();
var calEvent=CalendarApp.getCalendarById(calId);
var row=ss.getActiveRange().getRow();
var col=ss.getActiveRange().getColumn()
if (col!=15){
//wait for showtime
}else{
var vs=sh.getRange(row, 3, 1, 15).getValues();
if(vs[0][12] == false){
var dateStart=new Date(vs[0][7]);//col J
var dateEnd=new Date(vs[0][8]);//col K
var KdName=vs[0][0];//col 3
event_id below is not defined
var BV=event_id[0][4];//col G
var combinedNames=KdName + " - " + BV;
var items=Calendar.Events.list(calId, {timeMin: dateStart.toISOString(),timeMax: dateEnd.toISOString(),q: combinedNames}).items;
}
else{
var testVar=calEvent.getEventById(/*This is where I would put the htmlLink (the event-id)*/);
console.log(testVar);
}
}
}
Since you couldn't share your spreadsheet I share mine with an example
One thing that helps a lot is playing with the API explorer to figure what works and what doesn't. If you want to display all of the fields you can use * and this example proved very helpful as well
Here's the code:
function myOwnEventSearch() {
var calendarId='***********calendar id**************';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Sheet235');
var sr=2;
var sc=2
var rg=sh.getRange(sr,sc,sh.getLastRow()-sr+1,sh.getLastColumn()-sc+1);
var vA=rg.getValues();
var hA=sh.getRange(sr-1,sc,1,sh.getLastColumn()-sc+1).getValues()[0];
var idx={};//locates the data index from column header names
hA.forEach(function(h,i){idx[h]=i;});
var cal=CalendarApp.getCalendarById(calendarId);
var html='<style>td,th{}</style><table><tr><th>Summary</th><th>Start</th><th>End</th><th>Id</th></tr>'
for(var i=0;i<vA.length;i++) {
if(!vA[i][idx['Id']] && vA[i][idx['DateFrom']] && vA[i][idx['DateTo']] && vA[i][idx['SearchString']]) {
var request={timeMin:new Date(vA[i][idx["DateFrom"]]).toISOString(),timeMax:new Date(vA[i][idx["DateTo"]]).toISOString(),q:vA[i][idx["SearchString"]],showDeleted: false,singleEvents:true,maxResults:10,orderBy:"startTime"};
var resp=Calendar.Events.list(calendarId, request);
if(resp.items.length>0) {
var idA=[];
resp.items.forEach(function(item,j){
html+=Utilities.formatString('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>', item.summary,item.start,item.end,item.id);
idA.push(item.id);
});
sh.getRange(i+sr,idx['Id']+sc).setValue(idA.join(', '))
}
}
}
html+='<table>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html).setWidth(800), "My Events")
}
Here's the spreadsheet before the script runs.
Here's the dialog that displays the search results.
Here's what the spreadsheet looks like after running script:
The Event Ids were copied into the Id Column
And these were the four events I created on my calendar::
Here is how I worked around this. I stored all the events (from the range I was interested in) in a JavaScript Map() so I can find them later:
var cal = CalendarApp.getCalendarById("/* supply your calendar ID here*/");
if (!cal) {
Logger.log("Calendar not found for ID:" + calendarID);
} else {
var calEvents = cal.getEvents(new Date("March 8, 2010"), new Date("March 14, 2025"));
// Store them by eventId for easy access later
var calEventMap = new Map();
for (var j in calEvents) {
calEventMap.set(calEvents[j].getId(), calEvents[j]);
}
/* Later when you need to look up by iCalID... */
var calEvent = calEventMap.get(eventID);
}
Works for me when you get the calendar by id like this:
const calendar = CalendarApp.getCalendarById("theCalendarId");
const event = calendar.getEventById("someEventId");
Now the event is not null, but the actual event, and you can do whatever you want with it from here!

Google app script Error could not parse text

I am trying to retrieve data by ID. Use the 3rd method in this link: How to speed ​up the search data in sheet
I run the function and err : Could not parse text.
I do not understand why I have used this method so many times and ran well, but this case is faulty.
This is my code:
function loadDataOfThread() {
var ss = SpreadsheetApp.openByUrl(url);
var ws = ss.getSheetByName("sheet1");
var ID = "12345";
var formatRange = ws.getRange(1, 1, ws.getLastRow() ,ws.getLastColumn()).setNumberFormat("#STRING#");
var query = "select * where A ='" + ID + "'";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/gviz/tq?gid=" + ws.getSheetId() + "&tqx=out:csv&tq=" + encodeURIComponent(query);
var options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
}
};
var csv = UrlFetchApp.fetch(url, options);
var f = Utilities.parseCsv(csv); // err this line
var dataArr = [];
if (f.length > 0) {
for (var i = 0; i < f.length; i++) {
dataArr.push(f[i][1]);
}
}
}
I think in a spreadsheet whose data type is the date time column and it make err my function but i have convert to string !!! I do not understand why ?
How about this answer? Your issue might be able to be removed with "PasteDataRequest" because "PasteDataRequest" is better than parseCsv() as the parser of CSV data. In this answer, I would like to propose a method for using "PasteDataRequest" of Sheets API. Please think of this as just one of several answers. The flow of this method is as follows.
Insert a sheet as a temporal sheet.
Put the CSV data to the inserted sheet using "PasteDataRequest" of Sheets API.
Retrieve values from the temporal sheet.
Delete the temporal sheet.
Modified script:
When your script is modified, please modify as follows.
Before you use this script, please enable Sheets API at Advanced Google services.
From:
var f = Utilities.parseCsv(csv);
To:
var temp = ss.insertSheet("temp");
var sheetId = temp.getSheetId();
var resource = {requests: [{pasteData: {data: csv.getContentText(), coordinate: {sheetId: sheetId}, delimiter: ","}}]};
Sheets.Spreadsheets.batchUpdate(resource, ss.getId());
var f = temp.getDataRange().getValues();
ss.deleteSheet(temp);
Note:
Of course, I think that the issue can be also removed by modifying csv of var csv = UrlFetchApp.fetch(url, options);. But from your question, I cannot image the values of your issue. So I proposed above method. If you want to use other method, can you provide a sample Spreadsheet for replicating your issue? Of course, please remove your personal information. By this, I would like to think of the issue.
References:
Method: spreadsheets.batchUpdate
PasteDataRequest
If I misunderstood your question and this was not the direction you want, I apologize.

UrlFetchApp query a spreadsheet with gviz

I am trying to query a spreadsheet with gviz (Google Visualization), using UrlFetchApp, but no result so far.
Could you help me to fix this code?
(the query Url works fine in the browser)
function queryTest() {
var onlyforscope = SpreadsheetApp.getActiveSpreadsheet();
var template = "https://docs.google.com/spreadsheets/d/%s/gviz/tq?gid=%s&tq=select C,E,K,M,N,O where C contains '%s'";
var query = Utilities.formatString(template, docId, sheetId, value);
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var r = UrlFetchApp.fetch(query, param).getContentText();
// var j = JSON.parse(r);
Logger.log(r);
return;
}
Thanks in advance, Fausto
it was trivial, though hard to find out for me
the required scope is Drive !!!
I just add this line and it worked
var onlyforscope = DriveApp.getRootFolder();