Google App Script - How to monitor for new users - google-apps-script

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

Related

How to add people to google groups programmatically using google app 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

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 ...

How to resolve "Too much calls for this service today : gmail" error in Google Apps script?

My question is about an error in Google's spreadsheet using gmail service in a function.
Since a while, an error occur when I run a function (On Google Spreadsheet) for retrieve mails on a label founded in the MailBox (Gmail).
The error message is : "Too much calls for this service today : gmail".
I want to specify that function worked fine before and it hasn't been modified.
The function is launched one time per month (Except in exceptional case)
I did some research on the error message, and the answers found confirmed what I thought,
daily quotas for Google's gmail services are exceed and can not be used until 24 hours.
However, it's the only one that has not worked, while others are working properly with these services without any errors.
Following this, I created a copy of the spreadsheet with the function to test if it isn't the sheet that does not work, but it has not changed.
And I launched it with another Google account, and it worked.
Does anyone know why this message appears please ?
Should we do a special manipulation to make it work again ?
Here is the row that sends an error :
var threads = GmailApp.getUserLabelByName("Label").getThreads();
And the function :
function readMail(){
var threads = GmailApp.getUserLabelByName("Label").getThreads();
var messages = GmailApp.getMessagesForThreads(threads);
for(var i in messages){
var message = messages[i];
for(var j in message){
var mess = message[j];
var sub = mess.getSubject();
if(mess.getTo().indexOf("email#gmail.com") > -1)
continue;
var attach = mess.getAttachments()[0];
var file = {
title: attach.getName()
};
var fileDoc = Drive.Files.insert(file, attach, {convert: false}); // Use Drive API
mess.markRead();
}
}
}

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