[Scala] Plurk bot in 25 lines of code.

Today, I've add a PlurkBot interface to SOPlurk 0.2 -- a Scala binding for Plurk API 2.0.

Although there are a lot of debate that arguing Scala is a too complex programming language compared to Java. But Scala do provides a lot of useful features for library desginer, whcih makes library APIs become easy to use and very expressive, but still static typed -- the compiler will catch type error for you.

For example, the following code is a Plurk bot written with SOPlurk, it's basically a Scala version of this Python plurk bot. It will accept all friendship request, and respond to new plurks that contains the word hello.

The python version has more lines of code because it have to polling data itself instead of wrapping those logic in the libary like us. But to be frank, I don't know that the following code will be so much clear and expressive when I was written the PlurkBot class in SOPlurk.

import org.bone.soplurk.api._
import org.bone.soplurk.bot._
import org.bone.soplurk.constant._
import org.bone.soplurk.model._

val (appKey, appSecret) = ("APP_KEY", "APP_SECRET")
val (tokenKey, tokenSecret) = ("TOKEN_KEY", "TOKEN_SECRET")

val plurkBot = PlurkBot.withAccessToken(appKey, appSecret, tokenKey, tokenSecret) {
  plurkAPI: PlurkAPI => {
    case Alert(alertType, user, posted) => plurkAPI.Alerts.addAllAsFriends()
    case RealtimeResponse(user, plurk, response) => // Ignore any response
    case plurk: Plurk =>

      if (plurk.content.toLowerCase contains "hello") {
        plurkAPI.Responses.responseAdd(plurk.plurkID, "world", Qualifier.Says)
      }
  }
}

回響