Hi I'm trying to get the current WTI (West Texas Intermediate) price but GoogleFinance doesn't recognize it. Has anybody had luck with this?
Ok. Found a solution. Google Sheets has an add-on and you can add the Yahoo Finance and then run formula =YAHOOFINANCE("ticker") and pick up commodities such as WTI (CL=F).
With Yahoo, you can also get the information by decoding the json cntained in the web page. In A1 for instance =marketPrice("CL=F") and the script :
function marketPrice(code) {
var url='https://finance.yahoo.com/quote/'+code
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
var regularMarketPrice = data.context.dispatcher.stores.StreamDataStore.quoteData.item(code).regularMarketPrice.raw
return regularMarketPrice
}
Object.prototype.item=function(i){return this[i]};
Try
=GOOGLEFINANCE("NYSE:WTI","price")
Related
For these inputs:
Origin
Destination
Arrival Time
I want two Google Sheets formulas that result in showing:
the distance in miles
travel times (driving, with traffic).
It'd be simple formulas that reference cells in the sheet that goes something like
=TravelTime(Origin,Destination,Arrive)
I've set up a Google Directions API account and pieced together this so far, but I have no idea how to get the URL to work and how to get the formula to return the outputs I want.
function TravelTime(Origin,Destination,Arrive) {
var Origin
var Destination
var Arrive
var apiUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin='&Origin&'&destination='&Destination&'&key=MYKEY';
}
It seems you are trying to call an external API.
Try doing something like this:
function TravelTime(Origin,Destination,Arrive) {
var apiUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin='&Origin&'&destination='&Destination&'&key=MYKEY';
var response = UrlFetchApp.fetch(apiUrl);
var json = response.getContentText();
var data = JSON.parse(json); //your final object, get the data you want here then return it.
}
Hope it helps!
I am new to decoding hence I am unable to decode below response while using UrlFetchApp.
Below is the function I am using to fetch data but getting values in unicode which I need to decode. Any function that I can use to decode this?
function scrape() {
var url = UrlFetchApp.fetch("https://immi.homeaffairs.gov.au/visas/working-in-australia/skillselect/invitation-rounds");
var elements =/id="ctl00_PlaceHolderMain_PageSchemaHiddenField_Input" (.*?)\/>/gim;
var x = url.getContentText().match(elements);
Logger.log(x);
}
Although I'm not sure whether this is the best way, how about this modification?
Modified script:
function scrape() {
var url = UrlFetchApp.fetch("https://immi.homeaffairs.gov.au/visas/working-in-australia/skillselect/invitation-rounds");
var elements =/id="ctl00_PlaceHolderMain_PageSchemaHiddenField_Input" (.*?)\/>/gim;
var x = url.getContentText().match(elements);
var res = unescape(x[0].replace(/\\u/g, "%u")); // Added
Logger.log(res)
}
Result:
When above modified script is used, as a sample, the values are converted as follows.
From:
\u003cp\u003eThe table below shows the number of invitations issued in the SkillSelect invitation round on 11 September 2018.\u003c/p\u003e\n\n\u003ch3\u003eInvitations issued on 11 September 2018\u003c/h3\u003e\n\n
To:
<p>The table below shows the number of invitations issued in the SkillSelect invitation round on 11 September 2018.</p>\n\n<h3>Invitations issued on 11 September 2018</h3>\n\n
References:
unescape()
replace()
If I misunderstand your question, I'm sorry.
function scrape() {
var url = UrlFetchApp.fetch("https://immi.homeaffairs.gov.au/visas/working-in-australia/skillselect/invitation-rounds");
var elements =/id="ctl00_PlaceHolderMain_PageSchemaHiddenField_Input" (.*?)\/>/gim;
var x = url.getContentText().match(elements);
var res = unescape(x[0].replace(/\\u/g, "%u")); // Added
Logger.log(res)
}
I keep finding forum results that refer to the google visualiser for displaying my query results. But it just seems to dump the data in a pre-made table. I haven't found a way to write my own custom table dynamically.
In the past, when I have hacked together PHP to make use of mySQL DB, I would simply connect to my DB, run a query into an array, then cycle through the array and write the table in HTML. I could do IF statements in the middle for formatting or extra tweaks to the displayed data, etc. But I am struggling to find documentation on how to do something similar in a google script. What is the equivalent work flow? Can someone point me to a tutorial that will start me down this path?
I just want a simple HTML page with text box and submit button that runs a query on my Google sheet (back in the .gs file) and displays the results in a table back on the HTML page.
Maybe my understanding that GAS/google sheets is an alternative to PHP/mySQL is where I'm going wrong? Am I trying to make a smoothie with a toaster instead of a blender?
Any help appreciated
Welcome David. Ruben is right, it's cool to post up some code you have tried. But I spent many months getting my head around Apps-script and love to share what I know. There are several ways to get the data out of a Google sheet. There is a very well document Spreadsheet Service For GAS. There is also a client API..
There is the approach you mention. I suggest converting the incoming data to JSON so you can do with it as you like.
Unauthenticated frontend queries are also possible. Which needs the spreadsheet to be published and set to anyone with the link can view, and uses the Google visualisation API
var sql = 'SELECT A,B,C,D,E,F,G where A = true order by A DESC LIMIT 10 offset '
var queryString = encodeURIComponent(sql);
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/'+ spreadsheetId +'/gviz/tq?tq=' + queryString);
query.send(handleSampleDataQueryResponse);
function handleSampleDataQueryResponseTotal(responsetotal) {
var myData = responsetotal.getDataTable();
var myObject = JSON.parse(myData.toJSON());
console.log(myObject)
}
Other Approaches
In your GAS back end this can get all of your data in columns A to C as an array of arrays ([[row1],[row2],[row3]]).
function getData(query){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A1:C');
var data = range.getValues();
// return data after some query
}
In your GAS front end this can call to your backend.
var data = google.script.run.withSuccessHandler(success).getData(query);
var success = (e) => {
console.log(e)
}
In your GAS backend this can add data to your sheet. The client side API will also add data, but is more complex and needs authentication.
function getData(data){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A1:C');
var data = range.setValues([[row1],[row2],[row3]]);
return 'success!'
}
In your GAS frontend this can send data to your backend.
var updateData = [[row1],[row2],[row3]]
var data = google.script.run.withSuccessHandler(success).getData(updateData);
var success = (e) => {
console.log(e)
}
Finally
Or you can get everything from the sheet as JSON and do the query in the client. This works okay if you manipulate the data in the sheet as you will need it. This also needs the spreadsheet to be published and set to anyone with the link can view.
var firstSheet = function(){
var spreadsheetID = "SOME_ID";
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID +"/1/public/values?alt=json";
return new Promise((resolve,reject)=>{
$.getJSON(url, (data)=>{
let result = data.feed.entry
resolve(result)
});
})
}
firstSheet().then(function(data){
console.log(data)
})
I am new to Google API and got training wheels on for the App Script.
I need to know if there is a way to utilize the Activity API or any other inside App Script to pull sharing activity for all domain users.
Thanks in advance.
I got the following working for me but it is not showing me the "shared_externally" in particular, I need to use https://developers.google.com/admin-sdk/reports/v1/reference/activities/list api for all users on drive app, externally and internally shared filter.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
visibility: 'shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);
}
My output is the same with or without the optionalArgs for shared_externally, can someone help with the proper syntax for the visibility arguments?
Ok I got it to work, yay.
function listShares() {
var userKey = 'all';
var applicationName = 'drive';
var optionalArgs = {
filters: 'visibility==shared_externally'
};
var response = AdminReports.Activities.list(userKey, applicationName,
optionalArgs)
Logger.log(response);}
i need to get the page name of a google sites with google apps script, there is another post about it but is about URL such as Retrieve page title from URL in Apps Script, but i need to get the page title name.
Thanks.
If you are in a domain, use the following, replacing teh strings as appropriate.
var site = SitesApp.getSite("mydomainname.org", "sitename");
var page = site.getChildren()[0];
var title = page.getTitle();
Karl
As per this stackoverflow answer, the function works well for getting page title.
function betweenMarkers(text, begin, end) {
var firstChar = text.indexOf(begin) + begin.length;
var lastChar = text.indexOf(end);
var newText = text.substring(firstChar, lastChar);
return newText;
}
var pageTitle = betweenMarkers(response.getContentText(),"<title>","</title>")
console.log(pageTitle)