Facebook Graph API - Finding a users top friends - facebook

I am writing a android app that will pull in a list of all the users friends so they can tag them in the photo but displaying a large box of the friends with their photo instead of a list. Because some people have 500+ friends, we all know their are only a handful (maybe 50) that are friends they actively communicate on Facebook by comments or being tagged in photos. I would like to be able to just pull their top xxx friends as it seems Facebook does this same thing on their site, but I just cant find anything in the Graph API to do this task.
Anyone have any pointers?

The other way of doing it is, make a Graph API request for the status messages posted by the user, the friends who have commented or liked his status are the ones with whom he/she interacts the most, doing this is pretty simple, you can use this:
$statuses = $facebook->api('/me/statuses');
foreach($statuses['data'] as $status){
// processing likes array for calculating fanbase.
foreach($status['likes']['data'] as $likesData){
$frid = $likesData['id'];
$frname = $likesData['name'];
$friendArray[$frid] = $frname;
}
foreach($status['comments']['data'] as $comArray){
// processing comments array for calculating fanbase
$frid = $comArray['from']['id'];
$frname = $comArray['from']['name'];
}
}
keep counters as per your choice, and it will be done.

I wanted to do this without requiring additional/extended permissions. I found a fairly decent approximation for my needs was the mutual_friend_count field in the user FQL table.
So I used:
$params = array('method' => 'fql.query',
'query' => 'SELECT uid, pic_square, name
FROM user
WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())
ORDER BY mutual_friend_count DESC
And then just fire that off using the PHP SDK
$friend_array = $facebook->api($params);

I've ran into this same issue in a web app I'm working on, and open-sourced the code I've used, albeit in Ruby:
https://github.com/mikejarema/facebook-friend-rank
This is actually a web service which takes an active access token & user id and (assuming a read_stream permission has been granted) returns a hash of ids to counts which can be used for sorting within your android app.
I suppose since you're running on a smartphone, this let's you offload a series of calls and any call latency to a server somewhere which is running code optimized specifically for the friend ranking task.
In particular, the ranking algorithm looks at a user's 500 most recent interactions (activity feed) and tallies up the frequency of all friends appearing there. The result gives a reasonable ordering of friends, best to worst, and it also works on subsets of friends (eg. sorting mutual friends).
There's lots of room for exploring photo tags, mutual friend counts, and also looking for the type of interactions (eg. a checkin with a friend is probably a better measure of closeness than a like on their status). The project may evolve to encompass some of these considerations.
Here's a sample app using this approach and Friend Rank on the backend, inspect the network calls to see what the API looks like:
http://facebook-friend-rank.herokuapp.com/demo/index.html

If you watch the network traffic from Facebook's iPhone app, you can see they make this FQL call to get the users top 10 friends they communicate most with:
SELECT uid2, communication_rank
FROM friend where uid1 = me()
ORDER BY communication_rank DESC LIMIT 10
Unfortunately this is not available to applications by default. You would need to contact a Facebook engineer to get this field enabled for your application.

I recommend you the following class:
https://github.com/gajus/facebook-friend-rank
It give your friends a score based on user interaction:
'feed_like'
'feed_comment'
'feed_addressed'
'photo_tagged_friend_by_user'
'photo_tagged_user_by_friend'
'photo_like'
'photo_comment'
'friend_mutual'
'inbox_in_conversation'
'inbox_chat'
then it sort the list by score desc.
Hope it helps.

I can think of two direct ways to get a user's "top friends." The first does not require any extended permissions, rather just a valid access token (which as an app owner, you'll have). You make an API call to get the user's feed, which is a connection to the user node.
This call will that user's 25 most recent posts. With any luck, at least some of the items in JSON array returned from this call will be posts from that user's friends. How will know? Well each post comprising the feed, will have an unique id associated with it--whether an Application or FB User is the source of the Post--and each one of those FB ids can be compared against the user's friend list.
The idea of course is that any friends whose posts appear in the last 25 posts of the user's feed, are closer friends than otherwise.
The second technique is to make a call to the Graph API requesting the friendslists connection to the user node. This call requires the *read_friendlists* permission. The name a user gives to a given list is often strongly probative of the importance of the friends comprising that list (e.g., *best_friends*, or whatever); in other words, one or a combination of a couple of those lists will likely give you that user's top friends.

Related

Facebook get/querying all wall posts (access tokens return completely different values)

I've been trying to query what people have posted on my wall as a quick metric of closeness. I've tried both FQL and the Graph API to make these queries without a problem...
FQL:
SELECT actor_id FROM stream WHERE source_id = me() AND message != "" LIMIT 50
Graph:
FB.api('/me/feed?fields=from&limit=50', function(feedresponse) { //do stuff });
Testing these in the Graph Explorer when the application is set to "Graph API Explorer" returns the values I want - my own and other's posts on my wall.
However when the application is changed to my own application, "Fingerprint", the values include my likes, my recent friendship notifications, etc... information I don't want returned and that completely pollutes the query.
I've still gotten the correct results by passing the Graph API Access Token like so:
var access_token = "CAACEdEose0cBALLruchzIKJ1ewgvcjpPJmo1amJwbMHGYyuk544om8hDILt0ZBXiUAriiNI7VY2g1OOwlEgV4bVyCWZACOf2djD1rYBTIwxBnmseNHUm6qybvus23F4AShctQl3wu0rpPS5ZBh68ypVoDMgyyXEGnu6uXBbzOJ7Tx43m2xHsseo1oiU7A80oelxphhidgZDZD";
FB.api('/me/feed?fields=from&limit=50', { access_token : access_token}, ...
Though it works - it definitely doesn't seem like the right way. Can anyone explain why the results are different and how I can get my feed without the other bullshit FB sends me when I'm using the User Access Token with my App.

How to filter user's news feed to posts/actions from a specific app in Graph API

I have a Facebook app and I want to filter user's news feed to get latest posts/actions that was posted using my app, in Graph API.
I've found this: How to get activity from my app with Facebook Graph API?
This one is okay for getting actions/posts by a specific friend (or the user itself), what I need is almost the same, with the difference that I need this "stream" by all friends of the user that use my app, not a single user.
Then I've found this: Facebook graph api : how to filter app feeds. For this one, the example in the question itself returns empty data for me (with the appropriate access token with read_stream permission). The only answer suggests to use FQL. I've tried SELECT post_id, message, comments, likes FROM stream WHERE app_id = MY_APP_ID and I got this error:
{
"error": {
"message": "Your statement is not indexable. The WHERE clause must contain an
indexable column. Such columns are marked with * in the tables linked from
http://developers.facebook.com/docs/reference/fql ",
"type": "NoIndexFunctionException",
"code": 604
}
}
How do I retrieve the list of all the last (say 100) posts from a specific app by the user and their friends, from the user's scope?
With all FQL queries, your WHERE clause must include at least one indexable field (those are marked with a star next to the field name in the docs) – for performance reasons.
So for the stream table you have a choice between source_id (id of the user whose wall the post is on) or filter_key. You can read the valid filter keys from the stream_filter table – but every user has the filter key nf for what shows up in their news feed. (post_id is also indexable, but of no use for us here.)
So you could try filtering with WHERE filter_key = 'nf' AND app_id = 'YOUR_APP_ID' – that should give you the posts that your active user is able to see in their feed that where made via your app.
You could also try with source_id, filtering that to either being equal to me() (your current user in FQL), or it being in the list of your friends (whose ids you can get from the friend table, again using me(), as a sub-query) - so like this,
… WHERE (source_id = me() OR source_id IN (SELECT uid1 FROM friend WHERE uid2 = me())) AND app_id = 'YOUR_APP_ID'
– but I think that will have less good performance, so I’d try with filter key first and see if that gets you the posts you want.
EDIT: So, as the questioner found out, using /me/home?filter=app_MY_APP_ID works apparently better, and is also easier. Whoever else might need this, they should use this version, since it is more reliable – FQL often gives less results then one would expect.

Facebook graph API 'friends' request now only returning 25 friends per page? What's going on?

My application(game) has been running on Facebook for some time. I start by requesting a friends list via the graph API call: my-uid/friends
asking for user name and profile pic.
Normally I get back a list of all my friends up to a few thousand, until it starts putting friends on to the next page. Which is nice as most of my users get friends in 1 call.
Suddenly however, and with no changes to the app. about 40 minutes ago (18:40 Tuesday (PDT) - 2nd May 2012) I started getting responses with only 25 friends per 'page'!
I can still get my whole friends list using multiple calls, but the game is not currently set up to do that properly. Can anyone tell me why the sudden change? Anyone else seen similar problems and how do I get the list to give me up to 5000 friends per page like it used to.
Reproducible using the Graph API Explorer
I don't know what else to tell you; perhaps the default number returned has changed, but when I try, a call to /me/friends?limit=5000 returns the full list for me (but my friends list is >500 and < 1000 , so maybe it cuts off somewhere along the way)
(Side note: the average number of friends has been found to be ~190 so presumably most users will have less than 500 anyway, and having to page above 500 would be an edge case
In SDK 4.7 you need to pass in a bundle with the number of friends you want to return, I have set it to 5000 as this is the maximum number of friends you can have on Facebook.
You also need to set up your app as a game in the facebook dev console and use invitable friends to get a full friends list
Create your bundle
Bundle bundle = new Bundle();
Add params to your bundle
bundle.putInt("limit", 5000);
Then pass it in to your GraphRequest
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/invitable_friends",
bundle,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
//Do something with the response
}
}
).executeAsync();
It seems that facebook changed its limit to 25 results in other api calls too (feed, posts, friends, etc), if you request friends without parameters the JSON response shows the following:
"paging": {
"next": "https://graph.facebook.com/USER_ID/friends?format=json&limit=25&offset=25&__after_id=LAST_ID"
}
Anyway you could/should always set limit & offset parameters to prevent this kind of things, limit = 0 will return all your friends list.
https://graph.facebook.com/USER_ID/friends?limit=0
If you are only requesting friends from a normal user the maximum number allowed is 5,000 so the limit should could be either 0 or 5,000 if you are requesting info from a facebook page or other kind of api calls like posts or feed this limit could increase or decrease.
(Update) Facebook fixed this bug so setting limit to 0 returns 0 friends, you should set a positive limit, thanks Dinuz
I think the best thing you can do is to add limit=5000 parameter as Igy says.
However I posted a bug report since this change wasn't noticed or described in the document.
The number of results returned from the /v2.2/me/friends endpoint now defaults to 25.
Friend list now only returns friends who also use your app: The list of friends returned via the /me/friends endpoint is now limited to the list of friends that have authorized your app.
See Facebook changes
Facebook API change log
If you are using GraphRequest() (e.g. in React Native), you can put it directly in the string field, like so :
new GraphRequest(
'/me',
{
accessToken,
parameters: {
fields: {
string: 'id,email,first_name,last_name,friends.limit(5000)'
}
}
...

What function in Social Graph loads mutual friends so fast?

I am making a Facebook application for which I require the mutual friends of the logged in user. The Old API friends.getMutualFriends does the work but it is very slow. I was wondering if there is any other way of getting the list of mutual friends.
Moreover, applications like SocialGraph load very fast, so what functions are they using to get hold of the mutual friends so quickly?
I found the solution :)
With friends.getMutualFriends, it takes n^3 API which is a huge number. I tried areFriends as well which was no better. So I fetched the data via FQL query as follows:
//Create Query
$params = array(
'method' => 'fql.query',
'query' => " SELECT uid1, uid2 FROM friend
WHERE uid1 IN
(SELECT uid2 FROM friend WHERE uid1= $match)
AND uid2 IN
(SELECT uid2 FROM friend WHERE uid1= $match)",
);
//Run Query
$result = $facebook->api($params);
It takes less than a second to get the mutual friends !
If you are concerned about speed, I would suggest calling the information once and finding a way to cache the data. Facebook now provides you with the ability to do so "legally". You may use memcached for this sort of thing or save it temporarily in a database.
As of September 2011, there is a new api call for this:
This week we added a connection for the User object that allows you to
get the list of mutual friends between two users. To use it, just get
an access token for the current user and issue a GET request to:
https://graph.facebook.com/me/mutualfriends/FRIEND_ID
Platform Updates: Operation Developer Love

Facebook Graph API - get friends info

I'm trying to figure out how to get users friends information using either Graph API or FQL
Just for testing I would like to get my friends education_histroy.
To do that I created a test app, requested extended permissions using
scope=offline_access,manage_friendlists,friends_work_history,
friends_education_history,friends_about_me
and got access token to play with the API.
It works great when I query for current user using /me. But it returns nothing for my friends.
I was assuming that if I request, let's say friends_work_history, that extra field (work_history) will appear inside friend's object, when I query by friend's id:
https://graph.facebook.com/FRIEND_ID&access_token=TOKEN
But all I see is basic info about that user (friend).
Then I tried to request that field specifically:
https://graph.facebook.com/FRIEND_ID?fields=work&access_token=TOKEN
With no luck again. Returns just friend's id..
I tried to access that information with FQL:
https://api.facebook.com/method/fql.query?query=select+work_history+from+user+where+uid+in+(FRIEND_ID)&access_token=TOKEN
Returns work_history = TRUE instead of array. And that friend definitely has work history specified.
Can someone help me to understand how to get friends info using my app and extended permissions?
Graph API is the smart choice in most cases. To retrieve your friend information you need to collect some extended permissions from the user first. Then you can retrieve a lot more information other than the basic ones.
Following is a list of extended permissions related to friends different kind of information
friends_about_me
friends_activities
friends_birthday
friends_checkins
friends_education_history
friends_events
friends_games_activity
friends_groups
friends_hometown
friends_interests
friends_likes
friends_location
friends_notes
friends_online_presence
friends_photo_video_tags
friends_photos
friends_relationship_details
friends_relationships
friends_religion_politics
friends_status
friends_subscriptions
friends_videos
friends_website
friends_work_history
Hope it helps :)
I've been wrestling with this all day myself and I believe I have figured it out, nowhere in facebook documentation (that I have found) is this clear. And I don't believe the other answers actually answered your question, it looks like you requested permissions correctly. Anyway, to request the information you are looking for, ping the api like this:
https://graph.facebook.com/userid/friends?fields=work&access_token=ACCESSTOKENHERE
This will return you all the friends' info in one long JSON response.
It is a little confusing because the permissions you are asking for are not the same thing you need to query the API.
The query above will return the friends' ids with work history. You can add commas to the fields parameter to include additional info like name, but then the API calls/responses end up taking a long time.
http://developers.facebook.com/docs/reference/api/user/
you can get all the fields mentioned here .To get work you need to have user_work_history or friends_work_history permission
in the link it is mentioned what permissions to obtain before you get the info and another thing that user has to allow your application,this will make your app to get the informations.
From this answer to another question: a call to 'me/friends?fields=work' worked for me!
I'd suggest that you go to http://developers.facebook.com/docs/reference/api/user/ like most of the others are suggesting but as a general tip, use the friends_education_history as a way to get the friend's history.
P.S: Minor spelling error in your original question that should be edited. "education_histroy." = education_history
in the second line of your main paragraph.
You can use this code you will get name, profile picture, ID of your friends.
FB.api('/me/taggable_friends', function(response) {
for (var i = 0; i < friend_data.length; i++) {
results += ''+friend_data[i].name;
}
});
Before that in your developer account created app-> go to tools and support->graph API explorer-> click Get Token. In that window click user_tagged_places and click Get Access Token. You will get your friends list.