Follow/Unfollow twitter account using Twitter4j

24 / Sep / 2012 by Vishal Sahu 0 comments

Hi,

In my recent grails project, i worked on integrating twitter API with the grails application. In one of the requirements, we needed to show the tweets from user wall and show the profile of the person/account who posted that tweet. In the profile, the user should be able to Follow or Unfollow that person from his twitter account using our application interface. I used Twitter4j (a java wrapper for twitter API calls), to make API calls and implemented this functionality.


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.


Pre-Requirements:-

[java]
String consumerKey = CONSUMER_KEY // key obtained after registering app.
String consumerSecret =CONSUMER_SECRET // secret key obtained from the registered app.
String twitterToken = USER_TWITTER_TOKEN
// access_token received by authentication user’s twitter account
String twitterSecret= USER_TWITTER_SECRET
// access_secret obtained by authentication user’s twitter account
String twitterName = // twitterName of the twitter account the user want to follow/unfollow

[/java]


Code to Follow a Twitter Account:-

[java]

TwitterFactory factory = new TwitterFactory()
Twitter twitter = factory.getInstance()
twitter.setOAuthConsumer(consumerKey, consumerSecret)
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
twitter.setOAuthAccessToken(accessToken)
twitter4j.User user = twitter.createFriendship(twitterName)
}
[/java]

The above code will help to Follow the twitter account provided in the twitterName.


Code to Unfollow a Twitter Account:-

[java]

TwitterFactory factory = new TwitterFactory()
Twitter twitter = factory.getInstance()
twitter.setOAuthConsumer(consumerKey, consumerSecret)
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
twitter.setOAuthAccessToken(accessToken)
twitter4j.User user = twitter.destroyFriendship(twitterName)
}
[/java]

The above code will help to Unfollow the twitter account provided in the twitterName.


This worked for me.
Hope it helps.


Other Blogs:-

Send Direct Message using Twitter4j
Mark Tweet as Favorite using Twitter4j
Reply to a tweet using Twitter4j
Retweet a tweet using Twitter4j


Cheers!!!
Vishal Sahu
vishal@intelligrape.com

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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