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.
Related
Question
Is it possible to get a permalink, which can be embedded successfully, to a facebook post from a link that follows the form https://www.facebook.com/{REFERENCED_PAGE_ID}/posts/{SOME_OTHER_ID} instead of the typical form https://www.facebook.com/{POSTER_ID}/posts/{POST_ID}? If so, how can it be done?
Background
Given a link such as the following (which cannot be embedded properly)
https://www.facebook.com/209447300380/posts/10153494075900381
I need to be able to programmatically produce the following link which can be embedded
https://www.facebook.com/photo.php?fbid=10151668558417282&set=a.244117472281.146601.8128837281&type=1
Normally the solution would be to query facebook with the statement
select permalink from stream where post_id='209447300380_10153494075900381'
However this query does not produce any data for me. My suspicion is that there is a problem with the original link: 209447300380 is not the ID of the posting page, but rather, the ID of the page being referenced. In cases where 209447300380 is the ID of the posting page, I can get a permalink from Facebook without any problems.
Miscellaneous Details
I am using an application access token with the read_stream permission. It may be the case that I do not have sufficient permissions; I'm not sure.
I'm also having issues getting a permalink for user posts (posts not posted by official 'pages'). I don't know if this is relevant.
It looks like a bug. Getting the permalink using FQL doesn't work whereas it works with Graph API. You should use Graph API then:
https://graph.facebook.com/209447300380_10153494075900381?fields=link&access_token=YOUR_TOKEN
Result:
{
"link": "https://www.facebook.com/photo.php?fbid=10151668558417282&set=a.244117472281.146601.8128837281&type=1",
"id": "209447300380_10153494075900381",
"created_time": "2013-11-08T18:08:46+0000"
}
Using the Graph API won't do too much changes in your app, I guess.
Unfortunately we've found the most reliable way to figure out the embeddable link is simply to try to access the starting link, and then follow where it redirects to. If the redirects end at facebook.com/login, then it isn't embeddable (to the public, anyway). Otherwise, the embeddable link should eventually be reached.
C# Sample:
public static string GetPermalink (string url) {
HttpWebRequest request;
HttpWebResponse response;
request = (HttpWebRequest) WebRequest.Create (url);
request.Method = "HEAD";
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.16 (KHTML, like Gecko) Chrome/24.0.1304.0 Safari/537.16";
try { response = request.GetResponse () as HttpWebResponse; }
catch (WebException ex) { response = ex.Response as HttpWebResponse; }
using (response) {
string responseUri = null == response.ResponseUri ? null : response.ResponseUri.AbsoluteUri;
if (HttpStatusCode.OK == response.StatusCode) {
/* Ended at a login page. This post isn't viewable to the public. */
if (responseUri.StartsWith (#"https://www.facebook.com/login.php?") ||
responseUri.StartsWith (#"http://www.facebook.com/login.php?")) {
return null;
}
/* Found a public post. */
else return responseUri;
}
else return null;
}
}
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.
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();
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.
I'd like to know if there is a simple way of retrieving the Cover photo from a user in my application, via the Facebook php sdk.
I managed to retrieve the cover photo id of the album of the cover photo album, but my solution only works partially. (As you can see, it's not efficient, and If more albums will be added, and moved to other pages, thus this will not work).
$albums = $facebook->api('/me/albums','GET');
for($i = 0;$i<count($albums['data']);$i++){
for($j = 0;$j<count($albums['data'][$i]);$j++){
if($albums['data'][$i]['name'] == "Cover Photos"){
echo $facebook->api('/me/albums/'.$albums['data'][$i]['cover_photo'],'GET');
}
}
}
Facebook seems to have added the Cover field to User Object recently
https://graph.facebook.com/facebookuserid?fields=cover will give you the user cover pic Details
Facebook Doc Link : http://developers.facebook.com/docs/reference/api/user/
I think the easiest is to use the graph api:
http://graph.facebook.com/{user_id or page_id}?fields=cover
and parse the returned JSON.
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}
Facebook has a really poor and outdated documentation...
At the moment there isn't a proper way to do this via Graph API, but with FQL it is possible.
SELECT pic_cover FROM user WHERE uid='yourUserId'
The field pic_cover isn't documented but available.
The response should look like this:
[
{
"pic_cover": {
"cover_id": someId,
"source": "someUrl",
"offset_y": someOffset
}
}
]
The latest versions of Graph API (2.4 is current at the time of writing) support 'picture' field that returns user's profile picture. It's worth checking.
/<user-id>?fields=id,name,picture
I think it is better to ask type of album then name.
$albums = $facebook->api("/me/albums");
$album_id = "";
foreach($albums["data"] as $item){
//echo $item["id"]." - ".$item["name"]." - ".$item["type"]." - ".$item["cover_photo"]."<br/>";
if($item["type"] == "profile"){
$album_id = $item["id"];
$profile_picture_id = $item["cover_photo"];
break;
}
}
Looks like at this stage, pending updated documentation from facebook, that your method is the only "sure fire" way to retrieve the cover of a users timeline.
If you find this method to be slow or inefficient - maybe you could try running it as a cron job and having a minimal update delay.. eg. run the cron twice a day (maybe even more), maybe handle two or three users at a time and have the cron running every 2 minutes...
Not a solution per-say; more of a suggestion.
I use: http://graph.facebook.com/{user_id or page_id}?fields=cover
Return on browser:
{
"cover": {
"id": "XXX",
"source": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash4/311205_989690200741_1231438675_n.jpg",
"offset_y": 66
},
"id": "XXXXXX"
}
How can I get field 'source' to a php varible?
Sr, I can't reply so i post here. :(
it tries to automatically recover from the image through php
$json = file_get_contents("https://graph.facebook.com/PROFILE_ID?fields=cover");
$obj = json_decode($json);
echo $obj->cover ->source;
I use username instead of id and it works:
http://graph.facebook.com/{username}?fields=cover
Parse the JSON accordingly.
I have used https://graph.facebook.com/facebookuserid?fields=cover link but it did not work. When I search Facebook SDK documentation, I see the answer that works.
I hope this will be helpful for you.
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"/%#?fields=cover", [user objectForKey:#"id"]]
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"%#",[[result objectForKey:#"cover"]objectForKey:#"source"]);
/* handle the result */
}];
Result is a type of a Dictionary. You can see the link of user's cover photo under "cover" tag and its "source" tag also.
This is how I extracted my cover pic using Jackson and the Graph API.
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode actualObj = mapper.readTree(String.valueOf(object));
JsonNode cover = actualObj.get("cover");
Map<String,String> myMap = mapper.readValue(cover.toString(), HashMap.class);
Log.e("Cover link", myMap.get("source"));
coverpic = myMap.get("source");
} catch (IOException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "cover");
request.setParameters(parameters);
request.executeAsync();
function getCover() {
FB.api('/me?fields=cover', function(response) {
document.getElementById('cover').innerHTML =
"<img src='" + response.cover['source'] + "' alt='' />"
});
}