my code doesn't work anymore but i haven't changed it - google-apps-script

i created several months ago a script to publish assignments for my students in google classroom.the code is the following
function createTrigger() {
// Trigger every day at 9
ScriptApp.newTrigger('pubblicavideo')
.timeBased()
.atHour(9)
.everyDays(1) // Frequency is required if you are using atHour() or nearMinute()
.create();
}
function onOpen() {
//aggiunge il bottone autotrigger con run e stop all'apertura del documento spreadsheet
var ui = SpreadsheetApp.getUi();
ui.createMenu("Auto Trigger")
.addItem("Run","runAuto")
.addItem("Stop","deleteTrigger")
.addToUi();
}
function runAuto() {
// resets the loop counter if it's not 0
refreshUserProps();
// clear out the sheet
clearData();
// create trigger to run program automatically
createTrigger();
}
function refreshUserProps() {
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('loopCounter', 0);
userProperties.setProperty('contarighe', 1);
}
function deleteTrigger() {
// Loop over all triggers and delete them
var allTriggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < allTriggers.length; i++) {
ScriptApp.deleteTrigger(allTriggers[i]);
}
}
function pubblica(k)
{
var corso = Classroom.Courses.get(XXXXXXXXXXXXXX);
var foglio = SpreadsheetApp.getActive();
var linkini = foglio.getRange("C709:C3014");
var titolini = foglio.getRange("B709:B3014");
var autorini = foglio.getRange("A709:A3014");
var cell = linkini.getCell(k, 1);
var cella = titolini.getCell(k, 1);
var cello = autorini.getCell(k, 1);
var link = cell.getValue();
var titolo = cella.getValue();
var autore = cello.getValue();
var courseWork = {
'title': titolo,
'description': autore,
'materials': [
{'link': { "url": link}}
],
'workType': 'ASSIGNMENT',
'state': 'PUBLISHED',
}
Classroom.Courses.CourseWork.create(courseWork,XXXXXXXXXXXXXX);
}
function clearData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Data');
// clear out the matches and output sheets
var lastRow = sheet.getLastRow();
if (lastRow > 1) {
sheet.getRange(2,1,lastRow-1,1).clearContent();
}
}
function pubblicavideo()
{
var pezzialgiorno = 3; //numero di pezzi da pubblicare ogni giorno
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Data');
var userProperties = PropertiesService.getUserProperties();
var loopCounter = Number(userProperties.getProperty('loopCounter'));
var contarighe = Number(userProperties.getProperty('contarighe'));
// put some limit on the number of loops
// could be based on a calculation or user input
// using a static number in this example
var limit = 2301;
// if loop counter < limit number, run the repeatable action
if (loopCounter < limit) {
// see what the counter value is at the start of the loop
Logger.log(loopCounter);
// do stuff
for (var i=0; i<pezzialgiorno; i++)
{
pubblica(contarighe);
contarighe++;
}
// increment the properties service counter for the loop
loopCounter +=1;
userProperties.setProperty('loopCounter', loopCounter);
userProperties.setProperty('contarighe', contarighe);
// see what the counter value is at the end of the loop
Logger.log(loopCounter);
Logger.log(contarighe);
}
// if the loop counter is no longer smaller than the limit number
// run this finishing code instead of the repeatable action block
else {
// Log message to confirm loop is finished
sheet.getRange(sheet.getLastRow()+1,1).setValue("Finished");
Logger.log("Finished");
// delete trigger because we've reached the end of the loop
// this will end the program
deleteTrigger();
}
}
where i put the XXXXXXXXXXX there is the course ID.
the script is attached to a spreadsheet with 3 columns that have title, author and youtube link and the assignment is one of these videos put there as a link attached to the material. the script should publish every day at 9:00 a.m. 3 of the youtube videos in 3 different materials running down the list in the spreadsheet
when i try to execute the function called pubblicavideo it says
GoogleJsonResponseException: Chiamata API a classroom.courses.courseWork.create non riuscita con errore: Invalid value at 'course_work.description' (TYPE_STRING), 883 (riga 69, file "Codice")
i think the translation in english goes something like
GoogleJsonResponseException: API call to classroom.courses.courseWork.create didn't work with error: Invalid value at 'course_work.description' (TYPE_STRING), 883 (row 69, file "Code")
this very script worked perfectly until the 13th of august. i don't know if there were any changes in google classroom scripts.
anyone of you knows how to make it work again?

Answer:
The issue seems to be that at some point, the type of the value obtained from autorini.getCell(k, 1).getValue() is not a string which is causing the error.
Steps to Solve:
In pubblicavideo(), the function pubblica() is called inside a loop with the variable contarighe passed. The value of this gets put into k for each run of pubblica.
These are the lines that are problematic:
var autorini = foglio.getRange("A709:A3014");
var cello = autorini.getCell(k, 1);
var autore = cello.getValue();
You will need to check the value of autore before you make the request to Classroom.Courses.CourseWork.create().
As per the documentation on the CourseWork Resource, the value of description should be of type String.
When creating the coursework object:
var courseWork = {
'title': titolo,
'description': autore,
'materials': [
{'link': { "url": link}}
],
'workType': 'ASSIGNMENT',
'state': 'PUBLISHED',
}
The value of autore must reflect this. Make sure that at whatever point in the loop your code is halting, your sheet value is both of type String, and being retrieved correctly.
References:
REST Resource: courses.courseWork | Classroom API | Google Developers

Related

Storing an array of values from Docs in Google Apps Scripts

I'm a beginner working with Google Apps Script to pull data from a Google Doc, and I need some help...
I have a Google Doc that has a ton of cooking recipes. I'd like to write a function that randomly selects 4 recipes, and emails me the ingredients so I know what to shop for that week. All my recipes titles are 'Heading 3', with the ingredients as bullet points below them. I'm fully open to modifying the formatting if need be.
I think I have a way to identify all text that is of type 'Heading 3', but I need a way to store them in an array as text, to then randomly select 4 of them. I can't seem to solve this...
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Generate Weekly Shopping List')
.addItem('Send Email', 'generateMenu')
.addToUi();
}
function generateMenu() {
var ps = DocumentApp.getActiveDocument().getBody()
var searchType = DocumentApp.ElementType.PARAGRAPH;
var searchHeading = DocumentApp.ParagraphHeading.HEADING3;
var searchResult = null;
while (searchResult = ps.findElement(searchType, searchResult)) {
var par = searchResult.getElement().asParagraph();
if (par.getHeading() == searchHeading) {
// Found one, update Logger.log and stop.
var h = searchResult.getElement().asText().getText();
return h;
//how do I store this back into an array...then randomly select 4?
}
// Get the email address of the active user - that's you.
var email = Session.getActiveUser().getEmail();
// Send yourself an email with a link to the document.
GmailApp.sendEmail(email, "Shopping List For The Week", "Here is the shopping list:" + h);
}
}
The first function generates an array of objects from your document
function generateObj() {
var body = DocumentApp.getActiveDocument().getBody()
var children=body.getNumChildren();
//var html='';
var rObj={rA:[]}
for(var i=0;i<children;i++) {
var child=body.getChild(i);
if(child.getType()==DocumentApp.ElementType.PARAGRAPH && child.asParagraph().getHeading()==DocumentApp.ParagraphHeading.HEADING3 && child.asParagraph().getText().length>0) {
//html+='<br />' + child.asParagraph().getText();
var prop=child.asParagraph().getText();
rObj.rA.push(prop);
rObj[prop]=[];
var n=1;
while(body.getChild(i+n).getType()==DocumentApp.ElementType.LIST_ITEM) {
//html+='<br />'+body.getChild(i+n).asListItem().getText();
rObj[prop].push(body.getChild(i+n).asListItem().getText());
n++;
}
i+=n-1;
}
}
//DocumentApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Results')
return rObj;
}
//defaults to 4 selections
function pikn(n=4) {
var rObj=generateObj();//get array of objects
var rA=[];
var t=rObj.rA.slice();//copy array to temp array
for(var i=0;i<n;i++) {
var idx=Math.floor(Math.random()*t.length);//pick random index
rA.push(t[idx]);//save title of recipe
t.splice(idx,1);//remove that index
}
var s='';
//loop through selected recipes which are also object properties
rA.forEach(function(r,i){
var items=rObj[r];
s+='\n' + r;
items.forEach(function(item,j){s+='\n' + item});//loop through recipe items and collect everything in s as simple text to insert into standard body
});
GmailApp.sendEmail("Your email address","Random Recipes",s);
}
Requires Chrome V8

Google Apps Script API iterate/ loop through ID individually

i have an endpoint that i need to go through X number of times (dependent on how many IDs), Each call will need to assign its individual LineItem ID and bring back a JSON response.
I have tried the following code, and it seems I can call the API but can't seem to figure out how to translate the response back to my sheet, so in the case below i may have upto 10 LI ids that will need to be called up individually > results brought back> copied to last row of a particular range and then the next API call with the next LI id, etc...
function ListLI360API_Agetest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('MySheet');
var adID = 1558211;
var LIs =sheet.getRange(2, 3, sheet.getLastRow(), 1).getValues().filter(String);
var LIArrayLength = LIs.length;
for (var i = 0; i <= LIArrayLength; i++) {
if(LIs[i]!== undefined){
var url = 'https://displayvideo.googleapis.com/v1/advertisers/'+adID+'/lineItems/'+LIs[i]+'/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions'
//Logger.log(url);
var response = callApi5 (url, 'GET');
//Logger.log(response);
var content = response.getContentText();
//Logger.log(content);
var json = JSON.parse(content);
//Logger.log(json);
var ageData = json["assignedTargetingOptions"];
//Logger.log(ageData);
var rows = [],
data;
for (i = 0; i <= ageData.length; i++) {
data = ageData[i];
rows.push([data.name]);
}
//save results to spreadsheet in the next blank column and then API for next LI ID
Logger.log(rows);
}
}//endfor
}
I seem to be getting stuck on reading the results, i have tried with the following added into the script above but i get an error
"TypeError: Cannot read property "name" from undefined", im guessing there are some nulls/ blanks being returned in the JSON and hence it cant read the length
JSON looks like...
[20-06-24 21:34:57:159 BST] {
"assignedTargetingOptions": [
{
"name": "advertisers/1558211/lineItems/36917016/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503004",
"assignedTargetingOptionId": "503004",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_45_54",
"targetingOptionId": "503004"
}
},
{
"name": "advertisers/1558211/lineItems/36917016/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503005",
"assignedTargetingOptionId": "503005",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_55_64",
"targetingOptionId": "503005"
}
},
{
"name": "advertisers/1558211/lineItems/36917016/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503006",
"assignedTargetingOptionId": "503006",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_65_PLUS",
"targetingOptionId": "503006"
}
}
]
}
[20-06-24 21:34:57:694 BST] {
"assignedTargetingOptions": [
{
"name": "advertisers/1558211/lineItems/36917017/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503004",
"assignedTargetingOptionId": "503004",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_45_54",
"targetingOptionId": "503004"
}
},
{
"name": "advertisers/1558211/lineItems/36917017/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503005",
"assignedTargetingOptionId": "503005",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_55_64",
"targetingOptionId": "503005"
}
},
{
"name": "advertisers/1558211/lineItems/36917017/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions/503006",
"assignedTargetingOptionId": "503006",
"targetingType": "TARGETING_TYPE_AGE_RANGE",
"inheritance": "NOT_INHERITED",
"ageRangeDetails": {
"ageRange": "AGE_RANGE_65_PLUS",
"targetingOptionId": "503006"
}
}
]
}
From this Example there are 2 LI Ids so 2 separate outputs, i need to take parts of these outputs and print them into the spreadsheet
API function looks like...
function callApi5(url, methodType, requestBody) {
var service = getService();
if (service.hasAccess()) {
var headers = {
'Content-Type': 'application/json',
'Accept' :'application/json',
'Authorization': 'Bearer ' + getService().getAccessToken()
};
var options = {
method: methodType,
headers : headers,
muteHttpExceptions: true
};
if (requestBody) {
options.payload = requestBody;
}
return UrlFetchApp.fetch(url, options);
} else {
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s',
authorizationUrl);
}
}
function getService() {
// Create a new service with the given name. The name will be used when
// persisting the authorized token, so ensure it is unique within the
// scope of the property store.
return OAuth2.createService('MyService')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
// Set the client ID and secret, from the Google Developers Console.
.setClientId("xxxxx.apps.googleusercontent.com")
.setClientSecret("xxxxxx")
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
// Set the scopes to request (space-separated for Google services).
// this is blogger read only scope for write access is:
.setScope('https://www.googleapis.com/auth/display-video')
// Below are Google-specific OAuth2 parameters.
// Sets the login hint, which will prevent the account chooser screen
// from being shown to users logged in with multiple accounts.
.setParam('login_hint', 'xxxx#xxxs.com')
// Requests offline access.
.setParam('access_type', 'offline')
// Forces the approval prompt every time. This is useful for testing,
// but not desirable in a production application.
.setParam('approval_prompt', 'force');
}
I believe your goal as follows.
You want to retrieve the values from all requests, which used the URLs created by 'https://displayvideo.googleapis.com/v1/advertisers/'+adID+'/lineItems/'+LIs[i]+'/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions', and put them to the Spreadsheet.
For this, how about this answer? From your question, I thought that your script of callApi5() works and json of var json = JSON.parse(content); is the value you showed in your question. So I would like to propose to modify the function of ListLI360API_Agetest.
Modification points:
When the array is used in the for loop, please loop from 0 to array.length - 1. Because the 1st index of array is 0. So, when for (var i = 0; i <= LIArrayLength; i++) is used, an error occurs at the last loop of LIArrayLength. In this case, please modify to for (var i = 0; i < LIArrayLength; i++). Also, this can be said for for (i = 0; i <= ageData.length; i++) {.
In your script, 1 for loop is included in the for loop. And, each loop uses the variable i. In this case, the variables of i of each loop are affected. By this, the loop cannot be correctly worked.
I think that your error of TypeError: Cannot read property "name" from undefined might be due to above 2 points.
LIs of var LIs =sheet.getRange(2, 3, sheet.getLastRow(), 1).getValues().filter(String); is 2 dimensional array. So in this case, I think that LIs[i][0] is suitable instead of LIs[i].
When above points are reflected to your script, it becomes as follows.
Modified script:
Please copy and paste the following script, and set the destination sheet name to the last line of ss.getSheetByName("###").getRange(1, 10, result.length, 1).setValues(result);.
function ListLI360API_Agetest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('MySheet'); // Modified
var adID = 1558211;
var LIs = sheet.getRange(2, 3, sheet.getLastRow(), 1).getValues().filter(String);
var LIArrayLength = LIs.length;
var result = []; // Added
for (var i = 0; i < LIArrayLength; i++) { // Modified
if (LIs[i][0] !== undefined) { // Modified
var url = 'https://displayvideo.googleapis.com/v1/advertisers/'+adID+'/lineItems/'+LIs[i][0]+'/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions' // Modified
var response = callApi5 (url, 'GET');
var content = response.getContentText();
var json = JSON.parse(content);
var ageData = json["assignedTargetingOptions"];
for (var j = 0; j < ageData.length; j++) { // Modified
var data = ageData[j];
result.push([data.name]); // Modified
}
}
}
// Please set the destination sheet name.
ss.getSheetByName("###").getRange(1, 1, result.length, 1).setValues(result); // Added
}
If data.name is not existing, you don't want to put the values, please modify result.push([data.name]); to if (data.name) result.push([data.name]);.
Note:
In this modified script, it supposes that the structure of JSON object retrieved from each URL is the same. If the structure is different for each URL created by LIs[i][0], it is required to modify the script. Please be careful this.
I couldn't understand the result situation that the values are put to the Spreadsheet from your question. So in this modified script, the values are put to the destination sheet. If this is different from your actual situation, please modify the script.
References:
Array
getValues()
I have tested the answer provided by Tanike and modified the last part to be able to print to the spreadsheet. I have added a few more fields from JSON to test this, and finally added:
dataRange = sheet.getRange(lr+1, 17, result.length,result[0].length).setValues(result);
to print onto the spreadhseet.
function ListLI360API_Agetest(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('MySheet'); // Modified
var adID = 1558211;
var LIs = sheet.getRange(2, 3, sheet.getLastRow(), 1).getValues().filter(String);
var LIArrayLength = LIs.length;
var result = []; // Added
var lr = sheet.getRange('Q1').getDataRegion().getLastRow(); //Added
for (var i = 0; i < LIArrayLength; i++) { // Modified
if (LIs[i][0] !== undefined) { // Modified
var url = 'https://displayvideo.googleapis.com/v1/advertisers/'+adID+'/lineItems/'+LIs[i][0]+'/targetingTypes/TARGETING_TYPE_AGE_RANGE/assignedTargetingOptions' // Modified
var response = callApi5 (url, 'GET');
var content = response.getContentText();
var json = JSON.parse(content);
var ageData = json["assignedTargetingOptions"];
for (var j = 0; j < ageData.length; j++) { // Modified
var data = ageData[j];
result.push([
data.name,
data.assignedTargetingOptionId,
data.ageRangeDetails.ageRange]); // Modified
}
}
}
// Each Set of results is pushed one after another
dataRange = sheet.getRange(lr+1, 17, result.length,result[0].length).setValues(result);//Modified
}

This script does not populate sheet after parsing retrieved data

I hope this is well explained. First of all, sorry because my coding background is zero and I am just trying to "fix" a previously written script.
Problem The script does not populate sheet after parsing retrieved data if the function is triggered by timer and the sheet is not open in my browser .
The script works OK if run it manually while sheet is open.
Problem details:
When I open the sheet the cells are stuck showing "Loading" and after a short time, data is written.
Expected behavior is to get the data written no matter if I don't open the sheet.
Additional info: This is how I manually run the function
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [
{name: "Manual Push Report", functionName: "runTool"}
];
sheet.addMenu("PageSpeed Menu", entries);
}
Additional info: I set the triggers with Google Apps Script GUI See the trigger
Before posting the script code, you can see how the cells look in the sheet:
Script code
function runTool() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var rows = activeSheet.getLastRow();
for(var i=3; i <= rows; i++){
var workingCell = activeSheet.getRange(i, 2).getValue();
var stuff = "=runCheck"
if(workingCell != ""){
activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");
}
}
}
// URL check //
function runCheck(Url) {
var key = "XXXX Google PageSpeed API Key";
var strategy = "desktop"
var serviceUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=" + Url + "&key=" + key + "&strategy=" + strategy +"";
var array = [];
var response = UrlFetchApp.fetch(serviceUrl);
if (response.getResponseCode() == 200) {
var content = JSON.parse(response.getContentText());
if ((content != null) && (content["lighthouseResult"] != null)) {
if (content["captchaResult"]) {
var score = content["lighthouseResult"]["categories"]["performance"]["score"];
} else {
var score = "An error occured";
}
}
array.push([score,"complete"]);
Utilities.sleep(1000);
return array;
}
}
You can try the code using the sheet below with a valid Pagespeed API key.
You only need to add a Trigger and wait for it's execution while the sheet is not open in your browser
https://docs.google.com/spreadsheets/d/1ED2u3bKpS0vaJdlCwsLOrZTp5U0_T8nZkmFHVluNvKY/copy
I suggest you to change your algorithm. Instead of using a custom function to call UrlFetchApp, do that call in the function called by a time-driven trigger.
You could keep your runCheck as is, just replace
activeSheet.getRange(i, 3).setFormulaR1C1(stuff + "(R[0]C[-1])");
by
activeSheet.getRange(i, 3, 1, 2).setValues(runCheck(url));
NOTE
Custom functions are calculated when the spreadsheet is opened and when its arguments changes while the spreadsheet is open.
Related
Cache custom function result between spreadsheet opens

How do i get event.getEventById('id') or event.getEventSeriesById('id') to return anything other than null

Is there a way to make the .getEventById or .getEventSereiesById return anyhting other than null? I get valid ID for the initial event creation and can make that into a full functional URL but cannot use it in its native environment for its native purpose.
I am trying to make a basic google sheets schedule system that can refer to the calendar invite to check for changes and update the sheet or vise versa based on which side is further out in time. The system will be used in an environment where the scheduling has multiple users and meetings can be moved around a lot, generally further out in time. Everything works right up until i try to get information from the calendar even, .getStartTime(), due to the .getEvent calls returning null. not sure how to fix what other sources are telling me is a nonfunctional command that yet still "functions as intended".
function IEPscheduler() {
var spreadsheet = SpreadsheetApp.getActiveSheet(); // call sheet
//var calendarID = spreadsheet.getRange("H1").getValue();
var eventCal = CalendarApp.getCalendarById("mascharterschool.com_0edapns33khde9ig0di31i2mvc#group.calendar.google.com");
var signups = spreadsheet.getRange("A2:C2").getValues();
var lr = spreadsheet.getLastRow();
var lc = spreadsheet.getLastColumn(); //
var count = spreadsheet.getRange(2,1,lr-1,lc-1).getValues();// get meeting data
for (x=0; x<count.length; x++){
var shift = count[x]; // pull row from meeting data
var Start = shift[0];
var End = shift[1];
var Student = shift[2];
var guests = shift[3];
var description = shift[4];
var location = shift[5];
var run=shift[6]; // run following based on status column
// new meeting is scheduled
if(run == null || run == ''){
var event = {
'location': location,
'description':description ,
'guests':guests +',',
'sendInvites': 'True',
}
var invite = eventCal.createEvent(Student, Start, End, event);
invite.setGuestsCanInviteOthers(true); // allow guests to invite others
var eventId = invite.getId();
var date = invite.getDateCreated();
spreadsheet.getRange(x+2,7).setValue('Invite created'); // set status in sheet
spreadsheet.getRange(x+2,8).setValue(date); // inital date for created meeting invite
spreadsheet.getRange(x+2,9).setValue(eventId);
}
// check existing meetings for updates
else {
var id = shift[9];
var invite = eventCal.getEventSeriesById('id');
// if the time or location has changed update calander
if(invite.getStartTime() !== Start || invite.getEndTime() !== End || invite.getLocation() !== location){
// if sheet override flagged
if(shift[lc-1] !== null || Shift[lc-1] !== ''){
invite.setTime(Start,End); // update start/end time
invite.setLocation(location); // update location
}
// if canalder invite is further out than spreadsheet --> update spreadsheet
if(invite.getStartTime() >> Start){
spreadsheet.getRange(x+2,1).setValue();
spreadsheet.getRange(x+2,2).setValue();
}
// if spread sheet time is later than invite --> updater invite
else{
invite.setTime(Start,End); // update start/end time
invite.setLocation(location); // update location
}
var date = invite.getLastUpdate();
spreadsheet.getRange(x+2,7).setValue('Updated'); // set new status in sheet
spreadsheet.getRange(x+2,8).setValue(date); // set date meeting was updated
}
// if guest list has changed ???
if
}
}
}
// set script to be runnable from sheet tool bar
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Sync to Calendar') // tool bar banner
.addItem('Create Events Now', 'IEPscheduler') // sub catageory (title, function to run)
.addToUi();
}
We actually figured it out shortly after posting and I couldn't get back to this. Turns out the ID from .getId is the iCalUID and the .getEventById() takes a iCalID. The difference is that the UID has '#google.com' appended to the end of the ID. Split at the '#' and the get event works perfectly.
It's a stupid quirk that the getId command returns the right data in a useless form that requires editing to be used for its intended purpose.
No nulls returned for me with this script:
function getEvents() {
const cal=CalendarApp.getDefaultCalendar();
const dt=new Date();
const start=new Date(dt.getFullYear(),dt.getMonth()-1,dt.getDate());
const end=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate());
var events=cal.getEvents(start, end);
let eObj={idA:[],tA:[]}
events.forEach(function(ev,i){
eObj.idA.push(ev.getId());
eObj.tA.push(cal.getEventById(ev.getId()).getTitle());
});
Logger.log(JSON.stringify(eObj));
return eObj;
}

Ignore same-thread emails that have different labels

I am writing the Date and Subject from specific new emails to a new row of a Google Sheet.
I apply a label to the new mail items with a filter.
the script processes those labeled emails
the label is removed
A new label is applied, so that these emails won't be processed next time.
Problem: When there is a myLabel email, the script processes all emails in the same thread (eg same subject and sender) regardless of their label (even Inbox and Trash).
Question: How to only process new emails i.e. ones with the label myLabel - even when the thread of those messages extends outside the myLabel folder?
My current script:
function fetchmaildata() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('mySheetName');
var label = GmailApp.getUserLabelByName('myLabel');
var threads = label.getThreads();
for (var i = 0; i < threads.length; i++)
{
var messages = threads[i].getMessages();
for (var j = 0; j < messages.length; j++)
{
var sub = messages[j].getSubject();
var dat = messages[j].getDate();
ss.appendRow([dat, sub])
}
threads[i].removeLabel(label);
threads[i].addLabel(newlabel);
}
}
I hacked a solution for my purposes by changing my for loop to this:
for (var j = messages.length-1; j > messages.length-2; j--)
This says to process only the latest email in the thread, even when there is more than one email of a thread in the myLabel folder. Oddly, the script still changes the Labels of all the myLabel emails, but only the latest one of a thread gets written to the spreadsheet, so it works for me.
I had to make another change to the code because the above code does not run as a time-triggered scheduled task. I changed the code in this way and it now runs on a time schedule !!
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var ss = SpreadsheetApp.openById("myGoogleSheetID");
A label can be on a thread due to being on a single message in said thread. Your code simply goes label -> all label threads -> all thread messages, rather than accessing only the messages in a thread with a given label. That's not really your fault - it's a limitation of the Gmail Service. There are two approaches that you can use to remedy this behavior:
The (enable-before-use "advanced service") Gmail REST API
The REST API supports detailed querying of messages, including per-message label status, with Gmail.Users.Messages.list and the labelIds optional argument. For example:
// Get all messages (not threads) with this label:
function getMessageIdsWithLabel_(labelClass) {
const labelId = labelClass.getId();
const options = {
labelIds: [ labelId ],
// Only retrieve the id metadata from each message.
fields: "nextPageToken,messages/id"
};
const messages = [];
// Could be multiple pages of results.
do {
var search = Gmail.Users.Messages.list("me", options);
if (search.messages && search.messages.length)
Array.prototype.push.apply(messages, search.messages);
options.pageToken = search.nextPageToken;
} while (options.pageToken);
// Return an array of the messages' ids.
return messages.map(function (m) { return m.id; });
}
Once using the REST API, there are other methods you might utilize, such as batch message label adjustment:
function removeLabelFromMessages_(messageIds, labelClass) {
const labelId = labelClass.getId();
const resource = {
ids: messageIds,
// addLabelIds: [ ... ],
removeLabelIds: [ labelId ]
};
// https://developers.google.com/gmail/api/v1/reference/users/messages/batchModify
Gmail.Users.Messages.batchModify(resource, "me");
}
Result:
function foo() {
const myLabel = /* get the Label somehow */;
const ids = getMessageIdsWithLabel_(myLabel);
ids.forEach(function (messageId) {
var msg = GmailApp.getMessageById(messageId);
/* do stuff with the message */
});
removeLabelFromMessages_(ids, myLabel);
}
Recommended Reading:
Advanced Services
Gmail Service
Messages#list
Message#batchModify
Partial responses aka the 'fields' parameter
Tracked Processing
You could also store each message ID somewhere, and use the stored IDs to check if you've already processed a given message. The message Ids are unique.
This example uses a native JavaScript object for extremely fast lookups (vs. simply storing the ids in an array and needing to use Array#indexOf). To maintain the processed ids between script execution, it uses a sheet on either the active workbook, or a workbook of your choosing:
var MSG_HIST_NAME = "___processedMessages";
function getProcessedMessages(wb) {
// Read from a sheet on the given spreadsheet.
if (!wb) wb = SpreadsheetApp.getActive();
const sheet = wb.getSheetByName(MSG_HIST_NAME)
if (!sheet) {
try { wb.insertSheet(MSG_HIST_NAME).hideSheet(); }
catch (e) { }
// By definition, no processed messages.
return {};
}
const vals = sheet.getSheetValues(1, 1, sheet.getLastRow(), 1);
return vals.reduce(function (acc, row) {
// acc is our "accumulator", and row is an array with a single message id.
acc[ row[0] ] = true;
return acc;
}, {});
}
function setProcessedMessages(msgObject, wb) {
if (!wb) wb = SpreadsheetApp.getActive();
if (!msgObject) return;
var sheet = wb.getSheetByName(MSG_HIST_NAME);
if (!sheet) {
sheet = wb.insertSheet(MSG_HIST_NAME);
if (!sheet)
throw new Error("Unable to make sheet for storing data");
try { sheet.hideSheet(); }
catch (e) { }
}
// Convert the object into a serializable 2D array. Assumes we only care
// about the keys of the object, and not the values.
const data = Object.keys(msgObject).map(function (msgId) { return [msgId]; });
if (data.length) {
sheet.getDataRange().clearContent();
SpreadsheetApp.flush();
sheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}
}
Usage would be something like:
function foo() {
const myLabel = /* get label somehow */;
const processed = getProcessedMessages();
myLabel.getThreads().forEach(function (thread) {
thread.getMessages().forEach(function (msg) {
var msgId = msg.getId();
if (processed[msgId])
return; // nothing to do for this message.
processed[msgId] = true;
// do stuff with this message
});
// do more stuff with the thread
});
setProcessedMessages(processed);
// do other stuff
}
Recommended Reading:
Is checking an object for a key more efficient than searching an array for a string?
Array#reduce
Array#map
Array#forEach