A Scala Twitter client example

Just a quick note here today that if you want to create a Twitter client in Scala, the Java Twitter4J library looks like a good path to take.

I've shown an example below, where you can see that besides the eight lines of code it takes to create a Scala twitter object, the actual code you need to get information from the Twitter developer API is pretty short.

package com.devdaily.twitterclient
import twitter4j.TwitterFactory
import twitter4j.Twitter
import twitter4j.conf.ConfigurationBuilder

object ScalaTwitterClientExample {
  
  def main(args : Array[String]) {
    
    // (1) config work to create a twitter object
    val cb = new ConfigurationBuilder()
    cb.setDebugEnabled(true)
      .setOAuthConsumerKey("YOUR KEY HERE")
      .setOAuthConsumerSecret("YOUR SECRET HERE")
      .setOAuthAccessToken("YOUR ACCESS TOKEN")
      .setOAuthAccessTokenSecret("YOUR ACCESS TOKEN SECRET")
    val tf = new TwitterFactory(cb.build())
    val twitter = tf.getInstance()

    // (2) use the twitter object to get your friend's timeline
    val statuses = twitter.getFriendsTimeline()
    System.out.println("Showing friends timeline.")
    val it = statuses.iterator()
    while (it.hasNext()) {
      val status = it.next()
      println(status.getUser().getName() + ":" +
              status.getText());
    }

  }
}

This code is pretty much a straight Scala conversion of the Twitter4J Java configuration example shown on this Twitter4J page, with the Twitter friend's timeline call added at the end. (At some point I'll come back to this and make it look more like Scala than Java.)

I'll assume you're already familiar with Twitter client programming, so I won't explain all those keys, secrets, and tokens, but if not, see the Twitter developer website for more information.

In summary, if you're interested in Scala Twitter programming (Twitter API client programming), I hope this simple example helps get you started. My first inclination was to start writing my own Scala Twitter library based on REST calls, but when I found the Twitter4J project, I decided to start using it instead.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.