How to Use UrlFetch in Google App script for getting Inner fields of Facebook page feed? - facebook-graph-api

I am trying to get the inner fields of facebook page feed json data through urlfetch function in Google App script but i am getting
invalid argument
error.
I saw some other resolution but non of them work in my case this is my codes
I am trying to get the atttachment inner fields eg fields=attachments{subattachments,url} the braces are the problem here so how to parse this through urlfetchApp?
var url = 'https://graph.facebook.com'
+ '/pageneme/feed'
+'?fields=name,full_picture,message,attachments{subattachments,url}&access_token=MYACCESStoken'
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
var data =jsondata.data
var pagename =data[0].name
var images= data[0].full_picture
var messages =data[0].message
var attachment = data[0].attachments
var media =data[0].subattachments
Logger.log(images); //check this and adjust following for loop and html
showFeed function accordingly
Logger.log(messages);
Logger.log(attachment);

Got it by myself thanks for those down voted
I had unsafe characters in my url. I had to encode the url:
var url = 'https://graph.facebook.com'
+ '/pagename/feed'
// + '?access_token=' + encodeURIComponent(getToken());
+'?fields='+
encodeURIComponent("name,full_picture,message,attachments{subattachments,url}")
+'&access_token=token'

Related

is "Client_credential" grant type can be used to access powerBI scopes?

In my project, I am trying to get embed report information from powerBI without interactive login.
so far I am able to get the information using "password" grant; when I am trying to do the same thing using "Password" grant, it is giving me "unauthorized" error.
I have hosted the application in my link to github.
explaination of the use:
Get access token to get access token for authentication.
var form = new Dictionary<string, string>();
form["grant_type"] = "password";
form["username"] = _config.Azure.Username;
form["password"] = _config.Azure.Password;
form["client_id"] = _config.Azure.ClientID;
form["client_secret"] = _config.Azure.ClientSecret;
form["scope"] = string.Join(" ",_config.Azure.Scopes);
var content = new FormUrlEncodedContent(form);
var input = new HttpInputModel
{
BaseAddress = $"{_config.Azure.AuthorityUrl}/{_config.Azure.TenantID}/",
Content = content,
Headers = new Dictionary<string, string>
{
{ "Content-Type","application/x-www-form-urlencoded" }
},
Url = "oauth2/v2.0/token"
};
use the above accesstoken came from above to get powerBI client.
var token = await _azureService.GetAccessToken();
var tokenCredentials = new TokenCredentials(token, "Bearer");
_client = new PowerBIClient(new Uri(_config.PowerBI.ApiUrl), tokenCredentials);
use the client to retrieve report information.
var workspaceId = reportInput.WorkspaceID;
var reportId = reportInput.ReportID;
var report = await _client.Reports.GetReportInGroupAsync(workspaceId, reportId);
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await _client.Reports.GenerateTokenAsync(workspaceId, reportId, generateTokenRequestParameters);
var output = new ReportOutput
{
Username = _config.PowerBI.Username,
EmbdedToken = tokenResponse,
EmbedUrl = report.EmbedUrl,
Id = reportInput.ReportID.ToString()
};
return output;
Conclusion: at the step 1: you can see I am using password grant
type. When I tried "client_crdentials" in place of "password" and did
not give "username" and "password". The generated "accesstoken" was
giving "Unauthorized" exception in step 3.
Note:I have tried to search in a lot of forums and some of them say we can use "serviceprincipal". But I am not able to do that.
I tried to follow the microsoft article for it and in that article they have mentioned to add SPN in pwoerBI. I tried that alot of times but it never worked for me.
Then i used another account andbit worked there so it was my accounts problem which was not allowing me to add SPN.
I already posted whole solution in github eith steps.
Here is the link:
https://github.com/Donjay2101/API--access-powerbi-without-login

Converting Google Visualization Query result into JSON

I am a beginner trying to read a Google Sheet in a Javascript app using: https://docs.google.com/spreadsheets/d/mySheetID/gviz/tq?tq=Select%20*%20where%20A%20=%20%22Nan%22&tqx=out:JSON
I can access that row in my sheet and save it as JSON giving me a file with the content headed "/O_o/
google.visualization.Query.setResponse..." This is the file I cannot further process in javascript.
I see in: converting Google Visualization Query result into javascript array
that the solution appears to be: "If you add a header named X-DataSource-Auth in your request, the Visualization API will respond in JSON format". After a day of googling I am quite unable to find where I am supposed to put such a header and what its syntax should be.
But then I'm 82 years old and this stuff gets more difficult with each passing year... Can someone point me in the right direction?
once you receive the response from the query,
you can convert the response to a google data table.
var dataTable = response.getDataTable();
and the google data table has a method to convert the data table to JSON.
var jsonData = dataTable.toJSON();
this will return a JSON string.
if you then would like to work with the JSON using JavaScript,
you can parse the string...
jsonData = JSON.parse(jsonData);
the JSON will be an object with two properties, cols and rows.
you can see an example of the JSON result here...
see this fiddle for a working example using the following code...
https://jsfiddle.net/WhiteHat/5mu9wnbz/1/
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1M3wQgKg3JBF6_hzv1xWONP7HWVYoOvJ1jPbB27IUg94/gviz/tq?gid=0&headers=1');
query.send(function (response) {
if (response.isError()) {
console.log('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
};
var dataTable = response.getDataTable();
var jsonData = dataTable.toJSON();
jsonData = JSON.parse(jsonData);
document.getElementById('cols').innerHTML = jsonData.cols.length;
document.getElementById('rows').innerHTML = jsonData.rows.length;
console.log(jsonData);
});
});

Validating JSON schema in Postman

When using Postman I validate the JSON response like so:
tv4.addSchema(globalSchema);
const valResult = tv4.validate(data, schema);
// schema is an object, which is a subschema from the larger globalSchema
which works fine, except for the error reporting. The error object I get is missing dataPath and schemaPath, making it hard for my user to find out where the actual problem is. Is there a way to get those properties? (tried validateResult and validateMultiple to no avail)
As an alternative I tried ajv, but as I am in draft-04, it gives me errors. The advice from their site
var ajv = new Ajv({schemaId: 'id'});
// If you want to use both draft-04 and draft-06/07 schemas:
// var ajv = new Ajv({schemaId: 'auto'});
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json'));
does not work because the Postman sandbox does not allow me to require that… any thoughts?
See also: https://community.getpostman.com/t/json-schema-validation-troubles/5024
Here's how I validate schema's with postman to get more detailed errors:
const schema = {
};
var jsonData = JSON.parse(responseBody);
pm.test('Checking Response Against Schema Validation', function() {
var result=tv4.validateMultiple(jsonData, schema);
console.log(result);
pm.expect(result.valid).to.be.true;
});

UrlFetch failed because too much traffic is being sent to the specified URL

I'm writing a script for Google Sheets that uses Facebook's Graph API to get my data. Everything worked earlier today but suddenly I'm getting an error:
UrlFetch failed because too much traffic is being sent to the
specified URL.
I haven't hit any quotas about using UrlFetch because I can still fetch from other urls that are not graph.facebook.com - so the issue appears to be specifically with Facebook.
Script Code
var myClientID = '';
var myClientSecret = '';
var myAccessToken = '';
var graphURL = 'https://graph.facebook.com/v2.3/';
function getPageLikes(campaign_id) {
var searchParams = '/stats?fields=actions';
var campaignID = campaign_id;
var fullURL = graphURL + campaignID + searchParams + '&access_token=' + myAccessToken;
var fetchResult = UrlFetchApp.fetch(fullURL);
var campaign = JSON.parse(fetchResult);
var likes = campaign.data[0].actions.like;
return likes;
}
Google Sheet Formula
=getWebClicks('E2')
I discovered a solution after a little more research. I added the 'useIntranet' option as a parameter to fetchResult and that seemed to solve the issue. I imagine the request is now being sent from another resource that doesn't limit requests to Facebook's Graph API.
If anyone can explain why this fixed my problem, that would be great as well!
var options = {"useIntranet" : true};
var fetchResult = UrlFetchApp.fetch(fullURL, options);
I don't have Facebook so I can't try this, replace var fetchResult = UrlFetchApp.fetch(fullURL); with:
do{
var fetchResult = UrlFetchApp.fetch(fullURL);
}while(fetchResult == 'UrlFetch failed because too much traffic is being sent to the specified URL.');
Or anything that matches this error object.
The correct answer is: just wait until the ban gets lifted.

How to login into a third-party website using google app script and manage data on login?

I am interested in creating a google app script that on run would login into a specific website (third-party) and complete certain functions within the website (pressing buttons/copying text).
After browsing the stackoverflow and other forums I have created a script that allows me to login into my website (source1 source2).
However, I am having difficulties staying logged in and managing the data.
//The current code is just testing if I can get data from within the website.
//The results are displayed in a google app.
function doGet() {
var app = UiApp.createApplication();
app.add(app.createLabel(display_basic_data()));
return app;
}
//logins into website and displays data
function display_basic_data() {
var data;
var url = "http://www.website.bla/users/sign_in";
var payload = {"user[username]":"usr","user[password]":"ps"};
var opt ={"method":"post","payload":payload, "followRedirects" : false};
var response = UrlFetchApp.fetch(url,opt);
data = response;
return data;
}
Currently, the data returned from display_basic_data() is
"<html><body>You are being redirected.</body></html>".
If I try to change my script so that "followRedirects" is true, the data is equivalent to the HTML of the login page.
I understand I have to play around with cookies in order to 'stay' logged in but I have no idea what to do as the examples online provided to be fruitless for me.
Any help would be much appreciated!!!
You may want to do something like this:
var cookie = response.getAllHeaders()['Set-Cookie'];
//maybe parse cookies here, depends on what cookie is
var headers = {'Cookie':cookie};
var opt2 = {"headers":headers};
var pagedata = UrlFetchApp.fetch("http://www.website.bla/home",opt2);