I know this is two-in-a-row, but they're different issues, so I thought it best to split them up. I'm getting problems with accepting invitations on behalf of students. I'm a super admin within the domain, and it works through the API explorer, but not through Google Apps Script's Advanced Service for Classroom. And before you ask, yes, I did enable Classroom in both the Advanced Services menu and Developer's Console.
Here's the block of code:
function invitations() {
var classList = Classroom.Courses.list().courses;
for (i in classList) {
var classId = classList[i].id;
var teacher = Classroom.Courses.Teachers.get(classId, classList[i].ownerId).profile.name.fullName;
if (teacher == 'FULL_NAME_GOES_HERE') { // I had entered my full name here as a string. If testing, you can replace with your own
var title = Classroom.Courses.get(classId).name;
Logger.log('Teacher: %s, Title: %ss',teacher,title);
var list = Classroom.Invitations.list({'courseId':classId}).invitations;
if (list) {
Logger.log('list');
for (k in list) {
var invitation = list[k];
var student = invitation.userId;
var id = invitation.id;
var response = Classroom.Invitations.accept({id:id});
Logger.log('ID: %s',id);
}
}
}
}
}
The id being passed to Classroom.Invitations.accept returns an error "Requested entity was not found." but when I input the same ID into the API explorer, it returns 200 - OK. Is this a problem with the Authorization scope? I have authorization to manage Classroom rosters, which I believe this falls under.
Related
I have trouble understanding the problem to recover the user photo from google.
First, the photo user is authorized for everyone. Normally it is saved in Account google(people), see screenshot, below.
In my test procedure, there is no account id in the account google (people).
so, I take another solution: user.list at admin google.
I found the photo url: user.thumbnailPhotoUrl.
it doesn't display because "private" is in that URL. yet in the google account, the photo is public.
so How to get the real url?
function doGet() {
var emailadresse = 'testbertrand#radiopresence.com';
var id_user = '117966962362496071521';
var parm_table = UserPhotoTest (id_user);
Logger.log('parm_table :'+parm_table );
}
function UserPhotoTest (user_id) {
var accountId =user_id;
Logger.log ('function userphoto - N°account id :'+accountId );
var val_photoUrl = "";
var val_namefile = "";
try
{ var person = People.People.get('people/' + accountId, {personFields: 'names,photos,phoneNumbers,addresses,birthdays,sipAddresses,organizations,genders'});
//** var val_displayName_P = person.names[0].displayName;
var val_photoUrl = person.photos[0].url.replace("=s100","=s128");
var val_namefile = get_namefile(val_photoUrl);
}
catch (err)
{
Logger.log ('function userphoto - Error : '+err);
var user = AdminDirectory.Users.get(emailadresse);
var val_photoUrl = user.thumbnailPhotoUrl
if (val_photoUrl.indexOf("private") > -1)
{
var testphotoadmin = AdminDirectory.Users.Photos.get(emailadresse);
// in document, I didn't understand it for AdminDirectory.Users.Photos.get(emailadresse);
// May you help me to developp here
// how to retreive a real url ?
// val_photoUrl = ...
}
}
var parm_photo = val_photoUrl;
return parm_photo;
}
What I have noticed is that photos uploaded from the Admin console as an Admin if you have a Google Workspace account they remain as private when retrieving the thumbnailPhotoUrl. This function should allow you to check whether the URL is private or not:
function retrievePhoto(){
var user = 'youremail#yourdomain.com';
var photo = AdminDirectory.Users.get(user,{fields:'thumbnailPhotoUrl'});
console.log(photo);
}
Using the above code should retrieve your thumbnailPhotoUrl when using the Admin SDK in App Script. If the profile picture was updated from the Admin console most likely the URL will show as private. If the thumbnailUrl still shows as private try allowing this setting in the Workspace console and update the profile picture in aboutme.google.com as this should set the picture as public.
I was getting a list of contacts using the Contact method in Google App Script. As of June 16th, the Contact method is not longer available. I am trying to use the People method but cannot figure out how to get a specific list of email addresses categorized by the label. Please help and TYIA
Original Google App Script:
var emailList = [];
var contacts = ContactsApp.getContactGroup('Membership Committee').getContacts();
for(var i in contacts){
emailList.push(contacts[i].getEmailAddresses());
}
As answered by Rafa Guillermo:
Use contactGroups.get to get the group member resource names.
Use people.getBatchGet to make a batch request to the API and use member resource names and personFields: 'emailAddresses' as parameters.
Example:
function myFunction() {
var groupId = "Insert Group/Label ID here"
var contactGroup = People.ContactGroups.get('contactGroups/'+groupId, {"maxMembers" : 50});
var memberResourceNames = contactGroup.memberResourceNames;
var test = People.People.getBatchGet({
resourceNames: memberResourceNames,
personFields: 'emailAddresses'
})
test.responses.forEach(res => {
Logger.log(res.person.emailAddresses[0].value);
})
}
Note: Label ID can be found by clicking a Label and in the URL, any characters after https://contacts.google.com/label/ is the ID.
Output:
References:
Method: contactGroups.get
Method: people.getBatchGet
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:
I am looking for a method to find the unread message count of delegated mailboxes from any of the Google API's.
I am not sure IF it is possible, but it would help me develop a helping tool for a company using this for 1000+ users. A lot of delegation is going on, and I am eager to find a way to accomplish this.
But I might need some help, maybe from people closer with knowledge of the possibilities of the Admin SDK from Google.
I want to use Google Apps Script to collect the unread message count.
The Email Settings API allows you to see which delegations are in place.
It is not possible for a user to access the mailbox of another user who has delegated them access via IMAP, thus you can't authenticate as a user and check the delegated mailbox.
You should use OAuth 2.0 Service Accounts to authenticate to the mailboxes via IMAP.
Once authenticated you can select the Gmail "All Mail" folder (or Inbox if you only want count for Inbox). and do a Gmail search of "is:unread" to determine how many unread messages the user has.
FYI, my open-source app, GYB can do just this. There is a getting started guide for GYB. You'll also need to setup the service account. The command to get unread message count for all mail would be something like:
gyb --email delegated-mailbox#yourcompany.com --service-account your-service#account.com --action count --search "is:unread"
I got my answer from the GAS community on Google Plus, so credits to the posters there.
https://plus.google.com/106333172328928589411/posts/7g3Vu7iFZfb
Sergii:
Check out this gist that shows how to do 2-legged OAuth authentication in GAS https://gist.github.com/rcknr/c5be4eb80d821158c8ef.
Using 2 Legged Oauth you can get access to the ATOM feed of other users:
A piece of working code for it:
function gmail2lo(user) {
var OAUTH_CONSUMER_SECRET = 'secret';
var domain = 'domain'; //use the domain as key in apps panel
var username = 'user';
var xuser = username+'#'+domain;
var method = "GET";
var baseUrl = "https://mail.google.com/mail/feed/atom";
var timestamp = Math.round(new Date().getTime() / 1000);
var paramsJson;
var paramsOauth = {
oauth_consumer_key : domain,
oauth_nonce : timestamp,
oauth_signature_method : "HMAC-SHA1",
oauth_timestamp : timestamp,
oauth_version : "1.0",
'xoauth_requestor_id' : xuser
};
var paramsStringArray = [];
for (var k in paramsJson)
paramsStringArray.push(k + '=' + encodeURIComponent(paramsJson[k]));
var oauthStringArray = [];
for (var k in paramsOauth)
oauthStringArray.push(k + '=' + encodeURIComponent(paramsOauth[k]));
var paramsString = paramsStringArray.concat(oauthStringArray).sort().join('&');
var signatureBaseString = method +"&"+ encodeURIComponent(baseUrl) +"&"+ encodeURIComponent(paramsString);
var signatureBytes = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_1, signatureBaseString, OAUTH_CONSUMER_SECRET+'&');
var signature = encodeURIComponent(Utilities.base64Encode(signatureBytes));
var xoauthString = 'OAuth ' + oauthStringArray.sort().slice(0,oauthStringArray.length-1).join(", ") + ', oauth_signature=' + signature;
var ooptions = {
headers : {authorization: xoauthString}
}
url = baseUrl;
url += "?" + paramsStringArray.join("&") + '&xoauth_requestor_id=' + encodeURIComponent(xuser);
var response = UrlFetchApp.fetch(url, ooptions).getContentText();
}
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());
}
}
}
}
}