Update google contact photo with People API using google apps script - google-apps-script

I want to update a contact photo of my contacts using People API and google apps script. official document URL is here https://developers.google.com/people/api/rest/v1/people/updateContactPhoto
My Google Apps script code is below
function imageUpdate(){
var id = 'c6379259805458445151'
var url = 'https://admin.singlaapparels.com/Main/fileurl/64F619B8-C2BE-4EDF-BF9B-01FD60C5D957/4/RakeshKumar.jpg'
var blob = UrlFetchApp.fetch(url).getBlob();
var data = Utilities.base64EncodeWebSafe(blob.getBytes());
var resourceName = 'people/'+id;
Logger.log(data)
var reqBody = {
"photoBytes": data,
"personFields": "photos"
}
var res = People.People.updateContactPhoto(resourceName, reqBody)
Logger.log(res)
}
I got this error: API call to people.people.updateContactPhoto failed with error: Empty response

I change the position of parameters and It works for me.
from
var res = People.People.updateContactPhoto(resourceName, reqBody)
to
var res = People.People.updateContactPhoto(reqBody, resourceName)

Related

Contact properties from HubSpot to Google Spreadsheet

function callHsapi() {
var API_KEY = "YOUR_HUBSPOT_API_KEY"; // Replace YOUR_HUBSPOT_API_KEY with your API Key
var url = "https://api.hubapi.com/crm/v3/objects/contacts?limit=100&archived=false&hapikey=YOUR_HUBSPOT_API_KEY"; // Replace YOUR_HUBSPOT_API_KEY with your API Key
var response = UrlFetchApp.fetch(url);
var data = JSON.parse(response.getContentText());
var results = data['results'];
var sheet = SpreadsheetApp.getActiveSheet();
var header = ["Email", "First Name", "Last Name", "id"];
var items = [header];
results.forEach(function (result) {
items.push([result['properties'].email, result['properties'].firstname, result['properties'].lastname, result['id']]);
});
sheet.getRange(10,1,items.length,items[0].length).setValues(items);
results.forEach(function (result) {
Logger.log(result['properties']);
});
}
Hello all, i'm trying to get contact properties from HubSpot to Google Spreadsheet, but i have more that 7000+ contacts in hubspot but from the above code i can get maximum 100 contacts, can anyone help me get all the contacts from Hubspot to google spread sheet?, also in the URL if i increase limit=100 i'm getting the error. Any suggestions is appreciated.
thank you.

Google Apps Script how to export specific sheet as csv format

In MIT Inventor II, I use web component to get SpreadsheetID and SheetID through doGet() of google apps script. After I get the information I use another web component to set url as below to get csv-formatted file from specific sheet. My question is how to make GAS to get SpreadsheetID & SheetID and then export csv file at one time, so that I don't have to use 2 web components in Inventor side?
GAS codes is as below. This is to "return" spreadsheetID and sheetID.
function doGet(e) {
filename = e.parameter.account;
fileList = DriveApp.getFilesByName(filename);
while (fileList.hasNext()) {
var fileID = fileList.next().getId()
}
var file = SpreadsheetApp.openById(fileID) ;
sheet = file.getSheetByName("Message").activate()
var messageID = sheet.getSheetId();
return ContentService.createTextOutput([fileID,messageID]);
After I got SpreadsheetID & SheetID, I have to set 2nd web component from Inventor side to get csv file, see below.
https://docs.google.com/spreadsheets/d/xxxxSpreadsheetIDxxxx/edit#gid=sheetID
Here is how you can create a csv file of a selected sheet in google drive:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Sheet1"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv"
}
var fileJson = Drive.Files.insert(resource,result)
}
The code creates a csv file that has the content of Sheet1.
In order to run the aforementioned function you need to activate the Advanced Drive Service.
Explanation:
Go to Resources => Advanced Google Services => activate Drive API
Another option is to create the csv file to a particular folder, then you need to replace the resource part of the code with this:
var folder_id ='id';
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{ id: folder_id }]
}
My application was how to save a tab of a Google sheets spreadsheet to a CSV file in a shared drive. Doing it to the default "My Drive" was relatively easy based on Marios' answer in this post, but I struggled with this for a shared drive while until I came across ziganotschka's example which solved my problem.
Code for my simple App Script is:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "[Your sheet name goes here]";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name);
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv";
var url = "https://docs.google.com/spreadsheets/d/"+ params;
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "MimeType.CSV",
parents:[{
"id": "[Your Shared Drive Folder ID goes here]"
}]
}
var optionalArgs={supportsAllDrives: true};
var fileJson = Drive.Files.insert(resource, result, optionalArgs);
}
I added a timestamp to the file name and a trigger to cause the script to execute daily via a timer.

Downloading a Google Slides presentation as PowerPoint doc using Google Apps Script?

The GUI of Google Slides offers to download a GSlides presentation as a Powerpoint (myFile.pptx). I could not find the equivalent in the Google Apps Script documentation - any pointer?
EDIT
Thanks to comments and answers, I tried this snippet:
function testFileOps() {
// Converts the file named 'Synthese' (which happens to be a Google Slide doc) into a pptx
var files = DriveApp.getFilesByName('Synthese');
var rootFolder = DriveApp.getRootFolder();
while (files.hasNext()) {
var file = files.next();
var blobPptx = file.getBlob().getAs('application/vnd.openxmlformats-officedocument.presentationml.presentation');
var result = rootFolder.createFile(blobPptx);
}
}
It returns an error:
Converting from application/vnd.google-apps.presentation to
application/vnd.openxmlformats-officedocument.presentationml.presentation
is not supported. (line 7, file "Code")
SECOND EDIT
As per another suggestion in comments, I tried to make an http call from Google App Script, that would directly convert the gslides into pptx, without size limit. It produces a file on G Drive, but this file is corrupted / unreadable. The GAS script:
function convertFileToPptx() {
// Converts a public Google Slide file into a pptx
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch('https://docs.google.com/presentation/d/1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4/export/pptx');
var blobPptx = response.getContent();
var result = rootFolder.createFile('test2.pptx',blobPptx,MimeType.MICROSOFT_POWERPOINT);
}
Notes:
I got the mime type for pptx here
using the mime type 'pptx' returns the same error message
How about this modification?
Modification point:
response.getContent() returns byte array. So please use response.getBlob().
Modified script:
function convertFileToPptx() {
var fileId = "1Zc4-yFoUYONXSLleV_IaFRlNk6flRKUuAw8M36VZe-4";
var outputFileName = "test2.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var rootFolder = DriveApp.getRootFolder();
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
Note:
If you want to convert Google Slides, which are not published, in your Google Drive, please use access token. At that time please modify url as follows.
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx?access_token=' + ScriptApp.getOAuthToken();
DriveApp.createFile() creates a file on root folder as the default.
References:
Class HTTPResponse
getOAuthToken()
As mentioned by tehhowch, you could get the Google Slide file from your Drive and get it as a .pptx. (Not sure of mime type.)
File#getAs:
I add all modifications with token part and specific folder
function convertFileToPptx() {
var fileId = "Your File ID";
var outputFileName = "name.pptx";
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
//var rootFolder = DriveApp.getRootFolder();
var rootFolder = DriveApp.getFolderById("Your Folder ID")
var params = {method:"GET", headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url,params);
var blobPptx = response.getBlob();
var result = rootFolder.createFile(blobPptx.setName(outputFileName));
}
To get the byte[] do:
function downloadAsPPTX(){
var presentation = SlidesApp.getActivePresentation();
var fileId = presentation.getId();
var url = 'https://docs.google.com/presentation/d/' + fileId + '/export/pptx';
var response = UrlFetchApp.fetch(url);
var blobPptx = response.getBlob();
Logger.log("size: "+blobPptx.getBytes().length);
}

Appscript API for fetching access permissions of team drive

I am trying to generate a report of all access permissions currently various users have in Team Drive. Is there any API in Appscript to Fetch this data?
There doesn't seem to be any method for getting Drive permissions sorted by username, so you will need to implement this business logic yourself. According to the documentation, sending a GET request to the API endpoint below will get you the list of permissions for the Team Drive (use Team Drive ID instead of file id):
https://www.googleapis.com/drive/v3/files/fileId/permissions
I don't have any Team Drives set up - the example below is based on getting permissions for a single file using Drive REST API. Before the code can be executed, you must prove your identity by including API key in URL parameters and passing OAuth token in the headers of your 'GET'request.
The API key can be obtained from Google Cloud console. Enable the Drive API and click the key icon in the left menu to set up credentials. Choose "API key" from the drop-down and copy the value.
Your script must pass the token that includes all required authorization scopes to the API endpoint. OAuth scopes are set explicitly in the manifest file. In Script Editor, select "View - Show manifest file" and add relevant scopes. Scopes used in my manifest file are for accessing Drive Files and calling external services via UrlFetchApp:
"oauthScopes": [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/script.external_request"]
Finally, get the list of permissions for the file:
var fileId = "FILE_ID";
var apiKey = "API_KEY";
var apiUrl = "https://www.googleapis.com/drive/v3/files/fileId/permissions";
var token = ScriptApp.getOAuthToken();
var header = {"Authorization":"Bearer " + token};
var options = {
"method":"GET",
"headers": header,
"muteHttpExceptions": true
};
var res = UrlFetchApp.fetch(apiUrl.replace("fileId", fileId) + "?key=" + apiKey, options)
.getContentText();
var permissions = JSON.parse(res);
Logger.log(permissions);
Updates with help from Anton's answer. (Working with Appmaker as well).
Here's how I have achieved it,
function fileExport(folderId) //pass folder id or drive/team drive id to fetch permissions
{
var parent = DriveApp.getFolderById(folderId);
var path = DriveApp.getFolderById(folderId).getName();
var fileName = 'Permisssions_' + new Date(); //define file name
var newExport = SpreadsheetApp.create(fileName); // create new spreadsheet
var header = ["Path","Folder","File Name","Email","Role","Name","DocUrl"]; //define header
newExport.appendRow(header); // append header to spreadsheet
newExport.setFrozenRows(1);
newExport.getRange("A1:H1").setFontWeight("bold");
//traverse through each folder under current folder
getChildFolders(parent,newExport,path);
//appned files associated with current folder
var files = parent.getFiles();
while (files.hasNext()) {
var file = files.next();
var permitFile= makeRestCall(file.getId());
for(var j=0; j<permitFile.length;j++)
{
newExport.appendRow([path,'',file.getName(),permitFile[j].emailAddress, permitFile[j].role,permitFile[j].displayName,file.getUrl()]);
}
}
return 'File exported successfully to this path:'+ newExport.getUrl();
}
//Iterate through child folders using recursive call
function getChildFolders(parent,newExport,path) {
var childFolders = parent.getFolders();
while (childFolders.hasNext()) {
var childFolder = childFolders.next();
path = path +'--'+childFolder.getName();
var permit= makeRestCall(childFolder.getId());
for(var i=0; i<permit.length;i++)
{
newExport.appendRow([path,childFolder.getName(),'',permit[i].emailAddress, permit[i].role,permit[i].displayName,childFolder.getUrl()]);
}
var files = childFolder.getFiles();
while (files.hasNext()) {
var file = files.next();
var permitFile= makeRestCall(file.getId());
for(var j=0; j<permitFile.length;j++)
{
newExport.appendRow([path,'',file.getName(),permitFile[j].emailAddress, permitFile[j].role,permitFile[j].displayName,file.getUrl()]);
}
}
// Recursive call for any sub-folders
getChildFolders(childFolder,newExport,path);
}
}
function makeRestCall(fileOrFolderId) //make rest call to fetch permissions
{
var apiUrl = "https://www.googleapis.com/drive/v3/files/fileId/permissions";
var token = ScriptApp.getOAuthToken();
var header = {"Authorization":"Bearer " + token};
var options = {
"method":"GET",
"headers": header
};
var response = UrlFetchApp.fetch(apiUrl.replace("fileId", fileOrFolderId) + "?supportsTeamDrives=true&fields=*", options)
.getContentText();
var dataAll = JSON.parse(response);
var permit = dataAll.permissions;
return permit;
}

Fail to read information from a web site using Google Apps Script

I have tried to use "UrlFetchApp.Fetch" in google apps script to retrieve data from https://metoc.ndbc.noaa.gov/web/guest/jtwc".
However, the information highlighted in red as shown here "web capture" cannot be captured in the file I downloaded. Please help, thanks.
var FILE_NAME = 'data.txt'
var Google_DRive_ID = 'your google drive folder id'
var RESOURCE_URL = 'https://metoc.ndbc.noaa.gov/web/guest/jtwc'
var folder = DriveApp.getFolderById(Google_DRive_ID);
var exportUrl = RESOURCE_URL
var data = UrlFetchApp.fetch(exportUrl)
folder.createFile(FILE_NAME, data)
When I saw the source of https://metoc.ndbc.noaa.gov/web/guest/jtwc, it was found that the source you want is included in iframe with the id="_48_INSTANCE_0SiamlX2KcM6_iframe". The source URL is src="/ProductFeeds-portlet/img/jtwc/html/coop.jsp?". When your script is modified using the URL, it is as follows.
Modified script :
var root = "https://metoc.ndbc.noaa.gov";
var src = "/ProductFeeds-portlet/img/jtwc/html/coop.jsp?"; // You can also use "/ProductFeeds-portlet/img/jtwc/html/coop.jsp"
var FILE_NAME = 'data.txt'
var Google_DRive_ID = 'your google drive folder id'
var RESOURCE_URL = root + src;
var folder = DriveApp.getFolderById(Google_DRive_ID);
var exportUrl = RESOURCE_URL
var data = UrlFetchApp.fetch(exportUrl)
folder.createFile(FILE_NAME, data)
If I misunderstand your question, I'm sorry.