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
Related
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
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);
})
I am trying to create a small application in in Google Sheets to sorten URLs on my personal google account. I am using the following code which I found here: Google Sheets Function to get a shortened URL (from Bit.ly or goo.gl etc.)
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("Shorten")
.addItem("Go !!","rangeShort")
.addToUi()
}
function rangeShort() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
//var url = UrlShortener.Url.insert({longUrl: data[i][0]});
var url = UrlShortener.Url.insert({longUrl: 'www.google.com'});
output.push([url.id]);
}
range.offset(0,1).setValues(output);
}
I created a new Google Cloud Project and enabled the URL shortener API in the project and on the Google sheet. The problem is that when I try and run the code I get an err on the line: var url = UrlShortener.Url.insert({longUrl: 'www.google.com'});
error 403, message:forbidden
when i try an execute the rangeShort() function. I have no idea how to fix this. Any ideas would be most appreciated! Thanks!
As it turns out, like Ruben mentioned, Google has moved away from their URL shortener. So after much research ans testing here is the solution:
Step 1
Migrate Google Cloud Project over to Firebase or create a new Firebase Project. See steps here
Step 2
Create a dummy project in order to create a base URL for the shortening. See this youtube video
Step 3
Get the Web API Key from your new Firebase Project (not the app you just created)
Step 4
Check the left side menu on the screen and navigate to Grow->Dynamic Links. You should see the new application you created and a URL at the top of the application. This will become the base of the new shortened URLs.
Step 5
Create the code in Google Apps Script inside the code builder from within Google Sheets. Here is the code that worked for me (I passed the url into this function) (This code is based on the answer found here):
function api_call(url){
var req='https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[YOUR PROJECT WEB API KEY FROM STEP 3]';
var formData = {
"longDynamicLink": "[YOUR APPLICATION URL BASE FROM STEP 4]?link=" + url,
"suffix" : {
"option" : "UNGUESSABLE"
}
};
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(formData)
};
var response = UrlFetchApp.fetch(req, options);
var res=JSON.parse(response);
return res.shortLink;
}
Additional Information
Documentation on Creating Dynamic Links in Firebase
Documentation on using UrlFetchApp() in Google Apps Script
If the url shortener service was used in your project before March 30,2018
Instead of
www.google.com
use
https://www.google.com
Reference: https://developers.google.com/url-shortener/v1/url/insert
but if your project was created on or after March 30, 2018
From https://developers.google.com/url-shortener/v1/
Starting March 30, 2018, we will be turning down support for goo.gl URL shortener. Please see this blog post for detailed timelines and alternatives.
Just to be clear, please note, from the linked blog post:
For developers
Starting May 30, 2018, only projects that have accessed URL Shortener
APIs before today can create short links.
I can attest to #alutz's answer here with a small addition/correction to their code.
Use encodeURIcomponent() for the input url while assigning it to the Long Dynamic Link in case you have more than one custom parameters.
"longDynamicLink": "[YOUR APPLICATION URL BASE FROM STEP 4]?link=" + encodeURIcomponent(url),
This allowed me to pass in multiple arguments for my telegram bot like chat_id, text and parse_mode.
I am trying to display a Google Visualization GeoMap on my website. I created the code in the Code Playground and saved it as an Apps Script in my website. The page goes through the load process but nothing is displayed.
Here is the code:
function doGet() {
var app = UiApp.createApplication();
function drawVisualization() {
var query = new google.visualization.Query(
'https://docs.google.com/a/mantisnetworks.co/spreadsheet/ccc?key=0AoNHsySj5NxGdGt0dmxva3ZPb3dLYVpVZ2Z4TThNbGc&usp=drive_web#gid=0');
query.send(handleQueryResponse);
}
function handleQueryResponse(response){
if(response.isError()){
alert('Error in Query:' + response.getMessage()+''+response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var geochart = new google.visualization.GeoMap(document.getElementById('visualization'));
var options = {};
options['dataMode'] = 'regions';
options['resolution'] = 'provinces';
options['region'] = 'LS';
options['width'] = '600px';
options['height'] = '300px';
geochart.draw(data, options);
}
app.close();
return app;
}
Google Apps Script is based on Javascript, but as a server-side environment it does not have access to all client-side javascript constructs. The Google visualizations, for instance, are provided as the Charts Service. Using that service, you'll find support for much of the visualization API. However, you won't find GeoMap.
The code you've provided in your question needs to be reworked considerably to work properly in Google Apps Script. Start with the example given on the Charts Service page, then adapt to your situation.
You do have another alternative within Google Apps Script, which is to use the HTML service to "host" an HTML page containing "real" javascript. Javascript that's embedded in HTML pages can be made to run on the client browser, so the example you cooked up in the playground should work. A full run-down of this option is beyond the scope of your question, but if you're interested in it you could start by scanning previous questions about the HTML Service.
I have a Google Docs Spreadsheet that I'd like to use to update referenced cards in Trello. I've had some success with oauth and pulling data via their HTTP API, but am stuck with the following:
1) it seems Trello's code.js requires a window object, which the Google Doc script doesn't provide. So, I am stuck using their HTTP API.
2) authenticating via OAuth works, but only gives me read access. I cannot update cards with the token I am able to get.
function test() {
var oauthConfig = UrlFetchApp.addOAuthService("trello");
oauthConfig.setAccessTokenUrl("https://trello.com/1/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://trello.com/1/OAuthGetRequestToken");
oauthConfig.setAuthorizationUrl("https://trello.com/1/authorize?key=" + consumerKey + "&name=trello&expiration=never&response_type=token&scope=read,write");
//oauthConfig.setAuthorizationUrl("https://trello.com/1/OAuthAuthorizeToken"); <-- this only gives read access. Cannot POST
oauthConfig.setConsumerKey(consumerKey);
oauthConfig.setConsumerSecret(consumerSecret);
var url = 'https://trello.com/1/cards/yOqEgvzb/actions/comments&text=Testing...';
var postOptions = {"method" : "post",
"oAuthServiceName": "trello",
"oAuthUseToken": "always"};
var response = UrlFetchApp.fetch(url, postOptions); // "Request failed for returned code 404. Truncated server response: Cannot POST"
Logger.log(response.getContentText());
}
I've found a number of related questions but no direct answers:
How to get a permanent user token for writes using the Trello API?
Trello API: vote on a card
Trello API: How to POST a Card from Google Apps Script (GAS)
Google apps script oauth connect doesn't work with trello
Many thanks ahead of time for any advice.
In order to get write access, you need to change the authorization url.
This example works for me
var oauthConfig = UrlFetchApp.addOAuthService("trello");
oauthConfig.setAccessTokenUrl("https://trello.com/1/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://trello.com/1/OAuthGetRequestToken");
oauthConfig.setAuthorizationUrl("https://trello.com/1/OAuthAuthorizeToken?scope=read,write");
on 1) yes you cant use the library from server gas, its meant to be run from a browser.
on 2), Ive done it from GAS with write access without problems. You need to use the format:
https://api.trello.com/1/.../xxxx?key=yyyyyy&token=zzzzzzz&...
and when you get the token, you need to request permanent access (no expiration) and write access, as in:
https://trello.com/1/authorize?key="+key+"&name=xxxxxxx&expiration=never&response_type=token&scope=read,write"
As in:
function postNewCardCommentWorker(cardId, comment, key, token) {
var commentEncoded=encodeURIComponent(comment);
var url = "https://api.trello.com/1/cards/"+cardId+"/actions/comments?text="+commentEncoded+"&key="+key+"&token="+token;
var options =
{
"method" : "POST"
};
UrlFetchApp.fetch(url, options);
}