Get Google Sheets Last Edit date using Sheets API v4 (Java) - google-sheets

I'm using the Google Sheets API v4 in Android.
https://developers.google.com/sheets/api/quickstart/android
I need to know when the last modification to the sheet was made (including by user); I need this guy:
I'd like to do something like this:
Spreadsheet spreadsheet = sheetsService.spreadsheets().get(spreadsheetId).setIncludeGridData(true).execute();
Date date = spreadsheet.getProperties().getLastEditDate();
But, of course, no such getLastEditDate() property method exists. Is there a parameter or another API method to call to get this data?
Even better would be to get the modified date for each cell... but I'd settle for the date of the entire spreadsheet or sheet.

This is not available in the Sheets API, but you may be able to use the Drive API's files.get method, which includes a 'modifiedTime' in the response. (Note that by default it will not include the modified time, you have to explicitly ask for it in the 'fields' parameter.)

It looks like this cannot be done with Sheets API v4.
However...it does look like it can be done with the compatible Google Drive API v3.
Note: the best part about this solution was that I could use the same method of authentication and credential gathering for both APIs. E.g., once I had the code for getting the credentials, I could use it for both API's interchangeably and consecutively.
Here's what I did:
Added this to my build.gradle (shown below my Sheets API declaration)
compile('com.google.apis:google-api-services-sheets:v4-rev468-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
compile('com.google.apis:google-api-services-drive:v3-rev69-1.22.0') {
exclude group: 'org.apache.httpcomponents'
}
I was already using the EasyPermissions method for getting account and credentials. Great example here.
Then...
import com.google.api.services.drive.Drive;
...
protected Drive driveService = new Drive.Builder(transport, jsonFactory, credential)
.setApplicationName("My Application Name")
.build();
... async:
private DateTime getSheetInformation() throws IOException {
String spreadsheetId = settings.getSpreadsheetId();
Drive.Files.Get fileRequest = driveService.files().get(spreadsheetId).setFields("id, modifiedTime");
File file = fileRequest.execute();
if (file != null) {
return file.getModifiedTime();
}
return null;
}

The sheets api v3 will be deprecated in March 2020, when that happens, your best bet is to use the drive API.
https://developers.google.com/drive/api/v3/reference/files/list
you can pass

Related

google sheets importxml resource at url not found - Yahoo Finance

I tried to get Walgreen's number of full-time employees from Yahoo Finance using importxml like so:
=importxml("https://finance.yahoo.com/quote/WBA/profile", "/html/body/div[1]/div/div/div[1]/div/div[3]/div[1]/div/div[1]/div/div/section/div[1]/div/div/p[2]/span[6]/span")
I have used the function successfully in getting other figures from Yahoo Finance. Example (market cap):
=mid(importxml("https://finance.yahoo.com/quote/WBA", "/html/body/div[1]/div/div/div[1]/div/div[3]/div[1]/div/div[1]/div/div/div/div[2]/div[2]/table/tbody/tr[1]/td[2]/span"),1,6)+0
But with the number of employees (and, by the way, also the trailing twelve months' (ttm) revenues) - I get this error.
Without VBA, with which I am not familiar, how can this be fixed?
Thanks!
This site is built client side by javascript, not server side. Therefore, native functions are inoperative.
You have to extract the json inside the source and parse it.
The object is named root.App.main inside the source.
To get employees for instance
function fullTimeEmployees(url='https://finance.yahoo.com/quote/WBA/profile'){
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/root.App.main = ([\s\S\w]+?);\n/)
if (!jsonString || jsonString.length == 1) return;
var data = JSON.parse(jsonString[1].trim())
Logger.log(data.context.dispatcher.stores.QuoteSummaryStore.assetProfile.fullTimeEmployees)
}

How to search the group by the DisplayName using Microsoft Graph?

According to the document, I can list the Office 365 Groups by using the following Graph API:
GET https://graph.microsoft.com/v1.0/groups
I have a C# Web application, and there is a input for searching by the Group DisplayName. Any idea how to query groups based on the DisplayName?
I have tried the following URL: https://graph.microsoft.com/v1.0/groups?$search="displayName:Test" in the MS Graph Explorer which didn't work.
I get the following error.
{
"error": {
"code": "Request_UnsupportedQuery",
"message": "This query is not supported.",
"innerError": {
"request-id": "35d90412-03f3-44e7-a7a4-d33cee155101",
"date": "2018-10-25T05:32:53"
}
}
Any suggestion is welcomed.
Thanks in advance.
According to your description, I assume you want to search the Group by the DisplayName using the search parameters.
Based on this document, we can currently search only message and person collections. So we couldn't use the search parameter.
We can use the filter query parameter to search the Group by DisplayName. For example, we can search the groups whose displayName is start with 'Test',the request url like this:
https://graph.microsoft.com/v1.0/groups?$filter=startswith(displayName,'Test')
Here is C# code that I wrote to get a group using the DisplayName. This code requires a reference to the OfficeDevPnP.Core.
private static async Task<Group> GetGroupByName(string accessToken, string groupName)
{
var graphClient = GraphUtility.CreateGraphClient(accessToken);
var targetGroupCollection = await graphClient.Groups.Request()
.Filter($"startsWith(displayName,'{groupName}')")
.GetAsync();
var targetGroup = targetGroupCollection.ToList().Where(g => g.DisplayName == groupName).FirstOrDefault();
if (targetGroup != null)
return targetGroup;
return null;
}
UPDATE
I see that the answer has already been accepted, but I came across the same issue and found that this answer is out of date. For the next person, this is the update:
The 'search' functionality does work. Whether it was fixed along the way or always has, I am not sure.
'groups' support search,
both the v1 and beta api support search,
search only works on 'displayName' and 'description' fields,
searching on 'directory objects' require a special header: 'ConsistencyLevel: eventual'
Point number 4 is what tripped me up!
Your request would look like this:
https://graph.microsoft.com/v1.0/groups?$search="displayName:Test"
With the request header:
ConsistencyLevel: eventual
There is another catch: You can only specify the first 21 characters and the search always uses 'startsWith'. You're out of luck if you specify more than that: The search always fails.

Unable to save a query as a view table

I have a query that runs and can see the results. But while trying to save the query as a view table, I get error message saying
Failed to save view. No suitable credentials found to access Google
Drive. Contact the table owner for assistance.
I think the problem is caused by a table used in the query. The table is uploaded from a google sheet (with source URI), own by me. I have tried to enable Google Drive API from the project but no luck. Not sure how I can give BigQuery access to Google Drive.
I suspect the problem you are hitting is one of OAuth Scopes. In order to talk to the Google Drive API to read data, you need to use credentials that were granted access to that API.
If you are using the BigQuery web UI and have not explicitly granted access to Drive, it won't work. For example, the first time I tried to "Save to Google Sheets", the BigQuery UI popped up an OAuth prompt asking me to grant access to my Google Drive. After this it could save the results. Try doing this to make sure your credentials have the Drive scope and then "Save View" again.
If you are using your own code to do this, you should request scope 'https://www.googleapis.com/auth/drive' in addition to the 'https://www.googleapis.com/auth/bigquery' scope you are already using to talk to BigQuery.
If you are using the bq client, it has been updated to request this scope, but you may need to re-initialize your authentication credentials. You can do this with bq init --delete_credentials to remove the credentials, then your next action we re-request credentials.
Using Google App Script this worked for me:
function saveQueryToTable() {
var projectId = '...yourprojectid goes here...';
var datasetId = '...yourdatesetid goes here...';
var sourceTable = '...your table or view goes here...';
var destTable = '...destination table goes here...';
var myQuery;
//just a random call to activate the Drive API scope
var test = Drive.Properties.list('...drive file id goes here...')
//list all tables for the particular dataset
var tableList = BigQuery.Tables.list(projectId, datasetId).getTables();
//if the table exist, delete it
for (var i = 0; i < tableList.length; i++) {
if (tableList[i].tableReference.tableId == destTable) {
BigQuery.Tables.remove(projectId, datasetId, destTable);
Logger.log("DELETED: " + destTable);
}
};
myQuery = 'SELECT * FROM [PROJECTID:DATASETID.TABLEID];'
.replace('PROJECTID',projectId)
.replace('DATASETID',datasetId)
.replace('TABLEID',sourceTable)
var job = {
configuration: {
query: {
query: myQuery,
destinationTable: {
projectId: projectId,
datasetId: datasetId,
tableId: destTable
}
}
}
};
var queryResults = BigQuery.Jobs.insert(job, projectId);
Logger.log(queryResults.status);
}
The 'trick' was a random call to the Drive API to ensure both the BigQuery and Drive scopes are included.
Google Apps Script Project Properties

Get Tweets with Pictures using twitter search api

Is it possible to get tweets which contain photos? I am currently using twitter search api and getting all the tweets having entity details by setting include_entities=true. I see picture details under media object but is there anyway to filter and get tweets objects which just have these media items. Or is there anyway in Twitter4j to do this query?
There is no specific way to specify that I need only photos or videos but you can filter the results based on filter:links or filter:images or filter:videos in your query along with include_entities=true.
For Example: To get the tweets that contain links since 2012-01-31, you query should have include_entities parameter as well as filter:links as shown as follows:
https://search.twitter.com/search.json?q=from%3Agoogle%20since%3A2012-01-31%20filter%3Alinks&include_entities=true"
As your need is to filter your tweets based on images/photos, I think you should use filter:images.
An example of your case would look like:
https://search.twitter.com/search.json?q=from%3Agoogle%20since%3A2012-01-31%20filter%3Aimages&include_entities=true"
Hope this helps.
With Latest twitter API I couldn't get filters work and I couldn't find either any explanation in their docs. Althought you can get all the tweets and then parse only the media ones. You can fire this if inside your parsing script:
if(this.entities.media != null){
//Parse the tweet
}
This is not the best solution but the worst part comes to twitter who's giving you more information and using more of its own resources.
In the lastest twitter API you can do it in the ConfigurationBuilder instance, before creating the Twitter instance:
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(false);
cb.setOAuthConsumerKey(API_KEY);
cb.setOAuthConsumerSecret(API_SECRET);
cb.setOAuthAccessToken(ACCESS_TOKEN);
cb.setOAuthAccessTokenSecret(SECRET_KEY);
// enabling include_entities parameters
cb.setIncludeEntitiesEnabled(true);
Twitter twitterInstance = new TwitterFactory(cb.build()).getInstance();
Also, after enabling the entities, in the search string you have to had the condition "filter:images".
List<String> keywords = new ArrayList<String>();
keywords.add("#pet");
keywords.add("cat");
// String.join for Java 8
String twitterSearchString = "((" + String.join(" OR ", keywords) + ")";
// adding the filter condition
twitterSearchString += " AND filter:images)";
Query q = new Query(twitterSearchString);
And you will get just results with images (tested with twitter4j-core 4.0.4).
For filter in twitter API you can check official document for latest version as on date Apr 02 2019
https://developer.twitter.com/en/docs/tweets/search/guides/standard-operators.html

Getting top twitter trends by country

I know how to get trends using API, but i want it by country and top 10.
How can I ? Is that possible?
Tried this one but not working
http://api.twitter.com/1/trends/current.json?count=50
Note that Twitter API v1 is no longer functional. Read announcement
So you should use Twitter API 1.1.
REST method is this: GET trends/place
https://dev.twitter.com/docs/api/1.1/get/trends/place
You should authenticate with access tokens to reach this data.
Yes, you can.
First, figure out which countries you want to get data for.
Calling
https://dev.twitter.com/docs/api/1/get/trends/available
Will give you a list of all the countries Twitter has trends for.
Suppose you want the trends for the UK. The above tells us that the WOEID is 23424975.
To get the top ten trends for the UK, call
https://api.twitter.com/1/trends/23424975.json
you need to figure out the woeids first use this tool here http://sigizmund.info/woeidinfo/ and then it becomes as easy as a simple function
function get_trends($woeid){
return json_decode(file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json?exclude=hashtags", true), false);
}
Here you go, I wrote a simple sample script for you. Check It Out Here Twitter Trends Getter
Hope it helps!
I'm a 'bit' late to the party on this one but you can use:
npm i twit --save
then,
const Twit = require('twit');
const config = require('./config');
const T = new Twit(config);
const params = {
id: '23424829',
id: '23424975',
id: '23424977'
// count: 3
};
T.get('trends/place', params, gotData, limit);
function gotData(err, data, response) {
var tweets = data;
console.log(JSON.stringify(tweets, undefined, 2));
}
You have to Complete Authentication using Api Key to Fetch Results in JSON.
Another Thing Keep in Mind Twitter Api is Limited.
If you are Making Website for Top Twitter Trends then Visit this Url https://twitter-trends.vlivetricks.com/, Right Click >> Copy Source Code and Replace only Trends Name using Your Json Variable.

Resources