Classroom API IndividualStudentsOptions in Google Apps Script - javascript

Is it possible to use IndividualStudentsOptions object from Google Apps Script? I'm trying to create the object but returns this error
GoogleJsonResponseException: No se ha podido llamar a la API classroom.courses.courseWork.create; error: Invalid JSON payload received. Unknown name "individualStudentsOptions" at 'course_work': Proto field is not repeating, cannot start list.
It seems that is not possible from GAS.
function enviarclassdos(datos,alumnos){
// datos: object with needed variables for classroom publishing
// alumnos: individual students (array [students])
var stdid = []; //Array of IDs of individual students
//Getting the IDs of the individual students
var hojacuentas = SpreadsheetApp.openById("1oHlpSyRB913LWpj-UNTKattO").getSheetByName("CUENTAS");
var datacuentas = hojacuentas.getDataRange().getValues();
for(var al =0; al<alumnos.length; al++){
var alum = alumnos[al][0];
for (var dt=0; dt<datacuentas.length; dt++){
var alumdt = datacuentas[dt][0];
if (alumdt == alum){
var cuenta = datacuentas[dt][3];
stdid.push(cuenta);}}}
var curso = datos.curso;
var tipo = datos.tipo;
if (curso == "Primero A"){var id = "14085771****";}
if (curso == "Primero B"){var id = "14085996****";}
if (curso == "Segundo A"){var id = "14085996****";}
if (curso == "Segundo B"){var id = "14085996****";}
if (curso == "Cuarto AB"){var id = "14085996****";}
var titulo = datos.concepto;
var descripcion = datos.descripcion;
var fecha = datos.fecha;
var tema = datos.tipo
var ClassSource =
{
title: titulo,
description: descripcion,
state: "PUBLISHED",
workType: "ASSIGNMENT",
topicId: tema,
maxPoints: 100,
assigneeMode: "INDIVIDUAL_STUDENTS"
}
//This is the object that produces the error message
ClassSource.individualStudentsOptions = {studentIds:stdid};
var clss = Classroom.Courses.CourseWork;
var wrk = clss.create(ClassSource, id);
}

Instead of
ClassSource.individualStudentsOptions = [{studentIds:stdid}];
use
ClassSource.individualStudentsOptions = {studentIds:[stdid]};
Reference
https://developers.google.com/classroom/reference/rest/v1/IndividualStudentsOptions

Related

How to compare a value with each item of range

for the last 3 days (my first 3 days of coding) i've been trying to code an script to get my google contacts that have certain keyword, it being "Catamarca", on their name and also to delete that keyword after they've been added to the spreadsheet leaving only their name.
I've been succesfull in all of this. But now i want to only run the script on an existing database, and only run it if the new contacts are not on the sheet already, and not write over the existing ones.
Here is my code so far:
function impContacts() {
// variables
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GContacts");
var grupo = ContactsApp.getContactGroupById("http://www.google.com/m8/feeds/groups/email#gmail.com/base/6")
const contactos = grupo.getContacts();
const arraycontacts = [];
// get the last row on B with data on it
const lastRow = sheet.getLastRow();
const Avals = sheet.getRange("B2:B" + lastRow).getValues();
const Alast = lastRow - Avals.reverse().findIndex(c => c[0] != '');
Logger.log(Alast);
var rangeInteres = sheet.getRange(2, 1, Alast, sheet.getLastColumn()).getValues();
// look for contacts that has in their name the word "Catamarca", and save them with their id, name and phone.
contactos.forEach(contacto => {
var phone = ""
if (contacto.getPhones()[0]) {
phone = contacto.getPhones()[0].getPhoneNumber()
};
var name = ""
if (contacto.getFullName().match("Catamarca")){
name = contacto.getFullName();
};
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
const datoscont = [idcont, name, phone];
arraycontacts.push(datoscont);
})
// save new contact
sheet.getRange(2, 1, arraycontacts.length, 3).setValues(arraycontacts);
// look for "catamarca"
range = sheet.getRange("B2:B")
var textFind = range.createTextFinder("Catamarca");
textFind.matchEntireCell(false);
textFind.ignoreDiacritics(true);
textFind.matchCase(false);
var textFound = textFind.findNext();
// Si encuentra coincidencia reemplazar por ""
if (textFound !== null) {
var vals = textFound.getValues();
textFind.replaceAllWith("");
}
}
What i need to keep the most is the ID of the existing contacts (the IDs are different from the ones coming from google contacts but the names are the same), because they are linked to an app created using AppSheet.
I believe there should be a way to accomplish this by editing this part of the code
var idcont = ""
if (name == rangeInteres.forEach(namme =>
{
oldName = namme[1];
Logger.log(oldName);}))
{
idcont =
rangeInteres.forEach(id => {
oldId= id[0];
Logger.log(oldId);})
}
else
{
idcont = contacto.getId().replace(/\D/g, '')
};
In my head and with my current knowledge, the code should be working, but it's not, I mean, it runs, but overwrites everything.

How can I get all data in a unique message, from a sheet A from comparing two cells in different spreadsheet

I want to compare two cells in sheetA and SheetB like in the screens below to get the exact results (screen).
I've run a code, but it sends me multiple messages (Each single data row in a message) instead of a single message containing all the information (See results screen).
SheetA
SheetB
Results
Thank you in advance.
Here's the code I used :
function myFunction(){
var SheetA = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetA');
var SheetB = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetB');
var lr = SheetA.getLastRow();
for (i = 2; i < lr+1; i++){
var StoreB = SheetB.getRange(i,1).getValue();
var StoreA = SheetA.getRange(2,2).getValue();
var Activity = SheetA.getRange(2,4).getValue();
if (StoreA == StoreB && Activity == 'Actif'){
var order = SheetB.getRange(i,2).getValue();
var date_li = SheetB.getRange(i,4).getValue();
var date = Utilities.formatDate(new Date(date_li), 'Europe/Paris', 'dd/MM/yyyy');
var ref = SheetB.getRange(i,5).getValue();
var desi = SheetB.getRange(i,6).getValue();
var quantity = SheetB.getRange(i,7).getValue();
var livred = SheetB.getRange(i,8).getValue();
var email = SheetA.getRange(2,5).getValue();
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.email = email;
htmlTemplate.order = order;
htmlTemplate.date = date;
htmlTemplate.desi = desi;
htmlTemplate.ref = ref;
htmlTemplate.quantity = quantity;
htmlTemplate.livred = livred;
const htmlforEmail = htmlTemplate.evaluate().getContent();
console.log(htmlforEmail)
MailApp.sendEmail(
email,
'Modification date d\'inventaire',
"SVP Ouvrez ce mail avec le support HTML",
{htmlBody: htmlforEmail}
);
}
}
}
This is how I would do it but it will necessitate having to change the template so that it can handle a 2d array to place the data in to a table. Fortunately, the data also includes the first row of headers for the table.
function myFunction() {
const ss = SpreadsheetApp.getActive();
const sha = ss.getSheetByName('SheetA');//reference
const shb = ss.getSheetByName('SheetB');//order data
const hA = shb.getRange(1,1,1,8).getDisplayValues().flat().splice(2,1);
const vsb = shb.getRange(2, 1, shb.getLastRow() - 1, shb.getLastColumn()).getDisplayValues();
const StoreA = sha.getRange(2, 2).getValue();
const Activity = sha.getRange(2, 4).getValue();
const email = sha.getRange(2, 5).getValue();
const del = { pA: [] };
if (Activity == 'Actif') {
vsb.forEach((r, i) => {
let [st, order, , date_li, date, desi, quantity, livred] = r
if (StoreA == st) {
if (!del.hasOwnProperty(st)) {
del[st] = [];
del[st] = hA;//puts the titles into the data
del[st].push([r[0], r[1], r[3], r[4], r[5], r[6], r[7]]);
del.pA.push(st);
} else {
del[st].push([r[0], r[1], r[3], r[4], r[5], r[6], r[7]]);
}
}
});
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.order = del[st];
}
MailApp.sendEmail(email, 'Modification date d\'inventaire', "SVP Ouvrez ce mail avec le support HTML", { htmlBody: htmlTemplate.evaluate().getContent() });
}
Try this
function myFunction(){
var SheetA = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetA');
var SheetB = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetB');
var lr = SheetA.getLastRow();
var order = "";
var date_li = ""
var date = "";
var ref = "";
var desi = "";
var quantity = "";
var livred = "";
var email = "";
for (i = 2; i < lr+1; i++){
var StoreB = SheetB.getRange(i,1).getValue();
var StoreA = SheetA.getRange(2,2).getValue();
var Activity = SheetA.getRange(2,4).getValue();
if (StoreA == StoreB && Activity == 'Actif'){
order += SheetB.getRange(i,2).getValue()+'\n';
date_li += SheetB.getRange(i,4).getValue()+'n';
date += Utilities.formatDate(new Date(date_li), 'Europe/Paris', 'dd/MM/yyyy')+'\n';
ref += SheetB.getRange(i,5).getValue()+'\n';
desi += SheetB.getRange(i,6).getValue()+'\n';
quantity += (+SheetB.getRange(i,7).getValue());
livred = SheetB.getRange(i,8).getValue();
email = SheetA.getRange(2,5).getValue();
}
const htmlTemplate = HtmlService.createTemplateFromFile('Body');
htmlTemplate.email = email;
htmlTemplate.order = order;
htmlTemplate.date = date;
htmlTemplate.desi = desi;
htmlTemplate.ref = ref;
htmlTemplate.quantity = quantity;
htmlTemplate.livred = livred;
const htmlforEmail = htmlTemplate.evaluate().getContent();
console.log(htmlforEmail)
MailApp.sendEmail(
email,
'Modification date d\'inventaire',
"SVP Ouvrez ce mail avec le support HTML",
{htmlBody: htmlforEmail}
);
}
}
````

How to put variables inside a Json Array function in JS

I'm a beginner in Js and have a problem making a little program, I want to put the variables nome, document e Codigo, inside of the JSON array 'registros'
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var registro = [{
codigo: 0,
nome: "",
sexo: ""
}];
registro.push(codigo, nome, document);
}
You need to do a little adjustment in the salvar() function.
First, you can set each specific value of your "registro" var like this:
var registro = [{
codigo: codigo, //value = 1
nome: nome, //value = the innerText of document.getElementById("pNome")
sexo: ""
}];
Then, you use the push() function to insert "registro" into your "registros" array. Here is the full updated code:
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var registro = [{
codigo: codigo,
nome: nome,
sexo: ""
}];
registros.push(registro);
}
Array in JS comes in property/ value structure, and from your code you are assigning the values to a different variable registro instead of registros.
Moreover, the registros variable is never user.
To do this;
Create your array variable (registros)
Create a function (salvar)
Create an object that will hold your values, here nome in object will create a property name "nome" with the value being the value in nome which is document.get ...;
var obj = { "nome": document.getElementById("pNome").innerText.
Then push obj to array, registros
var registros = [];
var codigo = 1;
function salvar() {
var nome = document.getElementById("pNome").innerText;
var documento = document.getElementById("pDocumento").innerText;
var obj = { nome, documento, caodigo}
registros.push(obj);
}

You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI-

I intend to run my script on Google sheet
What I'm doing is to restore the values ​​of the cells, and use an if statement to compare an identifier cell with another userid cell.
If they are different, I want to eliminate that entire row, if they are equal I want to leaving the entire row as it is.
I get the error:
You can not convert CjwKEAjwiYG9BRCkgK-G45S323oSJABnykKAhI-
My code:
function myFunction() {
function Lento() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getActiveSheet();
var rows = sheet.getDataRange();
var values = rows.getValues();
var numCols = rows.getNumColumns();
var numRows = rows.getNumRows();
for (var r=1; r<values.length; r++) {
var row = values[r],
identificador = row[0],
palabraclave = row[1],
ciudad = row[2],
fecha = row[4],
pais = row[5],
idusuario = row[6],
nombre = row[7],
email = row[8],
telefono = row[9],
mensaje = row[10],
urllanding = row[11],
fechausuario = row[12];
Logger.log(identificador);
Logger.log(palabraclave);
Logger.log(ciudad);
Logger.log(fecha);
Logger.log(pais);
}
if (row[0] !== row[6]) {
spreadsheet.deleteRow(row);
}
}
Lento();
}
I think your problem is with spreadsheet.deleteRow(row). First, you want to delete the row on this particular sheet, so it should be sheet.deleteRow(...). The other problem is that deleteRow expects an integer as an argument, but you've provided row, which is an array. To delete the row, you want to do
sheet.deleteRow(r+1);
because r is the integer linked to the position in the array, not row. See the documentation on deleteRow(rowPosition):
https://developers.google.com/apps-script/reference/spreadsheet/sheet#deleterowrowposition
Now I have the solution to what I do.
as well as it gives errors since the comprovación of the array is null therefore not work , the code would look like .
function myFunction() {
function Lento() {
var h1 = SpreadsheetApp.getActive().getSheetByName('Hoja 1');
var h2 = SpreadsheetApp.getActive().getSheetByName('Hoja 2');
var rowsh1 = h1.getDataRange();
var valuesh1 = rowsh1.getValues();
var numColsh1 = rowsh1.getNumColumns();
var numRowsh1 = rowsh1.getNumRows();
var rowsh2 = h2.getDataRange();
var valuesh2 = rowsh2.getValues();
var numColsh2 = rowsh2.getNumColumns();
var numRowsh2 = rowsh2.getNumRows();
var idusuario = [];
var identificador = [];
//recorremos fila a fila y cogemos los datos de la hoja1
for (var r = 1; r < valuesh2.length; r++) {
var rowh2 = valuesh2[r],
nombre = rowh2[1],
email = rowh2[2],
telefono = rowh2[3],
mensaje = rowh2[4],
urllanding = rowh2[5],
fechausuario = rowh2[6];
idusuario[r] = rowh2[0]; //Guardamos los gclid del usuario en un array
}
//recorremos fila a fila y cogemos los datos de la hoja2
for (var r = 1; r < valuesh1.length; r++) {
var rowh1 = valuesh1[r],
palabraclave = rowh1[1],
ciudad = rowh1[2],
fecha = rowh1[4],
pais = rowh1[5];
identificador[r] = rowh1[0]; //Guardamos los gclid en un array
}
for (var i = identificador.length - 1; i >= 0; i--) {
var encontrado = false;
for (var y = 1; y < idusuario.length; y++) {
if (identificador[i] == null || idusuario[y] == null) continue;
if (identificador[i] == idusuario[y]) {
encontrado = true;
break;
}
}
if (!encontrado) {
h1.deleteRow(i + 1);
}
}
}
Lento();
}

returning nested json values using loop (google spreadsheet)

I have this google spreadsheet script that pulls in json formatted book data. I have no problem displaying book title and author, but he "offerData" object can contain a different amount of elements (prices from sellers) depending on the book. Right now I created a loop and am storing the offerData values like so:
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
and am returning the data like this:
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
Obviously this only returns 3 sellers with price, condition, seller info. The issue is that a book doesn't always have 3 sellers, it can be anywhere from 1 to 10 or so.
My question is how can I return all offerData (price/condition/seller) here? :
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
--
function getBookDetails(isbn) {
// Query the book database by ISBN code.
if (isbn !== "") {
var url = "https://api.bol.com/catalog/v4/search/?apikey=myapi6&offers=all&format=json&q=" + isbn;
var response = UrlFetchApp.fetch(url);
var results = JSON.parse(response);
if (results.totalResultSize) {
// There'll be only 1 book per ISBN
var book = results.products[0];
// get Title and Authors
var title = (results.products[0]["title"]);
var specstag = (results.products[0]["specsTag"]);
var offerdata = results.products[0]["offerData"];
if (typeof offerdata.offers !== 'undefined' && offerdata.offers.length > 0) {
var arrayLength = offerdata.offers.length;
var price = [];
var condition = [];
var seller = [];
for (var i = 0; i < arrayLength; i++) {
price[i] = offerdata.offers[i]["price"];
condition[i] = offerdata.offers[i]["condition"];
seller[i] = offerdata.offers[i]["seller"]["displayName"];
}
}
}
var resultRow = [[title, specstag, price[0], condition[0], seller[0], price[1], condition[1], seller[1], price[2], condition[2], seller[2]]];
return resultRow;
}
}
the answer
var resultRow = [];
resultRow[0] = [];
resultRow[0][0]=title;
resultRow[0][1]=specstag;
for (var i = 0; i < arrayLength; i=1+3) {
resultRow[0][3*i+2]=price[i];
resultRow[0][3*i+3]=condition[i];
resultRow[0][3*i+4]=seller[i];
}
how you should think about it is to see the index of the elements in the array and then find relation between i and the index you want
var resultRow = [
[
title, //[0][0]
specstag, //[0][1]
price[0], //[0][2]
condition[0], //[0][3]
seller[0], //[0][4]
price[1], //[0][5]
condition[1], //[0][6]
seller[1], //[0][7]
price[2], //[0][8]
condition[2], //[0][9]
seller[2]//[0][10]
]
];
You might be looking for something like this;
var data = { title: null,
spcstag: null,
pcs: [],
};
offerData.offers.forEach( p => { var pcsData = {};
!!data.title || data.title = p.title;
!!data.specstag || data.specstag = p.specstag;
pcsData.price = p.price;
pcsData.condition = p.condition;
pcsData.seller = p.seller;
data.pcs.push(pcsData);
});

Categories