Skip to content

Instantly share code, notes, and snippets.

@jmcmurry
Last active June 12, 2020 18:13
Show Gist options
  • Save jmcmurry/57d52f835375aaeb47e7f41be0d75a57 to your computer and use it in GitHub Desktop.
Save jmcmurry/57d52f835375aaeb47e7f41be0d75a57 to your computer and use it in GitHub Desktop.
From a list of google groups (the group addresses), fetch corresponding member emails for each and write them to a gSheet, each group occupies a separate column
// Note: API must be enabled before use.
// the person running the script needs to authorize the script AND from an email address that is listed as an administrator or owner on the group.
function main(){
// Destination sheet of members
var ss = SpreadsheetApp.openByUrl('SOMEURL');
//array of emails; here I fetch them from the a named range in the above spreadsheet, but they could be hardcoded as an array
var groupEmails = ss.getRangeByName("listOfGroups").getValues();
// Where you want to output the list member emails, each group name outputs at the column header, with each corresponding member below that.
// There is NO implied relationship between cells in adjacent columns.
var membersDestinationTabName = "feed";
// source and destination ss are the same
getData(ss,groupEmails,membersDestinationTabName);
}
function getData(ss,groupEmails,membersDestinationTabName) {
// TODO: wipe existing data from the sheet.
// TODO: add time trigger to do this 2x a day
Logger.log(groupEmails);
// this is a bit kuldgy but I am not certain how to iterate over column addresses in A1 Notation
var headerCols = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N"];
// WRITE HEADERS
for (i = 0; i < groupEmails.length && groupEmails[i]!=""; i++){
var range = ss.getRange(membersDestinationTabName+'!'+headerCols[i]+'1');
range.setValue(groupEmails[i]);
}
// WRITE MEMBERS FOR EACH GROUP
for (var i = 0; i < groupEmails.length && groupEmails[i]!= ""; i++) {
var GROUP_EMAIL = groupEmails[i];
var destinationAddress = membersDestinationTabName+'!'+headerCols[i]+'2';
var users;
var request;
try {
var group = GroupsApp.getGroupByEmail(GROUP_EMAIL);
users = group.getUsers();
Logger.log(GROUP_EMAIL);
} catch (err) {
// TODO: scope error more tightly
// When we can't fetch the users, it is generally a permissions issue; the output text to sheet could be changed if desired, but I don't want the program to crash for it
users = [""];
}
request = {
range: destinationAddress,
majorDimension: 'COLUMNS',
values: [users], //still 2D
};
//API must be enabled before use.
//https://developers.google.com/apps-script/advanced/sheets
Sheets.Spreadsheets.Values.update(request, ss.getId(), request.range, {
valueInputOption: 'USER_ENTERED',
});
// otherwise we get timeouts for too many calls in a time period
Utilities.sleep(3000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment