List More than 30 records in Google classroom API - google-apis-explorer

I am newBaby to Google Classroom API and have written code to pull information from Goggle classroom API but it seems only 30 rows are pull and i needed to get all records. I have more than 30 students in few course.
Also have tried for pageTokens and Next Page Token from this forum but the example provided is not enough. Can somebody change my below code and give me correct code in which all records are pulls.
function listdetails() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var optionalArgs = {
pageSize: 0
};
//var response = Classroom.Courses.list();
var courses = Classroom.Courses.list(optionalArgs).courses;
for (var c = 0; c < courses.length; c++) {
var course = courses[c];
var courseName = course.name;
var courseId = course.id;
var students = Classroom.Courses.Students.list(courseId).students;
var teachers = Classroom.Courses.Teachers.list(courseId).teachers;
// var courseworks = Classroom.Courses.CourseWork.list(courseId).courseWork;
var topics = Classroom.Courses.Topics.list(courseId).topic;
ss.insertSheet(course.name);
ss.getRange("A1").setValue('Course Id')
ss.getRange("B1").setValue('Course Name');
ss.getRange("C1").setValue('Student Id');
ss.getRange("D1").setValue('Student Name');
ss.getRange("E1").setValue('Student Email');
ss.getRange("F1").setValue('Teacher Id')
ss.getRange("G1").setValue('Teacher Name')
ss.getRange("H1").setValue('Course Work Due Date')
ss.getRange("I1").setValue('Course Work Topic Id')
ss.getRange("J1").setValue('Course Work Max Points')
ss.getRange("K1").setValue('Course Work Assignment')
ss.getRange("L1").setValue('Course Work Multiple choice questions')
ss.getRange("M1").setValue('Topic Course Id')
ss.getRange("N1").setValue('Topic Id')
ss.getRange("O1").setValue('Topic Name')
ss.getRange("P1").setValue('Topic Update Time')
ss.getActiveSheet().getRange(1,1,1,16).setFontSize(12).setFontWeight('bold');
ss.setFrozenRows(1);
for( var i = 0; i<students.length; i++)
for(var t = 0; t<teachers.length; t++)
// for(var w = 0; w<courseworks.length; w++)
for(var tp = 0; tp<topics.length; tp++)
{
var student = students[i];
var profile = student.profile;
var sid = profile.id
var fullname = profile.name.fullName;
var email = profile.emailAddress;
var teacher = teachers[t];
var tprofile = teacher.profile;
var tid = tprofile.id;
var tname = tprofile.name.fullName;
// var coursework = courseworks[w];
// var cwduedate = coursework.dueDate;
// var cwtopicid = coursework.topicId;
// var cwmaxpoints = coursework.maxPoints;
// var cwassignment = coursework.assignment;
// var cwmcq = coursework.multipleChoiceQuestion;
var topic = topics[tp];
var topicCid = topic.courseId;
var topicId = topic.topicId;
var topicname = topic.name;
var topicUpdateTime = topic.updateTime;
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i+2, 1).setValue(courseId);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i+2, 2).setValue(courseName);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i+2, 3).setValue(sid);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i+2, 4).setValue(fullname);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(i+2, 5).setValue(email);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(t+2, 6).setValue(tid);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(t+2, 7).setValue(tname);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(tp+2, 13).setValue(topicCid);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(tp+2, 14).setValue(topicId);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(tp+2, 15).setValue(topicname);
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(tp+2, 16).setValue(topicUpdateTime);
}
}
}

You don't include a reference to the S.O. questions where you say the pageTokens and Next Page Token examples didn't work for you - these constructs are what you need.
In fact I think you effectively need nested pageTokens, assuming you have more than 30 courses as well as more than 30 students on a course - you need to retrieve the courses a page at a time, and then retrieve the students a page at a time for each course. And likewise teachers and topics.
Alternatively you can gather all courses like this
static void getCourseList(ClassroomService service, ref List<Course> courses, string strCourseState = "ACTIVE")
{
string pageToken = null;
do
{
var request = service.Courses.List();
request.PageSize = 100;
request.PageToken = pageToken;
var response = request.Execute();
foreach (var course in response.Courses)
{
// wildcard option
if (strCourseState == "*" || course.CourseState == strCourseState) courses.Add(course);
}
pageToken = response.NextPageToken;
} while (pageToken != null);
}
and then write something similar for students, topics etc, which takes one course at a time as a parameter

Related

Google Script to return calendar guest names (only) into one cell separated by comma

I need help adjusting the script to return the calendar guest names only (not email) and put the names into 1 cell with each name separated by a comma.
I found a script that does this with the guests email, but I cannot figure out how to edit the script to return Names only. Here is the spreadsheet:
Daily Reminders
Any help would be appreciated.
Thank you for taking a look.
I have spent 3 days working on this. First I watched this video to learn to get the event, then had to read this previous, similar, but not really!, solution and have played with, and read this App Script Developer Site for 3 days until I figured out how to get the emails.
function getTomorrowEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Tomorrow");
var start_time = sheet.getRange("b2").getValue();
var end_time = sheet.getRange("d2").getValue();
var id_cal = sheet.getRange("B1:F1").getValue();
var cal = CalendarApp.getCalendarById(id_cal);
var events = cal.getEvents(new Date(start_time), new Date(end_time));
for (var i = 0;i<events.length;i++){
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
var loc = events[i].getLocation();
var des = events[i].getDescription();
var guests = events[i].getGuestList();
var guestEmails = "";
for (var j = 0; j < guests.length; j++) {
var guest = guests[j].getEmail();
guestEmails += guest+", ";
}
sheet.getRange(i+4,2).setValue(title);
sheet.getRange(i+4,3).setValue(start_time);
sheet.getRange(i+4,4).setValue(end_time);
sheet.getRange(i+4,5).setValue(loc);
sheet.getRange(i+4,6).setValue(des);
sheet.getRange(i+4,7).setValue(guestEmails);
}
Logger.log("Events have been added to the Spreadsheet");
}
I believe your goal is as follows.
About guestEmails in your showing script, you want to retrieve the user's name instead of the email address.
Issue and workaround:
When I saw getName() of Class EventGuest, it says the guest's name, or the guest's email address if the name is not available. Ref
When I saw attendees[].displayName of Event of Calendar API, it says The attendee's name, if available.. Ref
When I tested getName() in my calendar, no value is returned. Although, unfortunately, I'm not sure about your actual calendar, if you can retrieve the user's name, you can achieve your goal by the following modification.
From
var guest = guests[j].getEmail();
To
var guest = guests[j].getName();
If this modification was not the direct solution to your situation, it is required to convert the email address to the user's name. In this case, how about the following modification?
Modified script:
In this case, ContactsApp is used for converting the email address to the name.
From:
var guest = guests[j].getEmail();
To:
var guest = ContactsApp.getContact(guests[j].getEmail()).getFullName();
Or, I think that you can also use People API as follows. Before you use this script, please enable People API at Advanced Google services.
From
for (var i = 0;i<events.length;i++){
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
var loc = events[i].getLocation();
var des = events[i].getDescription();
var guests = events[i].getGuestList();
var guestEmails = "";
for (var j = 0; j < guests.length; j++) {
var guest = guests[j].getEmail();
guestEmails += guest+", ";
}
To
var res = People.People.Connections.list("people/me", { personFields: "emailAddresses,names", pageSize: 1000 });
var obj = res.connections.reduce((o, e) => (o[e.emailAddresses[0].value] = e.names ? e.names[0].displayName : e.emailAddresses[0].value, o), {});
for (var i = 0; i < events.length; i++) {
var title = events[i].getTitle();
var start_time = events[i].getStartTime();
var end_time = events[i].getEndTime();
var loc = events[i].getLocation();
var des = events[i].getDescription();
var guests = events[i].getGuestList();
var guestEmails = "";
for (var j = 0; j < guests.length; j++) {
var guest = obj[guests[j].getEmail()] || guests[j].getEmail();
guestEmails += guest + ", ";
}
References:
getContact(emailAddress)
Method: people.connections.list

Top level of JSON files, object? array?

I am using flutter/dart to fetch JSON files from Google Sheet. I use 2 different methods to get the same Google sheet, one is by scripting and the other is from 'sheetlabs' service. However, sheetlabs works and scripting fails. The top level from sheetlabs is an array while the top level from scripting is an object.
I just copy the scripting file from YouTube and I have no idea of google scripting. How can I modify the scripting code to make the top level being and array just like sheetlabs' file?
The structure of google sheet is relatively simple-- 10 columns with 'stockcode','stockname' ,etc as header which are freezed. Six stocks' data in rows.
Below is the scripting code.
function doGet(e){
var ss = SpreadsheetApp.openByUrl("MY ORIGINAL GOOGLE SHEET'S URL ADDRESS");
var sheet = ss.getSheetByName("sheet1");
return getUsers(sheet);
}
function getUsers(sheet){
var jo = {};
var dataArray = [];
var rows = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
for(var i = 0, l= rows.length; i<l ; i++){
var dataRow = rows[i];
var record = {};
record['stockname'] = dataRow[0];
record['stockcode'] = dataRow[1];
record['marketvalue'] = dataRow[2];
record['amount'] = dataRow[3];
record['currentprice'] = dataRow[4];
record['averagecost'] = dataRow[5];
record['profit'] = dataRow[6];
record['profitpercent'] = dataRow[7];
record['previousclosingprice'] = dataRow[8];
record['todaysprofit'] = dataRow[9];
dataArray.push(record);
}
jo.user = dataArray;
var result = JSON.stringify(jo);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);
}
You create json objects in the for loop.
You need to comment out var jo = {};
The following should work:
function doGet(e){
var ss = SpreadsheetApp.openByUrl("MY ORIGINAL GOOGLE SHEET'S URL ADDRESS");
var sheet = ss.getSheetByName("sheet1");
return getUsers(sheet);
}
function getUsers(sheet){
var dataArray = [];
var rows = sheet.getRange(2,1,sheet.getLastRow()-1, sheet.getLastColumn()).getValues();
for(var i = 0, l= rows.length; i<l ; i++){
var dataRow = rows[i];
var record = {};
record['stockname'] = dataRow[0];
record['stockcode'] = dataRow[1];
record['marketvalue'] = dataRow[2];
record['amount'] = dataRow[3];
record['currentprice'] = dataRow[4];
record['averagecost'] = dataRow[5];
record['profit'] = dataRow[6];
record['profitpercent'] = dataRow[7];
record['previousclosingprice'] = dataRow[8];
record['todaysprofit'] = dataRow[9];
dataArray.push(record);
}
var result = JSON.stringify(dataArray);
return ContentService.createTextOutput(result).setMimeType(ContentService.MimeType.JSON);

Load data from google sheet on start up

I tried to retrieve a list of agents who are stored in a google sheet. The problem that I am facing right now is that I can get the list of agents in the script file. However, when I try to pass it to an html file, I keep getting null for the list. I absolutely has no idea how that can be.
Can someone give me an idea where I should look for?
My script:
var DB_URL = "";
var AGENT_DB = "";
var CREATED_ON_IDX = 0;
var NAME_IDX = 1;
var EMAIL_IDX = 2;
function agentService_getAgents() {
var ss = SpreadsheetApp.openByUrl(DB_URL);
var sheet = ss.getSheetByName(AGENT_DB);
var dataRange = sheet.getDataRange();
var agents = [];
var values = dataRange.getValues();
for (var i = 1; i < values.length; ++i) {
var row = values[i];
var name = row[NAME_IDX];
var email = row[EMAIL_IDX];
var createdOn = row[CREATED_ON_IDX];
var agent = new Agent(name, email, createdOn);
agents[i-1] = agent;
}
Logger.log(agents);
return agents;
}
Ajax call in Html
<script type="text/javascript">
function onSuccess(agents) {
var $table = $("table");
console.log(agents);
}
google.script.run.withSuccessHandler(onSuccess)
.agentService_getAgents();
</script>
So Logger.log(agents) gives me a list of agent; but console.log(agents) gives me null.

Google Apps Script to list all assignments of all Classes in Google Classroom

I need to list all the assignments of all the classes in Google Classroom. One line is not working, but I don't know how to fix it. It produces the error message TypeError: Cannot read property "length" from undefined. later on.
function listAssignments2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('TAREAS');
var response = Classroom.Courses.list();
var courses = response.courses;
for (i = 0; i < courses.length; i++) {
var course = courses[i];
// This line below is not written right, which gives me an error further on.
var class = Classroom.Courses.CourseWork.list(course.id);
}
var w = class.courseWork;
var arr=[];
// The error comes out here stating "TypeError: Cannot read property "length" from undefined.".
for (i = 0; i < w.length; i++) {
var c = w[i];
var ids = c.id;
var user = c.creatorUserId;
var type = c.workType;
var ti = c.title;
var des = c.description;
var st = c.state;
var sch = c.scheduledTime;
var due = c.dueDate;
arr.push([ids,user,type,ti,des,st,sch,due]);
}
sh.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}
I was totally off on the order of what I was putting and on top of that I should have changed the two for loop variables.
function listAllAssignments() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('TAREAS');
var response = Classroom.Courses.list();
var courses = response.courses;
// First, the "arr" array had to be out of the for loop, this was the first error.
var arr =[];
for (i = 0; i < courses.length; i++) {
var course = courses[i];
var id = course.id;
var class = Classroom.Courses.CourseWork.list(id);
var w = class.courseWork;
/* The second and third error were here. First I had separated
the for loops, when I should have put the second for loop inside
the first, like I have here. Then, I should have changed the variable
of the second for loop (like I did here with the "k"). This seems to
have fixed the problems. */
for (k = 0; k < w.length; k++) {
var c = w[k];
var ids = c.id;
var user = c.creatorUserId;
var type = c.workType;
var ti = c.title;
var des = c.description;
var st = c.state;
var sch = c.scheduledTime;
var due = c.dueDate;
arr.push([ids,user,type,ti,des,st,sch,due]);
}
}
sh.getRange(1, 1, arr.length, arr[0].length).setValues(arr);
}
Partial answer.
It could be that Classroom.Courses.list() is returning an empty response. In order to prevent that your script throws an error replace, use something like the following
var response = Classroom.Courses.list();
var courses = response.courses;
if (courses && courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
Logger.log('%s (%s)', course.name, course.id); // Replace this with operations to be don on each iteration
}
} else {
Logger.log('No courses found.');
}
By the way, the script on the question has a for statement that on each iteration assigns a new value to class. It's very likely that you should include the following lines inside the for's code block:
var w = class.courseWork;
var arr=[];
// The error comes out here stating "TypeError: Cannot read property "length" from undefined.".
for (i = 0; i < w.length; i++) {
var c = w[i];
var ids = c.id;
var user = c.creatorUserId;
var type = c.workType;
var ti = c.title;
var des = c.description;
var st = c.state;
var sch = c.scheduledTime;
var due = c.dueDate;
arr.push([ids,user,type,ti,des,st,sch,due]);
}

Update Google FusionTables programmatically using data from spreadsheet

I am trying to update four out of five columns in FusionTables using data from Google Spreadsheet. I have just started programming Apps-scripts. I need help with update query. Any suggestions or feedback is appreciated. Thank you in advance.
function sync() {
var tasks = FusionTables.Task.list(TABLE_ID);
// Only run if there are no outstanding deletions or schema changes.
if (tasks.totalItems === 0) {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
//i = 1 for 1st row with values in spreadsheet. 0 for column headers.
for (var i = 1; i < data.length; i++) {
var cName = data[i][0];
var ed_vs = data[i][1];
var ed_vs_ada = data[i][2];
var color = data[i][3];
//update ft
var updateQry = "update "+TABLE_ID+" set ED_VS = "+ed_vs+",ED_VS_ADA = "+ed_vs_ada+", COLOR = "+color+ "where COUNTY = "+cName;
//FusionTables.Query.sql(updateQry);
//is this even possible to execute an update query? help with syntax?
Logger.log(updateQry);
}
}
};
Here's working solution for someone with similar issue.
function sync() {
var tasks = FusionTables.Task.list(TABLE_ID);
// Only run if there are no outstanding deletions or schema changes.
if (tasks.totalItems === 0) {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
//i = 1 for 1st row with values in spreadsheet. 0 will give column headers.
for (var i = 1; i < data.length; i++) {
var cName = data[i][0];
var ed_vs = data[i][1];
var ed_vs_ada = data[i][2];
var color = data[i][3];
//parse rowid from output
var selQry = "select ROWID FROM "+TABLE_ID+" where COUNTY = '"+cName+"' ";
var cdata = FusionTables.Query.sql(selQry);
var c_rowid = cdata.rows[0][0]; //rowid
Logger.log(c_rowid);
var updateQry = "update "+TABLE_ID+" set ED_VS = '"+ed_vs+"',ED_VS_ADA = '"+ed_vs_ada+"', COLOR = '"+color+ "' where ROWID = '"+c_rowid+"' ";
FusionTables.Query.sql(updateQry);
Logger.log(updateQry);
}
}
};