Fetching twitter user mentions using Twitter4j

25 / Sep / 2012 by Vishal Sahu 1 comments

Hi,

In the last blog, we saw how to retrieve the tweets from user timeline which the user has marked as favorite using Twitter4j java wrapper for making twitter API calls.

In the same grails project, i had the requirement to fetch all the tweets in which the current user in mentioned in the tweet text. I searched about it and found a easy way to do so using the same java library and thought it worth sharing.



For making any twitter API calls we need to have twitter account access_token and access_secret, which we obtains after authorizing/connecting twitter account with the application as mentioned in this blog.


Code to fetch mentions tweets of twitter user :-

[java]
TwitterFactory factory = new TwitterFactory()
Twitter twitter = factory.getInstance()
twitter.setOAuthConsumer(consumerKey, consumerSecret)
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
twitter.setOAuthAccessToken(accessToken)

int totalTweets = page * 20
Paging paging = new Paging(1, totalTweets)
List tweets = twitter.getMentions(paging)
tweets.each {tweet ->
println "ID : ${tweet.id}"
println "User : ${tweet.user.screenName}"
println "Tweet : ${tweet.text}"
}
[/java]

So, this code will fetch the latest 20 tweets in which username is mentioned in the text.

Hope this helps.


FOUND THIS USEFUL? SHARE IT

comments (1 “Fetching twitter user mentions using Twitter4j”)

Leave a Reply

Your email address will not be published. Required fields are marked *