I want to retrieve data via Jenkins API using Google Sheet Script and store it in Google Sheet
1) Pull Jenkins Job Builds using Jenkins API to Google Sheet - DONE
2) Store data to Google Sheet ???
(need only "builds.subBuilds.buildNumber" and "builds.subBuilds.duration" values)
(need to correct mistake in the script)
function getJenkinsBuilds() {
// get the jenkins job
var response = UrlFetchApp.fetch('http://jenkins.[domain].co/job/Build+Deploy/api/json', {
'method': 'get',
'muteHttpExceptions' : true,
'headers' : {'Authorization' : 'Basic [tokan]'},
});
// parse the json reply and return builds
var data = JSON.parse(response);
var builds = data["builds"];
Logger.log(builds);
return builds;
};
// store predefined parameters from builds in the spreadsheet
function setDataToTable() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Jenkins');
var cell = sheet.getRange("A1");
var rows = [['buildNumber','duration'],['','']]; // I GUESS THE MISTAKE IS HERE?
sheet.getRange(cell.getRow(), cell.getColumn(), rows.length, rows[0].length).setValues(rows);
}
Actual result:
Log shows retrieved array with Builds objects, i.e.:
[19-10-10 16:18:16:937 AEDT] [{number=2081, subBuilds=[{jobName=...
'Jenkins' spreadsheet is empty.
Expected result:
Store "builds.subBuilds.buildNumber" and "builds.subBuilds.duration" values
in the Google Sheet ('Jenkins' spreadsheet), i.e.:
buildNumber duration
123 15sec
456 16sec
... ...
I was able to make it working in the next way:
function getJenkinsBuilds()
{
// get jenkins builds
var response = UrlFetchApp.fetch('http://jenkins.[domain].co/job/Build+Deploy/api/json', {
'method': 'get',
'muteHttpExceptions' : true,
'headers' : {'Authorization' : 'Basic [token]'}
});
// parse the json reply
var data = JSON.parse(response);
var builds = data["builds"];
var number = data['builds'][0]['number'];
var url = data['builds'][0]['url'];
Logger.log(number);
Logger.log(url);
// fill in the spreadsheet with data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Jenkins');
var cell = sheet.getRange('A1');
var rows = [['BUILD']];
for (var i = 0; i < builds.length; i++)
{
var number = data['builds'][i]['number'];
var url = data['builds'][i]['url'];
rows.push(['=HYPERLINK("'+url+'","'+number+'")']);
Logger.log(number);
Logger.log(url);
sheet.getRange(cell.getRow(), cell.getColumn(), rows.length, rows[0].length).setValues(rows);
}
};
Related
I would like help with a google apps script. I would like to connect a Google sheet to the Mailerlite API in order to add multiple subscribers.
I would like to post each individual row from the google sheet as a subscriber in Mailerlite.
I would like a google sheet updated with the log of API responses with each trigger.
Here is the code I am using but can't get it to work. Thanks for your help!
function postUsersData() {
function getDataFromSpreadsheet() {
var usersSheetId = 11111111 // // Put your SHEET ID here
var usersSheet = getSheetById(usersSheetId)
// Users data
var values = usersSheet.getDataRange().getValues()
return values.map(function(value) {
return makePayload(values[0], value)
})
}
function postDataToMailerlite(payload) {
// API data
var url = 'https://api.mailerlite.com/api/v2/groups/'
var token = 'xxxxxxxxxxxxxxxxx' // // Put your TOKEN here
var groupId = 11111111 // // Put your GROUP ID here
var groupUrl = url + groupId + '/subscribers/import'
var params = {
'method': 'POST',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'apikey ' + token,
'Content-Type': 'application/json'
},
'payload': JSON.stringify({'subscribers': payload, 'resubscribe': false, 'autoresponders': true})
};
var response = UrlFetchApp.fetch(groupUrl, params)
return JSON.parse(response.getContentText())
}
function logAction(json) {
var logsSheetId = 11111111 // // Put your SHEET ID here
var logsSheet = getSheetById(logsSheetId)
var logsSheetValues = logsSheet.getDataRange().getValues()
var payload = {
'datetime': Date(),
'imported': json.imported.length,
'unchanged': json.unchanged.length,
'updated': json.updated.length,
'errors': json.errors.length,
'errors log': json.errors
}
Object.keys(payload).forEach(function(key) {
logsSheet.getRange(logsSheetValues.length + 1, logsSheetValues[0].indexOf(key) + 1).setValue(payload[key])
})
Logger.log('Done ' + Date())
}
function getSheetById(id) {
// Get sheet by ID
return SpreadsheetApp.getActive().getSheets().filter(
function(s) {return s.getSheetId() === id;})[0];
}
function makePayload(headers, value) {
// Make single user data JSON from data based on row number
return {
'email': value[headers.indexOf('email')],
'fields': {
'full_name': value[headers.indexOf('name')],
'job': value[headers.indexOf('job')],
'trigger': value[headers.indexOf('trigger')]
}
}
}
// Perform
const data = getDataFromSpreadsheet()
const response = postDataToMailerlite(data)
logAction(response)
}
I would like to add different API request on a spreadsheet where i already add some google app script code from here in oder to retrieve all orders from a woocommerce external source, however now i want to add another API calling request which allows me to list all products on my woocommerce source. So i type a new function below, modify the endpoint to /wp-json/wc/v3/products according to woocommerce API rest documentation here Woocommerce API rest doc. Here is the code i add to the Github code :
// Custom code to v2 Woocommerce API
function start_syncv2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(Products);
fetch_products(sheet)
}
function fetch_products(sheet) {
var ck = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B4").getValue();
var cs = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B5").getValue();
var website = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(OrderDetails).getRange("B3").getValue();
var surl = website + "/wp-json/wc/v3/sheet?consumer_key=" + ck + "&consumer_secret=" + cs + "&after=" + "&per_page=100";
var url = surl
Logger.log(url)
var options =
{
"method": "GET",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"muteHttpExceptions": true,
};
var result = UrlFetchApp.fetch(url, options);
Logger.log(result.getResponseCode())
if (result.getResponseCode() == 200) {
var params = JSON.parse(result.getContentText());
Logger.log(result.getContentText());
}
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = SpreadsheetApp.getSheetByName(sheet);
var consumption = {};
var arrayLength = params.length;
Logger.log(arrayLength)
for (var i = 0; i < arrayLength; i++) {
Logger.log("dfsfsdfsf")
var a;
var container = [];
a = container.push(params[i]["id"]);
Logger.log(a)
a = container.push(params[i]["name"]);
a = container.push(params[i]["sku"]);
a = container.push(params[i]["price"]);
a = container.push(params[i]["tax_status"]);
a = container.push(params[i]["stock_status"]);
a = container.push(params[i]["categories"]["name"]);
a = container.push(params[i]["images"]);
a = container.push(params[i]["attributes"]["options"]);
a = container.push(params[i]["_links"]["self"]["href"]);
var doc = SpreadsheetApp.getActiveSpreadsheet();
var temp = doc.getSheetByName(sheet);
temp.appendRow(container);
}
}
I have issue using google sheets calling method describe here. As i want my new API call request, i think my main problem is to select the right sheet into the spreadsheet.
Here is a copy of my spreadsheet : Woocommerce-google sheets integration
I'm trying to extract a specific value from this json file:
An example value I'm looking for is exDividendDate, fmt : 2020-09-24.
The code I've written to extract the value doesn't doesn't extract this or any other value and I'm not sure why. Any help would be greatly appreciated.
The error I get in the Google Apps Script is:
TypeError: Cannot read property 'earningsDate' of undefined (line 44,
file "Stock Database"
function callAPI(symbol) {
// Call the API
var url = 'https://query2.finance.yahoo.com/v10/finance/quoteSummary/'
var modules = "?modules=calendarEvents"
var response = UrlFetchApp.fetch(url + symbol + modules);
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data)
return JSON.parse(json)
}
function displayFinancials() {
// Load sheets
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Results");
var modelSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Financial Ratios Model");
// Get model input data
var company = "Apple"
var symbol = "AAPL"
// call the API
var api = callAPI(symbol);
var results = api[0];
// Output the API result
var output = [company, symbol, results.exDividendDate.fmt]
console.log(output);
dataSheet.appendRow(output)
}
When I saw the JSON data, it seems that exDividendDate is callAPI(symbol).quoteSummary.result[0].calendarEvents. So how about the following modification?
From:
var results = api[0];
To:
var results = api.quoteSummary.result[0].calendarEvents;
I need to change this code so that I have data from multiple sites in Analytics, ordered by date.
The code below works perfectly, but only for an Analytics account. I need to automate this, to get data from multiple sites in the same account.
function start(){
ScriptApp.newTrigger("getGoogleAnalyticsData").timeBased().everyDays(1).create();
}
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("Get external data")
.addItem("Google Analytics", "getGoogleAnalyticsData")
.addToUi();
}
function getGoogleAnalyticsData() {
var date = new Date();
var startDate = "2020-01-01";
var endDate = "2020-12-31";
var tableId = 'ga:201010452';
var metric = 'ga:totalPublisherRevenue';
var options = {
'dimensions': 'ga:date',
'sort': '-ga:date',
'filters': 'ga:medium!==organic',
'max-results': 425
};
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,options);
if (report.rows) {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();
var headers = report.columnHeaders.map(function(columnHeader) {
return columnHeader.name;
});
sheet.appendRow(headers);
sheet.getRange(2, 1, report.rows.length, headers.length)
.setValues(report.rows);
} else {
Logger.log('No rows returned.');
}
}
You can use Analytics Management API (https://developers.google.com/analytics/devguides/config/mgmt/v3) to get profile list from your account and adapt the code to cycle and query the views of interest.
I'm trying to save all of the sheets on my spreadsheet to google drive as one PDF (ultimately I would like to have them email as well). I'm having trouble saving more than just one of the sheets. I've tried multiple way of doing it. The code below is the best way I've found so far. Again the problem is that it only saves the first page as a PDF, I cant figure out how to get around the delete redundant sheets. All the posts I have seen only want to save 1 page, I have over 24 pages that need to be saved as one PDF. Thanks in advance for your help!
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
By using Drive API, you can convert from a spreadsheet to a PDF which has all sheets in the spreadsheet. In order to use this, so please enable Drive API on Google API Console as follows.
In the script editor, select Resources > Cloud Platform Project
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API "Drive API", then click the name once you see it.
On the next screen, click Enable API.
Close the Developers Console and return to the script editor. Click OK in the dialog.
I prepared a sample script for creating PDF file from spreadsheet. Please use this to your script.
Script :
var spreadsheetId = "#####";
var folderId = "#####";
var outputFilename = "#####";
var url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderId).createFile(response).setName(outputFilename);
About this script, although I confirmed this works fine, if it doesn't work at your environment, please tell me. And if I misunderstand your question, I'm sorry.
Added 1 :
function PDF() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet();
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
//Copy whole spreadsheet
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
//delete redundant sheets
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
//repace cell values with text (to avoid broken references)
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
//save to pdf
// var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
// var newFile = folder.createFile(theBlob);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + destSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Added 2 :
function PDF() {
var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
var ss = SpreadsheetApp.openByUrl(
'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***');
var pdfName = "MAR - " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
var sourceSpreadsheet = SpreadsheetApp.getActive();
var folder = DriveApp.getFolderById(folderID);
// A sample script was added here.
var url = "https://www.googleapis.com/drive/v3/files/" + sourceSpreadsheet.getId() + "/export?mimeType=application/pdf";
var options = {
method: "GET",
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options).getBlob();
DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
}
Here is the function that creates PDF file from google sheet and function that moves new created file into the folder that id you give to the parameter of the function.
function downloadPDF(fileId, folderId) {
var file = Drive.Files.get(fileId);
var url = file.exportLinks[MimeType.PDF];
var options = {
headers: {
Authorization:"Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions : true
}
var response = UrlFetchApp.fetch(url, options);
var status = response.getResponseCode();
var result = response.getContentText();
if (status != 200) {
// Get additional error message info, depending on format
if (result.toUpperCase().indexOf("<HTML") !== -1) {
var message = strip_tags(result);
}
else if (result.indexOf('errors') != -1) {
message = JSON.parse(result).error.message;
}
throw new Error('Error (' + status + ") " + message );
}
var doc = response.getBlob();
var newFileid = DriveApp.createFile(doc).setName(file.title + '.pdf').getId();
let id = moveFileTo(newFileid, folderId);
return id;
}
function moveFileTo(sourceId, folderId){
let file = DriveApp.getFileById(sourceId)
let blob = file.getBlob();
let id = DriveApp.getFolderById(folderId).createFile(blob).getId();
file.setTrashed(true)
return id;
}