How to enable Google Classroom courseWorkList - google-apps-script

I've been testing the Google Classroom Api and can't seem to get the courseWorkList method to run getting a caller error
I've basically cut and pasted code from the reference and it works if i remove the classCourseWork line. Otherwise I get a "The caller does not have permission" error. I've enabled the API services, approved it to run, etc. Any help in getting this one sorted?
function listCourses() {
var optionalArgs = {
pageSize: 10
};
var response = Classroom.Courses.list(optionalArgs);
var courses = response.courses;
if (courses && courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
var classCourseWork = Classroom.Courses.CourseWork.list(course.id);
}
Logger.log('%s (%s)', course.name, course.id);
} else {
Logger.log('No courses found.');
}
}

I've tried your code, here are the scenarios:
As a student:
Your code is working fine.
As a teacher:
I've also received "The caller does not have permission" error.
You might want to check this open issue tracker, that a teacher cannot access the coursework (or the students' turned-in assignments) in their course, getting the same permission error. It was updated and was filed a ticket internally, we can follow this ticket to be updated.
Hope this helps.

Does this thread sound like the same issue? Http://stackoverflow.com/questions/42796630/google-classroom-apps-script-coursework-list-permission-error

Related

How to pull deleted, archived, suspended users data to Google sheets from Admin SDK >> Reports API using Appscript

How to import deleted, archived, suspended USERS data (user email, deleted date, org unit path, archive date, suspended date) to Google sheets from Admin SDK >> Reports API using Appscript. Thanks.
Welcome to Stackoverflow. Please be mindful to always include any research/sample scripts you've done on your end when posting questions as much as possible. Please see the guidelines about How do I ask a good question? as this is an integral part in this community.
RECOMMENDATION:
You can use this sample script below as reference. This script is based to a sample from Google Apps Script Quickstart
function listUsers() {
var sheet = SpreadsheetApp.getActive().getActiveSheet();
var values = [];
var userKey = 'all';
var applicationName = 'admin';
var optionalArgs = {
maxResults: 100
};
var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs);
var activities = response.items;
if (activities && activities.length > 0) {
Logger.log('REPORTS:');
for (i = 0; i < activities.length; i++) {
var activity = activities[i];
//ONLY GET DATA IF ACTION IS EITHER "SUSPEND_USER", "DELETE_USER", or "ARCHIVE_USER"
if(activity.events[0].name == "SUSPEND_USER" || activity.events[0].name == "DELETE_USER" || activity.events[0].name == "ARCHIVE_USER"){
Logger.log('%s: %s (%s)', activity.id.time, activity.events[0].parameters[0].value,
activity.events[0].name);
//RETRIEVES THE TIMESTAMP, USER'S EMAIL, & THE EVENT NAME THAT WAS PERFORMED TO THE USER
values = [[activity.id.time, activity.events[0].parameters[0].value,activity.events[0].name]];
//SET THE DATA TO SHEET
var lrow = sheet.getLastRow()+1;
sheet.getRange("A"+lrow+":C"+lrow).setValues(values);
}
}
} else {
Logger.log('No reports found.');
}
}
NOTE:
Before you run the script, you need to add the AdminReports API on your Apps Script editor:
1. Click Services plus icon
2. Choose Admin SDK API
3. Click version drop-down, select reports_v1 and Add
SAMPLE SHEET
RESULT
After running the sample script, the timestamp when the action was made, user email address and the action made (Suspended/Deleted/Archived) will be added to the sheet:
Here's the Execution logs result for reference:

Having trouble listing AdminDirectory groups in Apps Script

I am trying to get groups in Google Apps Script. My code is as follows:
var list = AdminDirectory.Groups.list({
customer: 'my_customer'
});
I tried the above, and I tried replacing the customer arg with domain: MYDOMAIN (and I tried with a userKey) but I always get the same error:
Executing query for datasource SearchResults: (Error) : We're sorry, a server error occurred. Please wait a bit and try again. [18a249eb]
Is this not the right way to get the groups? (Incidentally, I would ideally like to search for groups rather than listing them all, but I don't see that as an option.)
Thanks for any tips or pointers.
According to the Using the debugger and breakpoints, this error can be one of the following:
Server error occurred, please try again.
There are a couple possible causes for this error:
A Google server or system is temporarily unavailable. Wait for a few moments and try running the script again.
There is an error in your script that doesn't have a corresponding error message. Try debugging your script and see if you can isolate
the problem.
There is a bug in Google Apps Script that is causing this error. Report the error on the issue tracker.
Make sure you're following the List all groups guide correctly:
function listAllGroups() {
var pageToken, page;
do {
page = AdminDirectory.Groups.list({
domain: 'example.com',
maxResults: 100,
pageToken: pageToken
});
var groups = page.groups;
if (groups) {
for (var i = 0; i < groups.length; i++) {
var group = groups[i];
Logger.log('%s (%s)', group.name, group.email);
}
} else {
Logger.log('No groups found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}

google domain shared contacts appscript, using oauth2 lib and SharedContactsApp lib error on listAllContacts

I am using oauth2.0 library
(Google open source OAuth2 library MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48)
I am also using SharedContactsApp library
(open source library MLbRKmnCytdiSBOmoaGe1DOVJ5jnXUK_T)
I am able to add a shared contact also add phone numbers.
I am also able to use
SharedContactsApp.getContacts();
but when I do, I notice that I am only getting 25 contacts that I added no contacts that are also in domain and showing in the Directory option in contacts.
I have created more than 25 but when I use getContacts(), I only get 25.
So I decided to use getContactsForPaging.
But I am getting an error when using SharedContactsApp.getContactsForPaging(Token);.
This is how I have it set up:
function listAllContacts() {
var sharedContactsService = getSharedContactsService();
var Token = sharedContactsService.getAccessToken();
SharedContactsApp.setOAuth2AccessToken(Token);
do {
var result = SharedContactsApp.getContactsForPaging(Token);
contacts = result.getContacts();
Token = result.getToken();
for (var i = 0; i < contacts.length; i++) {
Logger.log(contacts[i].getFullName());
}
} while (Token != null);
}
Am I doing something wrong?
This is my error:
Exception: Request failed for https://www.google.com/m8/feeds/contacts/dev.whitestratus.com/full/ returned code 401.
Truncated server response: <html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Error 401 (Client Error)!!1</title> <style type="text/css"> ... (use muteHttpExceptions option to examine full response)
(line 239, file "Code", project "SharedContactsApp")
HTTP 401 errors will be authentication related. My guess is that you don't have valid OAuth access. To confirm,
function tinyTest() {
Logger.log('hasAccess() is: %s', getSharedContactsService().hasAccess());
}
should result in 'hasAccess() is: true'. If it's false, you need to do two things:
Follow the How To use OAuth 2 with SharedContactsApp. This will walk you through getting an access token which is a manual exercise, really complex and error prone. Carefully follow and check each step again and don't assume anything or try to take short cuts.
Use the test() function on that page (step 6 there) to confirm your setup before going any further or using your own code. If test() doesn't work your code won't either.
If your test() fails, I suggest that you report here with details from steps 2,3,4,5 (but hide your "client secret").
Edited to add:
If your test passes, then all seems OK with your OAuth. Run the code below to page through all your contacts and log on the way. Perhaps you have some contact/s with bad data. Look at the log and you'll see the id of the first contact that fails. Delete that contact and try again until you have no errors.
function listAllContacts() {
SharedContactsApp.setOAuth2AccessToken(getSharedContactsService().getAccessToken());
var contacts = null;
var token = null;
do {
var result = SharedContactsApp.getContactsForPaging(token);
contacts = result.getContacts();
token = result.getToken();
for (var i = 0; i < contacts.length; i++) {
Logger.log(contacts[i].getId());
Logger.log(contacts[i].getGivenName());
Logger.log(contacts[i].getFamilyName());
Logger.log(contacts[i].getFullName());
}
} while (token != null);
}
You are using Token for two different things. There are two tokens the OAuth2 token and the paging token. This should fix it.
function listAllContacts() {
var sharedContactsService = getSharedContactsService();
var oaToken = sharedContactsService.getAccessToken();
SharedContactsApp.setOAuth2AccessToken(oaToken);
var Token = null;
var contacts = null;
do {
var result = SharedContactsApp.getContactsForPaging(Token);
contacts = result.getContacts();
Token = result.getToken();
for (var i = 0; i < contacts.length; i++) {
Logger.log(contacts[i].getFullName());
}
} while (Token != null);
}

Google Script not Finishing Successfully

I recently adapted a short piece of script to automatically send an e-mail to me when a specific response appears (the word FAIL) in a 'Google docs' spreadsheet, that collects responses from volunteers using a 'Google Form' to record their weekly checks on life-saving equipment.
The email on FAIL is working well, having tested it with a few FAIL responses. However, as the form 'owner' I am receiving notifications from Google, for each normal PASS response submitted, telling me that the script failed to finish successfully.
8/4/15 10:57 AM
SendGoogleForm
ReferenceError: "found" is not defined. (line 35, file "Code")
formSubmit
It finishes successfully if a FAIL response is submitted, so I suspect that, due to my inexperience with scripts, I have not defined what should happen when found is 'not true'.
It's probably glaringly obvious to a more experienced script writer but none of the things I have tried with 'Else' seem to work.
Any suggestions would be greatly appreciated.
function Initialize() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers)
ScriptApp.deleteTrigger(triggers[i]);
ScriptApp.newTrigger("SendGoogleForm")
.forSpreadsheet(SpreadsheetApp.getActiveSpreadsheet())
.onFormSubmit().create();
}
function SendGoogleForm(e) {
if (MailApp.getRemainingDailyQuota() < 1) return;
// Recipients email address
var email = "12345#abcde.co.uk";
// Subject for Google Form email notification
var subject = "Weekly Checks - FAIL Submitted";
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0];
var message = "A check form has been submitted containing a ** FAIL ** response: ";
// Look for a 'FAIL' response
var key = columns[keys];
for ( var keys in columns ) {
if ( e.namedValues[columns[keys]] == 'FAIL') {
found = true;
}
}
// Only include form fields that are not blank
if (found)
for (var keys in columns) {
var key = columns[keys];
if (e.namedValues[key] && (e.namedValues[key] !== "")) {
message += key + ' : ' + e.namedValues[key] + "\n\n";
}
}
MailApp.sendEmail(email, subject, message);
}
Your found variable is null whenever a non-"FAIL" occurs in your script and I think your if(found) is creating the error message.
You could Initialise your variable:
var found = false;
before you start testing it. That way, your if(found) will be false and it will skip down to your send email code.
Perhaps u can use
if ( e.namedValues["Pass or Fail"] == "Fail" ) { ... }
where "Pass or Fail" is the form question title. And also use e.range.getRow() to capture the sheet row that the responses were written.

Event guest list with user groups getting status by guest

I am trying to pull the list of guests for a calendar event and figure out each of the guests status (YES, NO, MAYBE) but ran into a problem with a user group. It just gives me the group name and a status of INVITED, but I need each guest in the user group and their invite status. Is this possible?
var calendarName="calendar name";
var calDate=new Date("04/02/2013");
function testCalendarEvents(){
var calendars = CalendarApp.getCalendarsByName(calendarName);
var events = calendars[0].getEventsForDay(calDate);
for(var c=0; c<events.length; c++){
Logger.log("Event "+c+": "+events[c].getTitle());
var guestList=events[c].getGuestList();
for(var d=0; guestList!=null && d<guestList.length; d++){
Logger.log("Guest "+d+": "+guestList[d].getEmail()+", Status: "+guestList[d].getGuestStatus());
}
}
}
This is not possible for DomainGroups presently, as there is no apps-script API support for drilling in to the status of group members. According to the documentation, you should be able to view those users and their status through the Calendar UI, assuming that you have appropriate permissions to view group members.
From the Enterprise Calendar FAQ:
Can I invite a mailing list from our corporate directory to a meeting?
Yes, you can invite any mailing list (group) in our corporate
directory to a meeting. Each member of the group will receive an email
invitation. Note, however, that the email invitation won't show all
the members of the group. Also, the group members will appear in the
invitation on each attendee's calendar only if you have permission to
view the group's member list.
If you are a Domain Administrator, you can use the GroupsManager service to retrieve the memberslist of a group. Unfortunately, within the context of a Calendar Event, that's about the only useful thing you can do. You cannot get the invitation status of individual users. I've modified your script to retrieve the member list:
function testCalendarEvents(){
var calendarName="david_bingham#mitel.com";
var calDate=new Date("04/01/2013");
var calendars = CalendarApp.getCalendarsByName(calendarName);
var events = calendars[0].getEventsForDay(calDate);
try {
var domainAdmin = false; // assume we aren't an admin in a domain
GroupsManager.getGroup("test");
domainAdmin = true; // we passed the test, so we ARE
}
catch (error) {
// We didn't pass the test... why not?
// Get "Service error: : Invalid request URI" if outside of an enterprise account
// Get "You do not have permission to perform that action." if not admin.
Logger.log("Not Domain Admin: "+error.message);
}
for(var c=0; c<events.length; c++){
Logger.log("Event "+c+": "+events[c].getTitle());
var guestList=events[c].getGuestList();
for(var d=0; guestList!=null && d<guestList.length; d++){
if (!domainAdmin) {
Logger.log("Guest "+d+": "+guestList[d].getEmail()+", Status: "+guestList[d].getGuestStatus());
}
else {
// Check if this guest is a group
var group = GroupsManager.getGroup(guestList[d].getEmail());
if (group) {
// getAllMembers() returns an array of email addresses
var groupMembers = group.getAllMembers();
for (var e in groupMembers) {
Logger.log("Guest "+d+"/"+e+": "+groupMembers[e]+
", Status: "+"UNKNOWN(group "+guestList[d].getEmail()+")");
}
}
else {
Logger.log("Guest "+d+": "+guestList[d].getEmail()+", Status: "+guestList[d].getGuestStatus());
}
}
}
}
}