Twitter Client in Scala
I’ve been playing with Scala a bit lately. Tonight, I was fooling around with Scala using an online, interactive shell called lotrepls. I decided to write a script that would call the Twitter API and return me the status for a Twitter user. The script takes a Twitter user name as input and prints that user’s status to the screen. It turns out that Scala has some built-in XML parsing capabilities that makes this really easy.
This is the script.
import java.net._
import scala.xml._
val screenName = "robbr" // Follow me!
val url =
new URL("http://twitter.com/users/show.xml?screen_name=" +
screenName)
val conn = url.openConnection
val xml = XML.load(conn.getInputStream)
val status = (xml\"status"\"text").text
println(screenName + ": " + status)
I’ll quickly break down the script line by line for non-Scala people. Not that I’m a Scala export myself.
- Scala is completely interoperable with Java. Scala can call Java and Java can call Scala. In the first line, I am importing all classes in the java.net package to use for making a HTTP request later in the script.
- In the second line I am importing all classes in the Scala XML package.
- I set the screen name which is input to the Twitter status API call. I could instead prompt the user for the screen name using Console.readline(), but this doesn’t work with lotrepls.
- Set the URL for the Twitter status API.
- Open a URL connection.
- Load the XML output of the HTTP request into a variable. The “val” modifier makes the variable final, therefore it can’t be changed.
- I use an XPath like statement to navigate the XML for the data element I am looking for. I get only the text of that element.
- Output the screen name and status to the screen.
This script can simply be cut and pasted into lotrepls. Remember to switch to Scala before running the script. Use CTRL+ENTER to execute. That’s all there is to it. Enjoy.
Twitter Me This?!?
OK, I’ll play. I’m not sure how exciting twittering will be unless I find it to be a nice replacement or supplement for IM. You can follow me here. I can see how people are getting hooked on it, however, I think it will be interesting to see if Twitter can sustain the hype.