Sending ‘Direct Message’ to a twitter user using Twitter4j

24 / Sep / 2012 by Vishal Sahu 0 comments

Hi,

In my recent grails project, i worked on integrating twitter API with the application. I used Twitter4j (a java wrapper for twitter API calls), to integrate the application and use the API calls. You can refer this blog to see how we can integrate the grails application with Twitter.


For making any 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 directMessage=’Hi, this is just a test message.’
String twitterName = // twitter name of the receiver.

[/java]


Code to send direct message to Twitter User:-

[java]

TwitterFactory factory = new TwitterFactory()
Twitter twitter = factory.getInstance()
twitter.setOAuthConsumer(consumerKey, consumerSecret)
AccessToken accessToken = new AccessToken(twitterToken, twitterSecret)
twitter.setOAuthAccessToken(accessToken)
DirectMessage directMessage = twitter.sendDirectMessage(twitterName, directMessage)

[/java]

So, the above code will send a direct message to the twitter user provided using API.
This worked for me.
Hope it helps.


Other Blogs:-

Mark Tweet as Favorite using Twitter4j
Reply to a tweet using Twitter4j
Retweet a tweet using Twitter4j
Post status update 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 *