How to add people to google groups programmatically using google app script? - google-apps-script

var form = FormApp.openById('1IErsge8yafg0UOltvhecAMhRd5Yh1VXJdhkI');
var groupID = "mygroup#googlegroups.com";
var formResponses = form.getResponses();
for (var i = 0; i < formResponses.length; i++) {
var formResponse = formResponses[i];
var itemResponses = formResponse.getItemResponses();
var email = itemResponses[1].getResponse();
Logger.log(email);
var newMember = {email: email, role: "MEMBER"};
AdminDirectory.Members.insert(newMember, groupID);
}
}
This is the code I've written and I'm getting an error
After some research I found out that the error is because I don't have a G Suite subscription.
However, I am not able to find anything about how achieve the same task without a G Suite subscription. Can anyone please help me with that?
Thanks in advance!

As you aren't Google Workspace Admin, please checkout the Jay Lee's answer to Google Groups API add Member. Tl;Dr: AdminDirectory can be used only by Google Workspace Admins.
You might try to use the Groups Service to get information about a Google Group but it hasn't a method to add users to a group, so your only options are to add the users manually or to use web-browser automation tool.
Resources
https://developers.google.com/apps-script/advanced/admin-sdk-directory
Related
Add users to Google Groups using Google Apps Script
Google Admin SDK error Resource Not Found: domain when trying to list existing users
Issue adding members to #googlegroups.com with Google Apps Scripts

Related

Google App Script - How to monitor for new users

I wondered if anyone could point me in the right direction here?
I want to monitor the Google Workspace estate, and when a new user has been created send them an email. I’ve looked through the APIs but nothing is jumping out at me. But I know there are 3rd party tools out there that do this, so there’s got to be something I have missed?
I just created this script in Google Apps Script which gets and prints the list of all the users that were created today.
You can use this as a guide and keep testing with it. To accomplish this I used the Reports API to get the admin logs and get the list of all the users that were created today.
function myFunction() {
var userKey = 'all';
var applicationName = 'admin';
var optionalArgs = {
eventName:'CREATE_USER',
startTime: "2022-03-23T12:00:00.000Z",
fields : "items.events.parameters.value"
};
var rep = AdminReports.Activities.list(userKey,applicationName,optionalArgs);
const A = (JSON.parse(rep));
var totalUsers = Object.keys(A.items).length;
for(var i=0; i<totalUsers; i++)
{
var userEmail = A.items[i].events[0].parameters[0].value;
Logger.log(userEmail);
}
}
You would just need to change the startTime value according to the date you need to use and implement the part of sending the email now that you have all the email addresses.
References
API method: activities.list
Apps Script reference: Reports API

Is there any way to do a for each all Google Forms created by a Gmail account?

I am trying to get a list with all the google forms created by a specific google account (my own Gmail account BTW), in order to list them, get each ID and after that, be able to extract the responses spreadsheet associated to it and consolidate everything in a big home-made merge table.
I have tried using FormApp, but it appears to be only for just one form.
I have tried filtering all the existing files in DriveApp, but no luck at all.
You can use DriveApp.getFilesByType() to get all Google Forms in your drive using MimeType.GOOGLE_FORMS.
Once you get all the forms, you can check its owner's email address using File.getOwner() User.getEmail() before listing all your File Ids'.
After that, you can open each form using FormApp.openById() and use Form.getDestinationId() to get the response destination.
Sample Code:
var formList = DriveApp.getFilesByType(MimeType.GOOGLE_FORMS);
var myForms = [];
while (formList.hasNext()) {
var form = formList.next();
var ownerEmail = form.getOwner().getEmail();
Logger.log(form.getName());
Logger.log(ownerEmail);
if(ownerEmail == "myEmail#example.com"){
myForms.push(form.getId());
}
}
myForms.forEach(id=>{
var form = FormApp.openById(id);
var destinationId = form.getDestinationId();
var destinationType = form.getDestinationType();
Logger.log(destinationId);
Logger.log(destinationType);
})

Triggered Email not working since migrating to V8 Runtime

First let me state that all my coding is self taught so my knowledge is functional but not deep. I am creating a Google sheet for my HR team in my company to track Paid Time Off. I had built triggers to send emails when time was submitted. It worked before the migration to V8 but doesn't now, and I don't know enough about syntax to be able to find the issue.
function sendNotification(e){
if(e.range.getColumn()=13 && e.value='Yes')
{
//Employee Name and Email Address
var EmployeeName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("R3");
var Employee = EmployeeName.getValue();
var EmployeeEmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("S3");
var EmployeeEmailAddress = EmployeeEmailRange.getValues();
//Approver Name and Email Address
var ApproverName = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("R4");
var Approver = ApproverName.getValue();
var ApproverEmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("S4");
var ApproverEmailAddress = ApproverEmailRange.getValues();
//HR Email Address
var HREmailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("S5");
var HREmailAddress = HREmailRange.getValues();
//Link to Employee's PTO Spreadsheet
var SheetLink = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("PTO Earnings").getRange("R1");
var Link = SheetLink.getValue();
//Email Content
var subject = 'PTO Submitted for '+Employee+' for '+e.range.getSheet().getName()+'.';
var body = 'Dear '+Approver+','+"\n\n"+'A PTO Request has been submitted by: '+Employee+', at:'+"\n\n"+Link +"\n\n"+'Thank you.'+"\n\n"+'Imagine This HR';
var recipient = [EmployeeEmailAddress, ApproverEmailAddress,HREmailAddress];
MailApp.sendEmail(recipient, subject, body);
}
}
Please help!
Seems that un-migrating is optional, but Google is auto-migrating scripts to V8.
Part of the problem is that Google is automatically migrating scripts that pass their compatibility tests. And apparently some use of MailApp.sendEmail will pass the test but will in fact fail when the script is run.
https://developers.google.com/apps-script/guides/v8-runtime#automatic_migration_of_scripts_to_v8
This required me to revert/opt out in about 30 sheets that use MailApp just to ensure they don't fail - users really need scripts to work.
There is no mention of MailApp.sendEmail compatibility issues in any of the migration help docs.
The migration to V8 is optional. If you aren't ready or you don't have time to make your code compatible with it, just disable it. To do this, click Run > Disable new Apps Script runtime powered by Chrome V8.
It seems like a lot of triggers don't work with V8 Runtime migration.
I have a trigger on onOpen () and it doesn't work when the sheet is opened by a collaborator. However, it works well when it is opened by the owner. I haven't found a solution yet ...

Get owner/manager of all the Team Drive within the domain (Google Apps Script)

I am newbie G-Suite domain administrator and I'm trying to fetch all of the team drives within the domain along with its owner. I used google apps script and success to grab all of the team drive name and id. But when I try to reach one of the team drive by its id DriveApp.getFolderById(teamDrivesId), I'm getting the following error:
Team Drive Not Found : {teamdriveid}.
Its well understood that i am not a member of those team drive, but I'm an admin so how can I get these things done? Please kindly help.
Here is the code :
function getTeamDriveName() {
var teamDrivesName, teamDrivesId, pageToken;
var ssDrives = SpreadsheetApp.openById(sheetTeamDrives.id);
var sheetDrives = ssDrives.getSheetByName(sheetTeamDrives.sheet);
do {
var drivesList = Drive.Teamdrives.list({
pageSize : 100,
useDomainAdminAccess : true,
pageToken: pageToken
})
var items = drivesList.items;
for(var j = 0; j < items.length; j++) {
teamDrivesName = items[j].name;
teamDrivesId = items[j].id;
var getDrive = DriveApp.getFolderById(teamDrivesId);
sheetDrives.appendRow([teamDrivesId,teamDrivesName]);
}
pageToken = drivesList.nextPageToken;
}
while (drivesList.nextPageToken)
}
First of all Team Drives are not folders, so you need to call another function in order to get Team Drives information from the API.
Along with this, as you want to access to Team Drives as administrator, you need to use Teamdrives collection. So the function you need to call is Drive.Teamdrives.get(teamDrivesId, {useDomainAdminAccess : true}). There you will get information from those Teamdrives. *Source: https://developers.google.com/drive/api/v2/reference/teamdrives/get
Anyways, you say you want to know the owners and I would like to remark that there aren't owners on Team Drives, that's exactly what make them different from your Drive.
I hope it's clear and this could help you.

How to show contact photo using google apps script?

Hi I'm trying to show contact photo using google apps script,
this is what i have so far. so i connect successfully to contacts,
take first one, it's id, then i authenticate using OAuth, load
full contact profile, i even have a link to the photo, but it
won't show. I read somewhere that adding access token to link
would help but where to get this token from?
function doGet() {
var app = UiApp.createApplication();
var c = ContactsApp.getContacts();
c1 = c[0];
var options = OAuthApp.getAuth('contacts','http://www.google.com/m8/feeds');
var response = UrlFetchApp.fetch(c1.getId().replace(/base/,'full')+"?alt=json&v=3.0", options);
var object = Utilities.jsonParse(response.getContentText());
app.add(app.createImage(object.entry.link[0].href));
return app;
}
When i'm using UrlFetchApp.fetch (that includes options paramer that include authorisation) it loads the image data, but i don't know how to authorise app.createImage instead.
UiApp can't display private images. Star issue 912 http://code.google.com/p/google-apps-script-issues/issues/detail?id=912