How to get active users of a specific page by Google analytics API? - real-time

I use rt:activeUsers metric to get active users on website for realtime data.
I want to get active users in real time for a specific page (path or url), not the whole website. Is there a way to implement it? I went through API Explorer but gain no success.

For anybody else looking for this below is an example of how I accomplished this in javascript.
I started with the sample at: https://ga-dev-tools.appspot.com/embed-api/third-party-visualizations/
That sample uses a extension to the embed api to get active users: active-users.js
I didn't know where to get that active-users.js file so I just used the developer tools in Chrome and grabbed it that way. Saved it locally and linked to it in my page. If anyone knows a official location to get that please comment below. Thx.
If you look at the source to that file, I modifed the pollActiveUsers function to add a filters parameter like so:
pollActiveUsers_: function () {
var t = this.get(),
i = 1e3 * (t.pollingInterval || 5);
if (isNaN(i) || i < 5e3)
throw new Error("Frequency must be 5 seconds or more.");
this.polling_ = !0,
gapi.client.analytics.data.realtime.get({
ids: t.ids,
metrics: "rt:activeUsers",
filters: t.filters
}).then(function (t) {
var e = t.result,
s = e.totalResults ? +e.rows[0][0] : 0,
n = this.activeUsers;
this.emit("success", {
activeUsers: this.activeUsers
}),
s != n && (this.activeUsers = s, this.onChange_(s - n)),
1 == this.polling_ && (this.timeout_ = setTimeout(this.pollActiveUsers_.bind(this), i))
}
.bind(this))
},
Now in my page javascript I can call it like so:
var activeUsers = new gapi.analytics.ext.ActiveUsers({
container: 'active-users-container',
pollingInterval: 5,
filters: "rt:pagePath==/somepath/somepage/",
ids: "ga:<yourviewid>"
});
Hope that helps somebody.

While the Real-time API is very limited it does allow you to use filters. Filters are a kind of where clause.
The real-time documentation is also very limited but you can look at the documentation for filters on the core reporting API it works the same
filters=ga:browser%3D~%5EFirefox
I think you should check out the dimension rt:pagePath its probably what you are looking for.

Related

Github API: Get number of contributions on a day by day basis

I want to GET from the Github API, the number of contributions per day. I'm making a webapp that compares the number of github contributions to the number of Dota 2 matches I play.
This picture should explain things more clearly.
http://i.stack.imgur.com/cZ1XK.png
I have scoured the Github API and the internet looking for a simple solution and some of the answers I've seen weren't what I was looking for. This Github API get last year of commit activity blurb is the closest I've gotten to finding a solution, but using it would involve making the API call for ALL repos in my account and concatenating the data into one JSON. If there are no solutions to this I would like to know it so I can abandon ship.
Thanks!
You can use the svg calendar data with the url :
https://github.com/users/USER/contributions?to=2016-12-25
You can set the to query param to your target day and then parse the svg result to get the last data in the output calendar.
For the web integration part, you can use a proxy like urlreq. An example :
const user = 'bertrandmartel';
const day = "2016-12-25";
fetch('https://urlreq.appspot.com/req?method=GET&url=https%3A%2F%2Fgithub.com%2Fusers%2F' + user + '%2Fcontributions%3Fto%3D' + day)
.then(function(response) {
return response.text();
})
.then(function(text) {
xmlDoc = new DOMParser().parseFromString(text, 'text/xml');
var nodes = xmlDoc.getElementsByTagName('rect');
var dayContributions = nodes[nodes.length-1].getAttribute('data-count');
console.log('contributions count for ' + day + ' : ' + dayContributions);
})
.catch(function(error) {
console.log('Request failed', error)
});

How to fix this authorization Google Apps Script suggest box library issue?

I'm trying to add an autocomplete feature (a Ui in a popup window in a spreadsheet) in my Google Spreadsheet using this Google Apps Script suggest box library from Romain Vialard and James Ferreira's book (modified):
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "my_sheet" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1) {
var names = ["Adam", "Peter", "Benjamin", "Ceaser", "Prometheus", "Gandi", "Gotama", "Mickey Mouse"];
var app = UiApp.createApplication();
var suggestBox = SuggestBoxCreator.createSuggestBox(app, 'contactPicker', 200, names);
app.add(suggestBox);
SpreadsheetApp.getActive().show(app);
var dataCell0 = r.offset(0, 1);
var dataCell0 = r.offset(0, 1);
if( dataCell0.getValue() == '' )
otherTestTunction();
}
}
}
But when I start editing column 1 of "my_sheet" and the Ui box appears, this autorization error happens (In my language it says: "you must have permission to perform this action"):
The documentation says that onEdit() trigger "They cannot access any services that require authentication as that user. For example, the Google Translate service is anonymous and can be accessed by the simple triggers. Google Calendar, Gmail, and Sites are not anonymous and the simple triggers cannot access those services."
Since I'm not using ContactsApp, I suppose that the suggest box library require authorization.
How could I set up an installable on Edit trigger that will ask for authorization? (Could you give me some code sample?)
Here is my test spreadsheet: https://docs.google.com/spreadsheet/ccc?key=0AtHEC6UUJ_rsdFBWMkhfWUQ0MEs2ck5OY1BsYjRSLXc&usp=drive_web#gid=0
Out of curiosity about what you suggested on authorizations needed by the library I made a test on a new sheet, the exact code below asks for spreadsheet access, nothing more.
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
var names = ["Adam", "Peter", "Benjamin", "Ceaser", "Prometheus", "Gandi", "Gotama", "Mickey Mouse"];
var app = UiApp.createApplication();
var suggestBox = SuggestBoxCreator.createSuggestBox(app, 'contactPicker', 200, names);
app.add(suggestBox);
SpreadsheetApp.getActive().show(app);
var dataCell0 = r.offset(0, 1);
}
To handle that you just have to ask your user to run one function in your script (no matter what function) and they will get the following popup :
After this initial step your function will work as expected, ie the Ui will show up.
Beside that, I'm not sure I understand what you want to achieve is feasible, the onEdit trigger fires when the edit is done, meaning after you hit ENTER, then the value in the suggestBox is not taken into account... moreover you have to handler in the UI to do anything so I'm still wondering what do you really expect to do with this code ? (what would be ideal is an onClick event in spreadsheetApp but unfortunately it doesn't exist so far...)
But maybe I missed something obvious.
About installable onEdit that you mention also in your post, you should note that it doesn't need to be authorized by the end user since it would run as YOU, the person that creates the trigger and not the user accessing the SS , therefor accessing your own data and not the user's ones... That might be a non negligible restriction (as Zig mentioned in a comment earlier...)

How to get the post of the user using javascript sdk

I am creating my first facebook app using javascript sdk. In that i can able to post to the user's wall using(FB.api('me/feed', 'post', )).
Now what I need is, when the user accessing my app, it has to show (or list) the post of that user. The code is
FB.api('/me/posts', function(response) {
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
alert('The value of post is:'+post);
if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}
}
});
But it is not working. If I remove l=response.length and change the condition as i<5 it is going inside the loop but it gives the value of post is undefined.
I didn't get why it is returning as undefined. It returns same for post.message also.
I am getting the access_token of the user also.
If I want to get the post of my user what code i have to use. Can anyone help me in this.
Thanks in advance
You can use the Facebook Graph API Explorer to better understand what data you will be receiving. https://developers.facebook.com/tools/explorer/
You should have l=response.data.length and var post = response.data[i];. Also, some posts will not have a "message", but will have a "story" instead (mainly posts like "Joe Smith and Tom Someone are now friends."). Make sure you also have the appropriate permissions (e.g. user_status) for the information you're trying to receive.

Facebook Events appear on Google Map

is there a way I can make events on the standard Facebook events app appear on a custom Google Map I've created?
Any tips would be much appreciated.
Given you have the user_events permission, you can access the locations like so:
FB.api("/me/events", function(events) {
if(events.error)
console.error(events);
var map = "http://maps.googleapis.com/maps/api/staticmap?zoom=14&size=512x512&maptype=roadmap&sensor=false";
for(var i = 0; i < events.data.length; i++) {
var point = "&markers=color:blue%7Clabel:S%7C";
point += (events.data[i].venue.latitude + "," + events.data[i].venue.longitude);
map += point;
}
var img = document.createElement("IMG");
img.src = map;
document.body.appendChild(img);
});
I didn't test it, but this should be enough to show an example of how to access the API in the browser and render a map with it's information. This is using Google Maps static API.
I just created a python script, source here.
It queries the given facebook page and it's events and puts the data into a MySQL table. It also contains a Geo-cache library, which combines a local database with the Google Maps Geocoding API, so you can query the longitude and the latitude of the events very fast.

Facebook Graph API - Get ID from Facebook Page URL

I have seen this question but what I want is different.
I want to get the Facebook ID not from a general URL (and therefore conditional if it has Like button or not). I want to get the Facebook ID given a Facebook page using the Graph API.
Notice that Facebook pages can have several formats, such as:
http://www.facebook.com/my_page_name
http://www.facebook.com/pages/my_page_name
http://www.facebook.com/my_page_ID
I know I could do some regex to get either the my_page name or my_page_ID, but I am wondering if any one know if GraphAPI is supporting what I want.
It seems to me that the easiest solution to what you describe is to just get the id/name from the url you have using lastIndexOf("/") (which most languages have an equivalent for) and then get "https://graph.facebook.com/" + id.
The data that this url returns has the id (i.e.: 6708787004) and the username (i.e.: southpark), so regardless of which identifier you use (what you extract from the url using lastIndexOf), you should get the same result.
Edit
This code:
identifier = url.substring(url.lastIndexOf("/"))
graphUrl = "https://graph.facebook.com/" + identifier
urlJsonData = getGraphData(graphUrl)
Should work the same (that is result with the same data) for both:
url = http://www.facebook.com/southpark
And
url = http://www.facebook.com/6708787004
(you'll obviously need to implement the getGraphData method).
Also, the 2nd url form in the question is not a valid url for pages, at least not from my tests, I get:
You may have clicked an expired link or mistyped the address. Some web
addresses are case sensitive.
The answer to the question is posted above but the method shown below works fine we do not have to perform the regex on the facebook page urls
I got the answer by this method
FB.api('/any_fb_page_url', function(response){
console.log(response);
});
any_fb_page_url can be any of the following types
https://www.facebook.com/my_page_name
https://www.facebook.com/pages/my_page_name
https://www.facebook.com/my_page_ID
This are also listed in question above
This code is tested on JS console available on Facebook Developers site tools
You can get the page id by using the below api
https://graph.facebook.com/v2.7/smhackapp?fields=id,name,fan_count,picture,is_verified&access_token=access_token&format=json
Reference image
This answer is updated and checked in 2019:
and it is very simple because you do not need to extract anything from the link. for examples:
https://www.facebook.com/pg/Vaireo-Shop-2138395226250622/about/
https://www.facebook.com/withminta
https://www.facebook.com/2138395226250622
https://graph.facebook.com/?id=link&access_token=xxxxxxxx
response:
{
"name": "Vaireo Shop",
"id": "2138395226250622"
}
full nodeJS answer:
async function getBusinessFromFBByPageURL(pageURL: string) {
const accessToken = process.env.fb_app_access_token;
const graphUrl = `https://graph.facebook.com/?id=${pageURL}? access_token=${accessToken}`;
const fbGraphResponse = await Axios.get(graphUrl);
<?php
function getFacebookId($url) {
$id = substr(strrchr($url,'/'),1);
$json = file_get_contents('http://graph.facebook.com/'.$id);
$json = json_decode($json);
return $json->id;
}
echo getFacebookId($_GET['url']);
?>
Thats a PHP example of how to get the ID.
As of Nov 26 2021 none of these solutions work.
Facebook has locked down the API so you need an App Review.
https://developers.facebook.com/docs/pages/overview/permissions-features#features
This answer takes into account that a URL can end with a trailing slash, something that Facebook event pages seem to have in their URLs now.
function getId(url) {
var path = new URL(url).pathname;
var parts = path.split('/');
parts = parts.filter(function(part) {
return part.length !== 0;
});
return parts[parts.length - 1];
}
You can Use Requests and re Modules in python
Code:
import requests,re
profile_url = "https://www.facebook.com/alanwalker97"
idre = re.complie('"entity_id":"([0-9]+)"')
con = requests.get(profile_url).content
id = idre.findall(con)
print("\n[*] ID: "+id[0])
Output:
[*] ID: 100001013078780
Perhaps you can look through the https://developers.facebook.com/docs/reference/api/#searching docs: search against a couple of types and if you find what you're looking for go from there.