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

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

Related

Facebook chat using graph API

I'm using graph API in order to use Facebook chat.
I'm using the http://restfb.com/ framework.
The issue is that with the following code I can read all conversations and messages.
public void initClient()
{
m_facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, MY_APP_SECRET);
}
public void readPage()
{
Page page = m_facebookClient.fetchObject("352179081632935", Page.class);
System.out.println("Page likes = " + page.getLikes());
Connection<Conversation> conversations = m_facebookClient.fetchConnection("me/conversations", Conversation.class);
for(List<Conversation> conversationPage : conversations) {
for(Conversation conversation : conversationPage) {
System.out.println(conversation);
System.out.println(conversation.getUnreadCount());
Message lastMessage = null;
for (Message message : conversation.getMessages())
{
System.out.println("Message text = " + message.getMessage());
System.out.println("Message unread = " + message.getUnread());
System.out.println("Message from = " + message.getFrom().getName());
System.out.println("Message to = " + message.getTo().get(0).getName());
System.out.println("Message unseen = " + message.getUnseen());
lastMessage = message;
}
}
}
I would like to know how to send reply messages or new messages using this framework or Graph API?
Thank you,
Moshe
First of all, there is no me/conversations endpoint for users. Conversations are only available for Pages so it would be /{page-id}/conversations: https://developers.facebook.com/docs/graph-api/reference/v2.2/page/conversations
The Facebook docs explain in detail how it works, including some example code. I suggest using one of the official SDKs instead (JS SDK, PHP SDK, ...).
The Chat API (which is what you would want to use) is deprecated: https://developers.facebook.com/docs/chat/
Meaning, it is not possible anymore to use the Facebook chat in your App.
I found the way yo solve it by replying based on the conversation id.
For example:
m_facebookClient.publish("t_mid.1420120490471:36257b35667389d257/messages", FacebookType.class, Parameter.with("message", "RestFB test"));
t_mid.1420120490471:36257b35667389d257 - is the conversation id

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

Accessing Facebook data through the Facebook Graph API and restFB

When I access Facebook through the Graph API I get only very few entries. For instance if I access the Galaxy S4 fan page through the Graph API I see only four entries:
https://graph.facebook.com/412437702197294/comments/
if I access it through restFB I only get 2:
FacebookClient publicOnlyFacebookClient = new DefaultFacebookClient();
Page page = publicOnlyFacebookClient.fetchObject("GalaxySFour", Page.class);
JsonObject galaxySFourID = publicOnlyFacebookClient.fetchObject("GalaxySFOUR", JsonObject.class);
JsonObject galaxySFour = publicOnlyFacebookClient.fetchObject(galaxySFourID.getString("cover_id") + "/comments", JsonObject.class);
Vector<String> comments = new Vector<String>();
for(int i = 0; i < galaxySFour.length(); i++) {
comments.add("Message: " + galaxySFour.getJsonArray("data").getJsonObject(i).getString("created_time") + ": " + galaxySFour.getJsonArray("data").getJsonObject(i).getString("message"));
}
I'm aware that I cannot get all data, but I didn't expect to get so little. Is there anyway to get more data?
Access via this link : http://facebook.com/412437702197294,
there are only 4 comments. So, https://graph.facebook.com/412437702197294/comments/ return 4 comments is right.
By default, when retrieving data via Facebook Graph API, you only get 20 results.
You can use limit to get more data, such as:
http://facebook.com/412437702197294?limit=500
The maximum limit is 5000.

how to get friend's likes from 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.

Google+ and facebook api/rss feed like twitter api feed

I searched lot and I can see some questions same as mine in StackOverflow too but didn't get answer.
I need to get user(google+ and facebook) messages whatever posted by him under his/her account and give it as xml response to a mobile app which is going to show user posts as better format/design - so here I need to fetch the posts from google+/facebook using the profile-id/username.
Eg: Like from twitter I can able to see status from
https://api.twitter.com/1/statuses/user_timeline.xml?include_entities=true&include_rts=true&screen_name=screenname&count=2
Is there any library or any particular way by which i can get it?
Thanks in Advance.
I can only speak to Facebook and Twitter, as they are the only two Social Media API's I have utilized.
Both API's are RESTful services. For Twitter and Facebook, you will need to create applications on the perspective platforms in order to obtain an OAuth token for your applications that will be fetching the data via the RESTful services.
For FaceBook, you can utilize the Graph API explorer for development. This enables you to develope without creating an application on the FaceBook platform.
Both FaceBook and Twitter have community driven projects for accessing these web services in various languages. Since you are doing this for the Android, I assume you would like your program for fetching this data in Java.
RestFB is my recommendation for a Java FaceBook library
FacebookClient facebookClient = new DefaultFacebookClient(authToken);
User facebookUser = facebookClient.fetchObject("me", User.class);
Twitter4j is a great Java Twitter library
For FaceBook, core concepts is a great place to start.
For more information on Twitter on see the overview documentation
You can use the activities API for Google+. This is currently restricted to public posts but should be enough to get you started. The profile ID comes from a user's profile. There are other ways you can get this content as well, including the search API.
The documentation and simple examples from various languages can be found on the Google plus page (https://developers.google.com/+/api/latest/activities) and the following JavaScript example could be helpful for justing seeing how things work:
// globals used for auth, showing debugging
var debug = true;
var key = "your api key from https://code.google.com/apis/console";
function handleRequestIssue(request){
// For now, just show the error
console.log("Error, status:" + request.status + " / response:" + request.responseText);
}
function performXHR(URL){
var objReturn = "";
var request = new XMLHttpRequest();
request.open('GET', URL, false);
request.send(); // because of "false" above, will block until the request is done
// and status is available. Not recommended, however it works for simple cases.
if (request.status === 200) {
if (debug) console.log(request.responseText);
var objReturn = jQuery.parseJSON(request.responseText).items;
if (debug){
for (value in objReturn){
console.log(value);
}
}
}else{
handleRequestIssue(request);
}
return objReturn;
}
// Gets the activities for a profile
function getActivities(profileID){
var activities = null;
var URL = "https://www.googleapis.com/plus/v1/people/" + profileID + "/activities/public?alt=json&key=" + key;
activities = performXHR(URL);
console.log(activities.length);
return activities;
}
You can at this point see the activities in your debugger. You could always render the content as HTML inside a div or something.
function renderActsComments(activities, identifier, filter){
var renderMe = "";
console.log("activities retrieved: " + activities.length);
for (var i=0; i < activities.length; i++) {
var render = true;
console.log("trying to do something with an activity: " + i);
var activity = activities[i];
if (filter != null && filter.length > 0){
if (activity.crosspostSource.indexOf(filter) == -1){
render = false;
}
}
if (render == true){
renderMe += "<br/><div class=\"article\"><p>" + activity.title + "</p>";
console.log(activity.id);
// get comments
var comments = getCommentsForActivity(activity.id);
var left = true;
for (var j=0; j<comments.length; j++){
if (left){
left = false;
renderMe += "<br/><p class=\"speech\">" + comments[j].object.content + "</p>";
renderMe += "" + comments[j].actor.displayName + "";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += " <img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += "</p>";
}else{
renderMe += "<br/><p class=\"speechAlt\">" + comments[j].object.content + "</p>";
left = true;
renderMe += "<p class=\"profileAlt\">";
renderMe += "<a href=\"" + comments[j].actor.image.url.replace(/\?.*/, "") + "\">";
renderMe += "<img border=0 src=\"" + comments[j].actor.image.url + "\"/></a>";
renderMe += " " + comments[j].actor.displayName + "";
renderMe += "</p>";
}
}
renderMe += "</div>";
}
}
console.log("I'm done");
document.getElementById(identifier).innerHTML = renderMe;
return renderMe;
}