I am able to export data such as names and emails using the code below. However I cannot export data for emails sent, etc. Not sure if I'm using the wrong terms. I'm struggling to find reliable documentation for this information.
function myFunction() {
// SalesLoft API credentials
var salesloft_api_key = 'API_KEY_PLACEHOLDER';
var headers = {'Authorization': 'Bearer ' + salesloft_api_key};
// Get data from SalesLoft API
var people_data = [];
var page = 1;
var page_size = 100; // Change this to the desired page size
while (true) {
var response = UrlFetchApp.fetch('https://api.salesloft.com/v2/people.json?page=' + page + '&per_page=' + page_size, {headers: headers});
var page_data = JSON.parse(response.getContentText()).data;
if (page_data.length == 0) {
break;
}
people_data = people_data.concat(page_data);
page++;
}
// Open Google Sheet and clear previous data
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
sheet.getRange(2, 1, sheet.getLastRow()-1, sheet.getLastColumn()).clear();
// Write headers
var headers = [
'id',
'first_name',
'last_name',
'display_name',
'email_address',
'person_or_lead',
'title',
'phone',
'city',
'state',
'country',
'industry',
'linkedin_url',
'personal_website_url',
'twitter_handle',
'last_contacted_at',
'last_activity_at',
'emails_sent',
'emails_clicked'
];
sheet.appendRow(headers);
// Write data to Google Sheet
for (var i = 0; i < people_data.length; i++) {
var person = people_data[i];
var row = [
person.id,
person.first_name,
person.last_name,
person.display_name,
person.email_address,
person.person_or_lead,
person.title,
person.phone,
person.city,
person.state,
person.country,
person.industry,
person.linkedin_url,
person.personal_website_url,
person.twitter_handle,
person.last_contacted_at,
person.last_activity_at,
person.emails_sent,
person.emails_clicked
];
sheet.appendRow(row);
}
}
Obviously I used a real api key in the code. However, most of the information gets exported effectively but not emails sent or emails clicked. These are the more important data points for me.
Related
I have a google app script that allows me to retrieve data via a public API and a fetch. So far so good. I initialized a table in order to push the data into it, then I call a function that will send the data to a column of my google sheets table. My first function fills the array with a "while" loop, when the length of the array reaches 12, my "pushDatasToSheet" function launches but I have an error, the console tells me that my data range is at 1 and therefore does not correspond not in range of my selected cells. What is funny is that my table does indeed indicate a length of 12 when executing my function sending data to the table and when I modify the range of my cells by putting only one , the console shows me 12 for my data range. I can't find where my mistake is coming from. thank you in advance for your help.
Here an image of the console error:
error code in app script console
And my code:
const signsList = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"];
var SHEET_NAME = "horoscope";
const options = {
'method': 'post',
};
var rowDescription = [];
// Get horoscopes from API
function doPost(e) {
signsList.forEach(sign => {
while (rowDescription.length < 12) {
var url = 'https://aztro.sameerkumar.website/?sign=' + sign + '&day=today';
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
rowDescription.push(data.description);
}
pushDatasToSheet();
})
}
function pushDatasToSheet() {
Logger.log(rowDescription.length);
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
var descriptionColumn = sheet.getRange('B2:B13');
descriptionColumn.setValues([rowDescription]);
};
Problem solved 😅
In case another person with the same problem happen, the array have to be a 2D array. And i have changed my while loop for a if statement.
Here the correction snippet:
const signsList = ["aries", "taurus", "gemini", "cancer", "leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"];
var SHEET_NAME = "horoscope";
const options = {
'method': 'post',
};
var rowDescription = [];
// Get horoscopes from API
function doPost(e) {
if (rowDescription.length < 12) {
signsList.forEach(sign => {
var url = 'https://aztro.sameerkumar.website/?sign=' + sign + '&day=today';
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
rowDescription.push([data.description]);
})
}
pushDatasToSheet();
}
function pushDatasToSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
sheet.getRange('B2:B13').setValues(rowDescription);
};
I'm trying to figure out how to send request to URL, so that it populates in Google Sheets. At this moment the log throws error "Order not found". It's my first time writing script for that request. So far I have:
function myFunction() {
var data = {
"date":"2021-07-01",
"reference":"REFERENCE",
"products":[
{
"id":"31565598851174",
"quantity":15
},
{
"id":"31424655589478",
"quantity":10
}
]
}
var options = {
'method' : 'post',
'contentType': 'application/json',
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var url = "https://stockists.rerootedorganic.co.uk/api/order/?key=example"
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
I think that the problem might be with the syntax in query. Any help to identify what I'm doing wrong would be amazing, thank you.
Errors:
Execution log
11:45:18 AM Notice Execution started
11:45:19 AM Info
{"error":{"message":"Order not found"}}
11:45:19 AM Info null
11:45:20 AM Info
{"error":{"message":"Order not found"}}
11:45:20 AM Info {error={message=Order not found}}
11:45:19 AM Notice Execution completed
Adapt this code
function myFunction() {
var url = 'https://stockists.rerootedorganic.co.uk/api/order/?key=example&date='
var when = '2021-07-01' // string format
var data = JSON.parse(UrlFetchApp.fetch(url+when).getContentText())
Logger.log(data.order.reference)
for (var i=0;i<data.order.products.length;i++){
Logger.log(data.order.products[i].id + ' qty: ' + data.order.products[i].quantity)
}
}
to populate the sheet
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('** Menu **')
.addItem('request','myFunction')
.addToUi();
}
function myFunction() {
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var d = Utilities.formatDate(sh.getRange('B3').getValue(), "GMT+2", "yyyy-MM-dd")
var url = sh.getRange('B1').getValue() + '?key=' + sh.getRange('B2').getValue() + '&date=' + d
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())
for (var i=0;i<data.order.products.length;i++){
sh.appendRow([data.order.reference,data.order.products[i].id,data.order.products[i].quantity])
}
}
I am working on a personal project to try and stretch limits of a 10K ft project management systems API and being new to GAS or Javascript I will appreciate help on the code I am trying to do. The API documentation for this can be found at https://github.com/10Kft/10kft-api.
Using time entries and users endpoints, I would like to loop through all users and get their time entries for a particular time frame. I would like these data saved as an array and the time entries (hours) added to get totals. If for some reason, a particular user time entries are below 3hrs, an email is sent to the user notifying him/her to complete timesheets. I got lost at some point. Here is the code I have so far: Anyone good at this, please help.
function getTime() {
var range = [5323, 9626, 4998];
var user = [];
for (var i = 0; i < range.length; i++) {
var auth = 'xxxxxxxx=';
var from = '2020-01-08'
var to = '2020-01-09'
var url = 'https://api.10000ft.com/api/v1/users/' + range[i] + '/time_entries?from=' + from + '&to=' + to + '&auth=' + auth;
var options = {
method: 'get',
headers: {
Authorization: 'Bearer ' + auth
}
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response.getContentText());
var user_data = response.getContentText();
user_data.foreach(function(data) {
var total_hours = sum.reduce(data.hours);
})
var array = [];
return array;
}}
You'll need to parse the response.
Loop through user entries.
Aggregate them based on user id.
Loop through aggregation.
Conditionally send email.
Something like this :
var submitted_time_entries = {};
var response = UrlFetchApp.fetch(url, options);
var response = JSON.parse(response.getContentText());
var time_entries = response.data;
time_entries.foreach(function(time_entry) {
if (time_entry.user_id in submitted_time_entries) {
submitted_time_entries[time_entry.user_id] += time_entry.hours;
} else {
submitted_time_entries[time_entry.user_id] = time_entry.hours;
}
});
submitted_time_entries.forEach(function(user_id) {
if (submitted_time_entries[user_id] < 3) {
//send mail
}
});
I'm using Google SpreadSheet and IFTTT to do a DB Call Log of my phone, this is working perfect.
Now I'm trying to populate a form in a web page by API from this DB Call Log.
I would like to send lastRow to my API every time IFTTT populate the Sheet.
The first Row in the Sheet is populated with headers name: departament, first_name, last_name, email, phone, deadline.
So i manage to send data to API like this:
function myFunction() {
var data = {
'department': 1,
'first_name' : 'Test',
'last_name' : 'test',
'email' : 'email#gmail.com',
'phone' : ["0700000000"],
'deadline' : '2017-04-10T00:00'
}
var payload = JSON.stringify(data)
var headers = {
'AUTHORIZATION': 'Token b8473654v6345teryrby456yrtyrtyertytdvfh87afc',
// Add any other required parameters for XXX API.
};
var url = 'http://api.XXX.com/api/1.0/clients/';
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers,
'payload' : payload,
};
var response = UrlFetchApp.fetch(url, options);
}
Now i need to automate it but i don't know how:
(this is a SpreadSheet question) IFTTT populate the "deadline" column in this format "April 10, 2017 at 01:54PM" however the needed format for API is "2017-04-10T13:54", how to auto modify it?
to get the values from Sheet cells (from lastRow) and send them throw json payload
to set a trigger event so the script trigger's every time IFTTT populates a new Row in the Sheet.
Thank you!
Will try to answer the question one by one:
1) Reformat date: You can use Utilities.formatDate() in apps script to modify your date.
Code:
function reformatDate(dtStr)
{
if (dtStr == undefined)
dtStr = "April 1, 2017 at 01:54PM"
dtStr = dtStr.replace("at", "") // Remove at
dtStr = dtStr.replace(/(\d)(PM)/g,"$1 $2") //Add a space between the time and PM
dtStr = dtStr.replace(/(\d)(AM)/g,"$1 $2") //Add a space between the time and AM
Logger.log(dtStr)
dtStr = new Date(dtStr)
var newDt = Utilities.formatDate(dtStr, SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm")
Logger.log(newDt)
return newDt
}
2) Get last row Values: You can use getLastRow() and getValues() functions in apps scripts
function lastRowData(){
var ss = SpreadsheetApp.getActive()
var sheet = ss.getActiveSheet()
var lastRow = sheet.getLastRow()
var lastCol = sheet.getLastColumn()
var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getValues()
return lastRowData[0]
}
Edit
To get values as is i.e. displayed values in the sheet, you can modify the getvalues to getDisplayValues() like so:
var lastRowData = sheet.getRange(lastRow,1,1,lastCol).getDisplayValues()
3) Trigger your sheet: I will not reinvent the wheel here. But will provide you with an awesome answer from #Mogsdad
Link: Trigger an email when a cell is written into from another app (IFTTT)
In short, you will have to use onEdit Trigger to detect new entries.
If on edit doesn't work, try on Change trigger.
Complete code:
function myFunction() {
var lastRow = lastRowData()
var data = {
'department': lastRow[0],
'first_name' : lastRow[1],
'last_name' : lastRow[2],
'email' : lastRow[3]',
'phone' : [lastRow[4]],
'deadline' : reformatDate(lastRow[5])
}
var payload = JSON.stringify(data)
var headers = {
'AUTHORIZATION': 'Token b8473654v6345teryrby456yrtyrtyertytdvfh87afc',
// Add any other required parameters for XXX API.
};
var url = 'http://api.XXX.com/api/1.0/clients/';
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headers,
'payload' : payload,
};
var response = UrlFetchApp.fetch(url, options);
}
Hope that helps!
I am building a mobile app using Titanium for ios and I am having a tough time getting my arms wrapped around passing variables. I am using a combination of local database and remote database to deliver my data. In this case I want to pass the data on the tableViewRow selected. The label that displays the data I call "categorydescription". In my table.addEventListener, I want to pass that data as the title for the new window and I will pass that same data to my php file on the remote server. Here is the code I am trying to use:
var xhr = Ti.Network.createHTTPClient({
onload: function() {
Ti.API.debug(this.responseText);
var json = JSON.parse(this.responseText);
for (i = 0; i < json.cms_client.length; i++) {
client = json.cms_client[i];
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true
});
var categorydescription = Ti.UI.createLabel({
text:client.catdesc,
font:{fontSize:'16dp', fontWeight:'bold'},
height:'auto',
left:'10dp',
color:'#000'
});
row.add(categorydescription);
tableData.push(row);
}
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: ??});
var catdesc = ??;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});
table.setData(tableData);
Would someone be so kind to tell me what I need to put in place of the ?? in the 'title' and 'var catdesc' above?
Just add the category description and title to the row object itself:
row = Ti.UI.createTableViewRow({
height:'44dp',
hasChild:true,
categoryDescription : client.catdesc, //Add this
clientTitle : client.title // Add this
});
Now get them in the listener:
table.addEventListener('click',function(e) {
var win = Ti.UI.createWindow({url: 'clients.js', title: e.row.title});
var catdesc = e.row.categoryDescription;
win.catdesc = catdesc;
Titanium.UI.currentTab.open(win,{animated:true});
});