how to get friend's likes from facebook - facebook

I am retrieving the complete list of a friend's likes(the list of pages that the user likes) using the code bellow:
Uri ex_a = new System.Uri("https://graph.facebook.com/" + friend_id + "/likes? access_token=" + token);
WebClient WC_a = new WebClient();
WC_a.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(list_likes);
WC_a.DownloadStringAsync(ex_a);
private void list_likes(object ob, DownloadStringCompletedEventArgs e)
{
JsonObject jo = new JsonObject(e.Result);
JsonArray dataArray = (JsonArray)jo["data"];
if (dataArray.ToString().Length > 2)
{
foreach (JsonObject account in dataArray)
{
list_of_likes.Add(new class_of_likes("http://graph.facebook.com/" + (string)account["id"] + "/picture?type=small", (string)account["name"]));
}
}
}
However, in October 2013, this approach will only retrieve 25 results/request.
I need to know how to create a loop to get the remaining results because facebook uses pagination like:
"paging": {
"next": "https://graph.facebook.com/user_id/likes?limit=25&offset=25&__after_id=last_page_id"
Thank you.

Get pagination section, and parse it to get next_page value, then send a query for it. There's no automatic process or get all method , otherwise spams/bots would be the happiest creature in this world.

Related

Facebook api not returning friends contact info

In my contacts manager app, I need to have an option to import contacts from facebook. Im using hello.js This is the function
function getFriends(network, path){
var list = document.getElementById('list');
list.innerHTML = '';
// login
hello.login( network, {scope:'friends'}, function(auth){
if(!auth||auth.error){
console.log("Signin aborted");
return;
}
// Get the friends
// using path, me/friends or me/contacts
hello( network ).api( path , function responseHandler(r){
for(var i=0;i<r.data.length;i++){
var o = r.data[i];
var li = document.createElement('li');
var ph = "";
if(o.gd$phoneNumber != undefined)
{
for (var j = 0; j <= o.gd$phoneNumber.length; j++ ) {
if(o.gd$phoneNumber[j] != undefined)
{
//console.log(o.gd$phoneNumber[j].$t);
ph += o.gd$phoneNumber[j].$t +'<br>';
}
};
}
li.innerHTML = o.name + (o.thumbnail?" <img src="+o.thumbnail+" />":'') +' Phone : '+ph;
list.appendChild(li);
};
});
});
}
The function is invoked by getFriends('facebook','me/friends') .This only returns the count of friends like this
{
"data": [
],
"summary": {
"total_count": 1076
}
}
but by using getFriends('facebook','me/taggable_friends'), I'm getting the name and image of the friends but not any email id or contact number.
Can anyone figure out the issue ?
/me/taggable_friends is ONLY for getting tagging tokens (you don´t get User IDs), and ONLY for tagging your friends (in status posts, for example).
/me/friends only returns friends who authorized your App too, that´s intentional. Users who don´t use your App don´t show up for privacy reasons.
That being said, even if you would be able to get ALL friends, you can´t get any details like email and especially not a contact number. You can´t even get the phone number from the authorized User.
Detailed information can be found in the changelog: https://developers.facebook.com/docs/apps/changelog

How to get other user's mention timeline of twitter with twitter4j api?

I'm struggling to get other user's mention timeline with twitter4j api. I could figure out that it's possible only to get other user's UserTimeline. It seems that there is no way to get other user's mention timeline
(I found that here - lookup "Interface TimelinesResources")
Is there way to get other user's mention timeline ???
You can get the MentionsTimeline using getMentionsTimeline() method of TimelineResources as a link you mentioned with some limitations of number of tweets returned.
Find below example of the example which will give you MentionsTimeline.
Twitter twitter = new TwitterFactory().getInstance();
try {
User user = twitter.verifyCredentials();
List<Status> statuses = twitter.getMentionsTimeline();
System.out.println("Showing #" + user.getScreenName() + "'s mentions.");
for (Status status : statuses) {
System.out.println("#" + status.getUser().getScreenName() + " - " + status.getText());
}
} catch (TwitterException te) {
te.printStackTrace();
System.out.println("Failed to get timeline: " + te.getMessage());
System.exit(-1);
}
You can use getUserTimeline() method of Twitter class.
References:
1. http://twitter4j.org/javadoc/twitter4j/Twitter.html
2. http://twitter4j.org/javadoc/twitter4j/Status.html
The Twitter API doesn't have an endpoint for viewing other users mentions (the statuses/mentions_timeline API returns only the mentions of the authenticated user).
You should use the search API, using as the query string the #screen_name of the user you want to get the mentions. Please note that the Twitter Search API may not return all mentions for a given user (it says that "the Search API is focused on relevance and not completeness").
So, using Twitter4j, you can get #NASA mentions using the following
Twitter twitter = new TwitterFactory().getInstance();
try {
Query query = new Query("#NASA");
QueryResult result;
do {
result = twitter.search(query);
List<Status> tweets = result.getTweets();
for (Status tweet : tweets) {
System.out.println("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
}
} while ((query = result.nextQuery()) != null);
System.exit(0);
} catch (TwitterException te) {
te.printStackTrace();
}

Get the number of likes of a post on an FB page using RestFB API

I am trying to retrieve all the posts, the number of likes on each post, the comments on each post and the number of likes of each comment from a particular FB page (https://www.facebook.com/JnuConfessions). I am using RestFB to do this.
While I have managed to get the post content, comments content and comments likes correctly, I am not able to get the number of likes of any post. I use the following code
Page page = facebookClient.fetchObject("jnuConfessions", Page.class);
Connection<Post> myPagePost = facebookClient.fetchConnection(page.getId() + "/posts", Post.class);
for (List<Post> myFeedConnectionPage : myPagePost) {
for (Post post : myFeedConnectionPage) {
System.out.println ("Number of likes: " + post.getLikesCount());
}
}
However for every post, I just get a null value instead of the correct number of likes.
Is there some way to get the number of likes of each post correctly?
Try this, You should pass the parameters whichever you need.
for (List<Post> myFeedConnectionPage : myFeed) {
for (Post post : myFeedConnectionPage) {
//JSONObject userPosts = new JSONObject();
try {
post = facebookClient
.fetchObject(
post.getId(),
Post.class,
Parameter
.with("fields",
"from,actions,message,story,to,likes.limit(0).summary(true),comments.limit(0).summary(true),shares.limit(0).summary(true)"));
System.out.println ("Number of likes: " + post.getLikesCount());
} catch (Exception e) {
e.printStackTrace();
}
}
}

How can i post the feed to facebook page as admin using c# sdk?

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}
1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.

How to retrieve a particular Facebook post using post_id

In my application, there is a case where I want to retrieve the content (message) of a particular Facebook post. I am able to get the postid id for that particular post, but I am not able to get the content associated with that id. I could not find any FQL query to get the post message with post_id or a Graph API URL.
I have this URL to get the all posts, ../100005002784039/posts?fields=id,name,message, but I want only a particular message of the post while passing the post id.
How can I achieve this?
Thanks to sahil, my URL is like this:
https://graph.facebook.com/"+PostId()+"?access_token=Token);
Code
URL fbmsg = new URL("https://graph.facebook.com/"+trace.getFbPostId()+"?access_token="+TOKEN+"");
URLConnection yc = fbmsg.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
String s = "";
while ( (inputLine = in.readLine()) != null)
System.out.println(inputLine);
Log.d(TAG, "getPostId trace getFbPostId " + inputLine);
s = s + inputLine + "n";
Log.d(TAG, "getPostId trace getFbPostId " + s);
in.close();
System.out.println(s);
Simply make the following query to the API-
/POST_ID