Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 6

[ 119 ]

Direct messages

Twitter has a direct message feature that allows you to send messages directly to
another Twitter user. Direct messages don't show up in your general Twitter profile
and are private to the sender and the recipient. We can use the APIs to send direct
messages to a user and to check our own current messages from other users:


def twitter = TwitterFactory.singleton

// Send a direct messsage to twitter user GroovyDSL
twitter.sendDirectMessage(
"GroovyDSL",
"Hi Fergal read Groovy for DSL and loved it")

// Retrieve our latest direct messages
// same as visiting http://twitter.com/#inbox
messages = twitter.directMessages

messages.each { message ->
println "Message from : $message.senderScreenName"
println " ${message.text}"
}

You can only direct message to users in Twitter who follow you. This
also applies to the preceding example. If you try it out yourself, you
will need to use a user ID that is one of your Twitter followers.

In the code snippet that we've just seen, we used the Twitter.sendDirectMessage
method to send a message to the Twitter user GroovyDSL. We then use the
Twitter.directMessages method to retrieve our latest direct messages from our
inbox. This, in fact, is a shortcut to the Twitter.getDirectMessages API, which
returns a list of DirectMessage objects. Groovy conveniently allows us to take
shortcuts to any getter methods as a property access, even though the Twitter class
is not in fact a POJO. We then list the sending user's screen name and the text of the
message. We can also retrieve the time when the message was sent, and the user
objects for the sender and recipient of the message.

Free download pdf