I create a script to get all the users in one SpreadSheet, Name and Email, but I'm not able to get the users that are created under the secondary domain.
This is my code:
function writeToSpreadsheet(){
var values = [],
users = [],
userListQuery = {},
nextPageToken = '',
listObject = {
domain:'the domain name',
maxResults: 500,
},
i = 0,
activeSpreadsheet;
do {
if (nextPageToken && nextPageToken !== '') {
listObject.pageToken = nextPageToken;
}
userListQuery = AdminDirectory.Users.list(listObject);
// if there are more users than fit in the query a nextPageToken is returned
nextPageToken = userListQuery.nextPageToken;
// Add the query results to the users array
users = users.concat(userListQuery.users);
} while (nextPageToken);
for (i = 0; i < users.length; i += 1) {
values.push([users[i].name.fullName, users[i].primaryEmail]);
}
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange(2, 1, values.length, values[0].length).setValues(values);
}
Use the Google Admin Settings API, it allows administrators of Google Apps domains to retrieve and change settings of their domains in the form of Google Data API feeds.
To retrieve from secondary domain, you may send HTTP GET to the account information administrator secondary email address feed URL and include an Authorization header as described in Authenticating to the Admin Settings service
A successful response returns an HTTP 200 OK, along with the administrator's secondary email address.
Sample HTTP GET request:
https://apps-apis.google.com/a/feeds/domain/2.0/{domainName}/accountInformation/adminSecondaryEmai
Related
Hey I am trying to get the YouTube Analytics for a Brand Account. I am using Google Apps Script but now I have the problem that i always get the information for the Google Account not the Brand Account. At the Moment I am using this code.
function retrieveMyUploads() {
var results = YouTube.Channels.list('contentDetails', {mine: true});
for(var i in results.items) {
var item = results.items[i];
// Get the playlist ID, which is nested in contentDetails, as described in the
// Channel resource: https://developers.google.com/youtube/v3/docs/channels
var playlistId = item.contentDetails.relatedPlaylists.uploads;
var nextPageToken = '';
// This loop retrieves a set of playlist items and checks the nextPageToken in the
// response to determine whether the list contains additional items. It repeats that process
// until it has retrieved all of the items in the list.
while (nextPageToken != null) {
var playlistResponse = YouTube.PlaylistItems.list('snippet', {
playlistId: playlistId,
maxResults: 25,
pageToken: nextPageToken
});
for (var j = 0; j < playlistResponse.items.length; j++) {
var playlistItem = playlistResponse.items[j];
Logger.log('[%s] Title: %s',
playlistItem.snippet.resourceId.videoId,
playlistItem.snippet.title);
}
nextPageToken = playlistResponse.nextPageToken;
}
}
}
It would be great if someone could help me getting the information of the Brand Account and not the Google Account.
I don't know how YouTube recommends to get the authorization token but here is how I took it for a brand account:
Log in to the associated Google account on https://developers.google.com/youtube/v3/docs/channels/list then on the right pane, fill snippet for part and true to mine, open the network tab of your web browser (Ctrl + Shift + E), click execute at the bottom of the right pane then select the account you are connected with and then the brand account and get from the XHR request from the network tab the AUTHORIZATION_TOKEN that is given for the authorization header.
Then you can run this shell command to make sure you got the right AUTHORIZATION_TOKEN to meet your needs.
curl 'https://youtube.googleapis.com/youtube/v3/channels?part=snippet&mine=true' --header 'Authorization: Bearer AUTHORIZATION_TOKEN'
In the response you should see the name of your brand account so you can then modify the endpoint to meets your needs.
I need to find USER_ID of all the users in our current organization. We have Google Workspace - Basic plan and have 120+ users.
Please refer here for what USER_ID I'm talking about
https://developers.google.com/hangouts/chat/reference/message-formats/basic#messages_that_mention_specific_users
What is the easiest way to fetch the USER_ID? The solution can be something like where Google Sheet is updated with the new user and its USER_ID.
Answer
It is not possible to get this USER_ID of all the users in a specific domain. This is what the documentation says about this id:
To determine the USER_ID for a user, examine the sender field of the incoming message from the user.
Also, if you were to use the space.members.list method to get a membership (or a user) resource, they do not contain any id.
Work around
There is a sample code in the documentation that shows how to get all the users in a Google Workspace domain. I have modified it to get the user ids and finally create a Sheet with all the information.
Code
function listAllUsers() {
var pageToken;
var page;
var userList = []
do {
page = AdminDirectory.Users.list({
domain: 'example.com',
maxResults: 100,
pageToken: pageToken
});
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
userList.push([user.id, user.name.fullName, user.primaryEmail])
Logger.log('u:%s, %s (%s)', user.id, user.name.fullName, user.primaryEmail);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
var nusers = userList.length
var ss = SpreadsheetApp.create('usersList')
ss.getActiveSheet().getRange(1,1,nusers,3).setValues(userList)
console.log(ss.getUrl())
}
References
Admin SDK Directory Service: List all users
Chat API: Method spaces.members.list
Chat API: Resource Membership
Chat API: Resource User
I have users in our Gsuite domain who use several email aliases. I need to setup different email signatures depending on the sender email alias. Is there a way to do this without having to pay for external software?
Thanks folks!
Since you have tagged apps script you can create a script where you can use G Suite Admin SDK and Gmail API to retrieve all the users and then set up a signature for each alias of the user.
This is an example on Apps Script for users: list:
/**
* Lists users in a G Suite domain.
*/
function listUsers() {
var optionalArgs = {
customer: 'my_customer',
maxResults: 10,
orderBy: 'email'
};
var response = AdminDirectory.Users.list(optionalArgs);
var users = response.users;
if (users && users.length > 0) {
Logger.log('Users:');
for (i = 0; i < users.length; i++) {
var user = users[i];
Logger.log('%s (%s)', user.primaryEmail, user.name.fullName);
}
} else {
Logger.log('No users found.');
}
}
Using Users: list (from Admin SDK) you will get all the users on your domain, and from that you can use path or update (from Users.settings.sendAs) to create a signature.
Is there a method in google apps script to get the files of a suspended owner based on his/her email id? I am literally trying to implement transfer drive files to a new owner using google apps script, I am using this code to find the details of all the suspended users:
/**
* Fetches the suspended user details from the AdminDirectory.
*/
function fetchUser() {
// Set the constant options only once.
const options = {
domain: 'xyz.com',
orderBy: 'email',
query: 'isSuspended=true',
maxResults: 500,
fields: "nextPageToken,users"
};
// Could log the options here to ensure they are valid and in the right format.
const results = [];
do {
var search = AdminDirectory.Users.list(options);
// Update the page token in case we have more than 1 page of results.
options.pageToken = search.nextPageToken;
// Append this page of results to our collected results.
if(search.users && search.users.length)
Array.prototype.push.apply(results, search.users);
} while (options.pageToken);
//Logger.log(results);
for(var k = 0; k < results.length; k++){
var fullEmail = results[k].primaryEmail;
Logger.log(fullEmail);
fetchFiles(fullEmail);
}
}
/**
* Fetches the files of the suspended users based on their email.
*/
function fetchFiles(email){
var pageToken;
var filesList = Drive.Files.list({ // Invalid value error is thrown here, I am not sure if this the right way to use Drive API in google script
domain: 'xyz.com',
orderBy: 'email',
q: "'email' in owners",
maxResults: 500,
pageToken: pageToken
});
Logger.log('filesList:' +filesList);
}
I am trying to implement something like Transfer ownership of a file to another user in Google Apps Script, but is there some way by which I can fetch the files of the user from the details obtained from the above code which basically returns the following output:
[
{
orgUnitPath = /,
ipWhitelisted = false,
gender = {type = other},
creationTime = 2017-06-13T14:38:44.000Z,
isMailboxSetup = true,
isEnrolledIn2Sv = false,
kind = admin#directory#user,
suspensionReason = ADMIN,
isAdmin = false,
suspended = true,
emails = [{
address = john.seb#xyz.com,
primary = true
}],
lastLoginTime = 2017-09-12T00:27:00.000Z,
isDelegatedAdmin = false,
isEnforcedIn2Sv = false,
changePasswordAtNextLogin = false,
customerId = v12idsa,
name = {
givenName = John,
familyName = Seb,
fullName = John Seb
},
etag = "npJcgeAc7Xbfksfwer22344/sfasdfaffUDsfdsjfhsfhsdfw-ec",
id = 1033392392142423424,
primaryEmail = john.seb#xyz.com,
agreedToTerms = true,
includeInGlobalAddressList = true
},
...
]
I am trying to use the Drive API in the google apps script in order to access the files of suspended users using their email, but its throwing
"Invalid Value" error
for the line Drive.Files.list, I am not sure if this is the right way to use the DRIVE API in google script, is there any other way to use this api in google script?
In your function fetchFiles, you never use the input argument email. Instead, you query the Drive REST API for the literal text 'email' in owners. Since the text string 'email' is not a valid email address, you correctly receive the error message "Invalid value".
Rather than this code:
/**
* Fetches the files of the suspended users based on their email.
*/
function fetchFiles(email){
var pageToken;
var filesList = Drive.Files.list({
domain: 'jerseystem.org',
orderBy: 'email',
q: "'email' in owners",
maxResults: 500,
pageToken: pageToken
});
Logger.log('filesList:' +filesList);
}
You should perform the substitution first, to set up all constant options (as I mentioned and demonstrated in your other question), and then repeatedly query the Drive API for the files owned by the user with that email address:
function fetchAllFilesOwnedByEmail(email) {
const searchParams = {
corpora: 'some corpora',
orderBy: 'some ordering criteria',
q: "'" + email + "' in owners",
fields: 'nextPageToken,items(id,title,mimeType,userPermission)'
};
const results = [];
do {
var search = Drive.Files.list(searchParams);
if (search.items)
Array.prototype.push.apply(results, search.items);
searchParams.pageToken = search.nextPageToken;
} while (searchParams.pageToken);
return results;
}
You need to review the Drive REST API documentation, see Drive.Files.list and Search for Files at minimum. Don't forget to enable the Drive advanced service if you haven't.
Also note that while the above code will resolve the "Invalid Value" error you get, it won't necessarily make the user's files show up, even if you're executing the code as the G-Suite admin. Your research should have turned up at least these two related questions:
How can an Admin access the Google Drive contents of all the users in a particular domain?
Most efficient process for transferring ownership of all of a user's files using the Google Drive API
Is it possible to get all domain email addresses (#example.com) to a variable? (the domain is of course connected with Gmail). I was searching and have found just ContactsApp class, which can give contacts from address books, but I need all company's email addresses.
To get user information like this for your entire domain, you need to use the Admin SDK Directory API. You will need to query Google Apps for your domain's users.
var optionalArgs = {"customer":"my_customer"},
response,
users = []
;
response = AdminDirectory.Users.list(optionalArgs);
users = response.users;
This will get you your first page of users, so you may need to create a loop to fetch all of them. You will need to understand the User resource, which is returned for each of your users. Both their primary domain email and their aliases can be found in this resource:
var email,
aliases
;
email = users[0].emails[0]; // if email.primary is true, email.address is the primary domain email for this user
aliases = users[0].aliases; // list of user's alias email addresses
More information can be found in the documentation
This is the function to get all the users email address list in appscript .
function listAllUsers1() {
var pageToken;
var page;
do {
page = AdminDirectory.Users.list({
domain: 'abc.com',
orderBy: 'givenName',
maxResults: 100,
pageToken: pageToken,
});
var users = page.users;
Logger.log(users);
if (users) {
for (var i = 0; i < users.length; i++) {
var user = users[i];
Logger.log(user);
Logger.log('%s (%s)', user.name.fullName, user.primaryEmail);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}