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

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();
}
}
}

Related

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();
}

Getting Facebook Interests graph api call

I am trying to get the users liked Facebook pages, here is my code:
exports.checkUserInterests = function (fbaccountID,fbModule) {
var facebookModule = fbModule;
;
//code to get the list of facebook likes for any given user
facebookModule.requestWithGraphPath('me/interests', {}, 'GET', function(e) {
if (e.success) {
alert(e.result);
} else if (e.error) {
alert(e.error);
} else {
alert('Unknown response');
}
});
};
My Permissions is set as following:
//set permissions for graph api
var permissions = ['user_friends', 'user_interests', 'user_birthday', 'user_photos', 'basic_info'];
I an returning an empty json array, is my request correct?
Thanks
I use a different call to get the Facebook Likes of a user, maybe thats the problem.
For example, if I want to know if the user likes a page with id: xxxxx, I do a GET call to "me/likes/xxxxxx" and see if the result is true.
For this to work, you should have the permissions to user_likes.

posts in group feed have unavailable content

I am an admin of a private group in facebook and I would like to use facebook API to scrap all group posts.
I used graph api explorer to generate an access token with read_stream, friends_group and user_groups permissions.
When I access the group post with https://graph.facebook.com/GROUP_ID/feed?access_token=TOKEN I get a data array with each post but the caption element has the value
"Attachment UnavailableThis attachment may have been removed or the person who shared it may not have permission to share it with you." and all the other fields such as link, message, etc ... are not present.
If I open the facebook group using the browser I can see all posts.
Am I missing something here ?
This issue appears to have been corrected. I can access all the Group content for my private group as long as I have a valid Auth Token.
Below is the code where I fetch the posts of a group in a JSON Object. This JSON object contains a JSON Array of "data".
This further contains a separate JSON array for messages (or status of the post).
GraphRequest.newGraphPathRequest(
accessToken, "/id/posts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
try {
graphResponse.getRawResponse();
m=graphResponse.getJSONObject();
JSONArray n=m.getJSONArray("data");
messages=new String[n.length()];
for(int i=0;i<n.length();i++) {
JSONObject a = n.getJSONObject(i);
messages[i]=a.optString("message");
}
list.setAdapter(new ArrayAdapter<String> (fb.this,android.R.layout.simple_list_item_1,messages));
} catch (Exception e) {
Toast.makeText(fb.this, "error is: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
}).executeAsync();

How to post image on facebook fan page using C# facebook sdk on codeplex

Currently I'm working on my HTML 5 ASP.Net Application,
Which has requirement of Graffiti Wall, When user draw something on my Wall(means on my HTML 5 Canvas element), and Press Share Button on my Page, at that time the whole picture should need to be post on one of the Facebook Page.
Now my question is that is this thing possible using C# facebook sdk by codeplex ?
if its possible, than how to post image on facebook fan page using this SDK??
Where can I get the good resource the implement this kind of functionality or similar code.
I've check the all examples given by them, there is no any example which post on the facebook fan page.
Or even other library that can implement this kind of functionality.
I've check this library, and see that it has FacebookClient,ExpandoObject, FacebookMediaObject kind of classes, but how to and where to use this classes,where are the description and sample code.
Thanks,
Jigar Shah
you can post to others wall using "{id}/feed"
if you want to post image/video on wall. Try downloading the samples from nuget.
Install-Package Facebook.Sample
Here is how to do using the graph api.
public static string UploadPictureToWall(string id, string accessToken, string filePath)
{
var mediaObject = new FacebookMediaObject
{
FileName = System.IO.Path.GetFileName(filePath),
ContentType = "image/jpeg"
};
mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath));
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Post(id + "/photos", new Dictionary<string, object>
{
{ "source", mediaObject },
{ "message","photo" }
});
var postId = (string)result["id"];
Console.WriteLine("Post Id: {0}", postId);
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
return postId;
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}

Retrieve Facebook Post Comments Using Graph API

I tried to get Facebook comments using:
http://graph.facebook.com/[post_id]/comments
It results only 2 of 15 comments, and without count info.
{
"data": [
{
"id": "[post_id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T02:36:23+0000"
},
{
"id": "[id]",
"from": {
"name": "[name]",
"id": "[id]"
},
"message": "[message]",
"created_time": "2011-01-23T05:16:56+0000"
}
]
}
Anyone know why only 2 comments?
Also, I want to retrieve comments (default number) or retrieve comments with my limit number, and get its comments count. Any idea? (Please use Graph API).
You need to call it from a secure request https and provide an access_token:
https://graph.facebook.com/19292868552_118464504835613/comments?access_token=XXX
EDIT:
Added the object from the post document. try clicking the comments connection and then remove the access_token and try and see the difference.
In order to get the Like count and the comment count then you need to use a combination of the PostOwnerID and PostID not just the PostID
So for your example it would be:
https://graph.facebook.com/153125724720582_184234384932460/comments
Again, as mentioned in some of the other answers you need to use the https method along with an auth_token
I experienced the same problem with comments. The issue was that I was using an access token for a test user. Because test users don't have access to other FB users information, only the comments from pages were shown.
There is a word JUGAAR in Urdu that means, finding a way out, just to get the job done. So for like purpose I made this JUGAAR, I hope it helps.
$contents = file_get_contents("http://graph.facebook.com/" . $_GET['id'] . "/likes");
if (substr_count($contents, 'name')>0) {
echo substr_count($contents, 'name') . " people like this album";
}
By the way I am also new to this Fb stuff, I am looking for help to post comments. When I try to use graph.api./id/comments?access_token=sdfsfsdf&message="D" it still returns comments for the id instead of posting.
As a sanity check, do you have "read_stream" permission? I can see the full comments with my access token that uses "read_stream". As mentioned by other people, you have to use https and access token as well...
Try to authenticate via App Login (http://developers.facebook.com/docs/authentication) and then to call GraphAPI with access_token prarameter.
You can do something like this to avoid the whole count of comments issues:
Get the object's (a post is considered an object in the Graph API) ID-as I understand from your question, you already have it?
Create a Comments Social Plugin with this ID, and get the code for it.
Embed the code in your site.
This will result in all the comments for this object.
To get the count of comments per object, you can execute an fql query, something like this:
SELECT comments FROM stream WHERE post_id = [yourpostid]
This will return in the comments array under the count parameter the number of counts for this object.
SELECT comments FROM stream WHERE post_id = [yourpostid] shall not work in this case ..
the id which is returned after making a graph call successfully to post on a user's wall (using access_token of an application ) is of the form abcdef_qwerty ( underscore seperated id )
where as the post id which is mapped in the post_id of the comments table is of the form "lmnop" ..
to get the counts of like and comments on this post id of form "abcdef_qwerty" making a graph call withh app generated access token seems to be the only solution ..
something like:
https://graph.facebook.com/100002619172565_117323155031656?access_token=xxxxxxxxxxxxx
After Successfully Login call this method facebookComments()
parameters.putString("fields", "message"); .............// Its Important
AccessToken accessToken = AccessToken.getCurrentAccessToken();
public void facebookComments() {
try {
getFriends(accessToken, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("keshav", "one" + response);
CommonMethod.showAlert("res --> " + response, MainActivity.this);
}
}
);
} catch (Exception e) {
CommonMethod.showAlert("Exception is -> " + e, MainActivity.this);
}
}
public void getFriends(AccessToken token, GraphRequest.Callback callback)
{
// TODO Comments Working but id return only
GraphRequest requestt = new GraphRequest(token, "744511125731315_751199848395776/comments",
null, HttpMethod.GET, callback);
Bundle parameters = new Bundle();
parameters.putString("fields", "id"); // todo in use imp
parameters.putString("fields", "name"); // todo in use imp
parameters.putString("fields", "from"); // todo in use imp
parameters.putString("fields", "message"); // todo in use imp
requestt.setParameters(parameters);
requestt.executeAsync();
}
It results only 2 of 15 comments
Add a limit parameter to the URL:
http://graph.facebook.com/[post_id]/comments?limit=1000&access_token=XXX
This should show all the comments.