I have a big problem with the Twitter API. Currently Twitter doesn't support fetching Tweets with their associated replies.
I would like to grap the mentions of the timeline and associate them with their replies.
Until this step everything is fine. Now my problem. I would like to add also the children replies of a reply to get a full relation between the mention and the replies.
Currently I fetch the timeline and split the results into mentions and replies.
public void fetchTwitterTimeline(long sinceId) {
try {
Paging timelinePaging = new Paging();
if (sinceId > 0) {
timelinePaging.setSinceId(sinceId);
}
LOG.debug("Fetching Twitter Timeline");
ResponseList<Status> statusResponseList = twitterClient.getMentionsTimeline(timelinePaging);
assignTwitterStatusResponse(statusResponseList);
} catch(TwitterException e){
e.getStackTrace();
System.out.println(e);
LOG.error("Could not fetch Twitter Timeline: {}", e);
}
}
private void assignTwitterStatusResponse(ResponseList<Status> statusResponseList) {
for (Status status : statusResponseList) {
if (status.isRetweet()) {
continue;
}
if (status.getInReplyToStatusId() > 0) {
replies.add(status);
} else {
mentions.add(status);
}
}
}
So thanks a lot for your response. Now I have a good solution also for those who has the same problems with it.
public List<Status> fetchTwitterThread(long tweetId) throws TwitterException {
Paging timelinePaging = new Paging();
timelinePaging.setSinceId(tweetId);
ResponseList<Status> statusResponseList = twitterClient.getMentionsTimeline(timelinePaging);
statusResponseList.addAll(twitterClient.getHomeTimeline(timelinePaging));
List<Status> thread = new ArrayList<>();
thread.add(getStatusById(tweetId)); // Add root status
fetchTwitterThread(tweetId, statusResponseList, thread);
return thread;
}
private void fetchTwitterThread(long parentId, ResponseList<Status> statusResponseList, List<Status> thread) {
for (Status status : statusResponseList) {
if (status.getInReplyToStatusId() == parentId) {
thread.add(status);
fetchTwitterThread(status.getId(), statusResponseList, thread);
}
}
}
I have two methods. This will be needed if you want to save some API calls. In the first step I fetch the mentionsTimeline and the hometimeline since the requested id. This is necessary for you own tweets and replies.
After that I've implemented a second method as a recursion. I iterate through the responseList and if one status (inReplyToStatusId) matches with the parentId, I add them to the thread.