Twitter Plugin

  • Tags: /
  • Latest: 0.2
  • Last Updated: 07 January 2009
  • Grails version: 1.1.1
  • Authors: Burt Beckwith
4 votes
Dependency:
compile ":twitter:0.2"

 Issues

Summary

Installation

To integrate the plugin into your application just run the 'install-plugin' Grails script, e.g.

grails install-plugin twitter

Description

The Twitter plugin allows you to view and update Twitter information.

The current release (0.2) of the plugin ships with a jar that was built using JDK6. If you're using JDK5 please replace plugins/twitter-0.2/lib/json-112808.jar with the fixed version found here. This was unintentional - there's no JDK6-specific code - and will be fixed in the next release.


The plugin uses the JTwitter API, although it uses a slightly modified version with some bug fixes that have been submitted back to the API author.

Installation

To integrate the plugin into your application just run the 'install-plugin' Grails script, e.g.

grails install-plugin twitter

Features

  • provides a Service that wraps the JTwitter API
  • provides a TagLib to simplify displaying users, messages, statuses, etc.
  • implements a basic authentication system to remember Twitter username/password between requests
  • sample controller and GSPs provided to demonstrate usage

Usage

See the sample code in src/templates for examples of usage:

  • copy TwitterController.groovy to your grails-app/controllers folder
  • copy twitter.gsp to grails-app/views/layouts
  • create the folder grails-app/views/twitter
  • copy the remaining GSPs to grails-app/views/twitter
  • load http://localhost:8080/yourapp/twitter in your browser, authenticate with your Twitter credentials, and you'll see a summary page with your Friends, Followers, tweets, etc.
Note the files above to copy to your project will be located in the $HOME/.grails/1.1-xxxx/projects/APPNAME/plugins/twitter-0.2/src/templates/ directory.

Data classes

Message

Property/getter nameType
createdAtDate
idint
senderUser
recipientUser
textString
isPublic()boolean
favoritedboolean
inReplyToStatusIdlong
inReplyToScreenNameString
inReplyToUserIdlong
truncatedboolean

Status

Property/getter nameType
createdAtDate
idlong
textString
userUser
inReplyToStatusIdlong
inReplyToScreenNameString
inReplyToUserIdlong
truncatedboolean

User

Property/getter nameType
descriptionString
idint
locationString
name (the display name, e.g. "Daniel Winterstein")String
profileImageUrlURI
protectedUserboolean
screenName (the login name, e.g. "winterstein")String
statusStatus
websiteURI

TwitterService

TwitterService wraps the JTwitter API and also provides authentication methods.

API wrapper methods

All API methods where 'Requires Auth' is true either need cached credentials (from a previous login() call) or can take a 'username' and 'password' in an optional 'authParams' parameter.

For example, getUserTimeline() requires authentication; the method signature is

List<Status> getUserTimeline(Map authParams = [:]) throws TwitterException

so if you're logged in you would call getUserTimeline() and if you need to pass credentials you would call getUserTimeline([username: 'foo', password: 'bar'])

NameDescriptionReturnParametersRequires Auth
befriendBefriends the specified userUserString username: the ID or screen name of the user to befriendtrue
breakFriendshipDiscontinues friendship with the specified userUserString username: the ID or screen name of the user with whom to discontinue friendshiptrue
destroyStatusDestroys the status specified by the required ID parameter. The authenticated user must be the author of the specified status.voidStatus status: the status to deletetrue
destroyStatusDestroys the given status. The authenticated user must be the author of the status post.voidint statusId: the id of the status to deletetrue
getDirectMessagesReturns direct messages sent to the authenticated user.List<Message>nonetrue
getRateLimitStatusGet the remaining number of API requests available to the authenticated user before the API limit is reached for the current hour.int, the remaining numbernonetrue
getRecentDirectMessagesReturns the last 20 direct messages sent to the authenticated userList<Message>nonetrue
getDirectMessagesReturns the direct messages sent to the authenticated userList<Message>Date since: narrows the resulting list of direct messages to just those sent after the specified datetrue
getDirectMessagesReturns the direct messages sent to the authenticated userList<Message>long sinceId: the id of a direct message, narrows the resulting list of direct messages to just those sent after the specified message idtrue
getFeaturedReturns the users currently featured on the siteList<User>nonefalse
getFollowersReturns the authenticated user's followersList<User>nonetrue
getFriendsReturns the (latest 100) authenticated user's friendsList<User>nonetrue
getFriendsReturns the (latest 100) given user's friendsList<User>String username: the ID or screen name of the userfalse
getFriendsTimelineReturns the 20 most recent statuses posted in the last 24 hours from the authenticated user and that user's friendsList<Status>nonetrue
getFriendsTimelineReturns the 20 most recent statuses posted in the last 24 hours from the user and that user's friendsList<Status>String id: optional, specifies the ID or screen name of the user for whom to return the friends_timeline, Date since: optional, narrows the returned results to just those statuses created after the specified datetrue
getPublicTimelineReturns the 20 most recent statuses from non-protected users who have set a custom user iconList<Status>nonefalse
getRepliesReturns the 20 most recent replies (status updates prefixed with @username) to the authenticated userList<Message>nonetrue
getStatusGet the current status of the authenticated userStatusnonetrue
getStatusReturns a single statusStatusint id: the numerical ID of the statustrue
getStatusGet the current status of the given userStatusString username: the usernamefalse
getUserTimelineReturns the 20 most recent statuses posted in the last 24 hours from the authenticated userList<Status>nonetrue
getUserTimelineReturns the most recent statuses posted in the last 24 hours from the specified userList<Status>String id: optional, specifies the ID or screen name of the user, Integer count: optional (defaults to 20), specifies the number of statuses to retrieve; may not be greater than 20 for performance purposes, Date since: optional, narrows the returned results to just those statuses created after the specified dateAuthentication is needed to see the posts of a private user
sendMessageSends a new direct message to the specified user from the authenticated userMessage, the sent messageString recipient: the ID or screen name of the recipient user, String text the text of your direct message - keep it under 140 characters!true
setStatusSets the authenticated user's statusStatus, the posted statusString text: the text of your status update. Must not be more than 160 characters and should not be more than 140 characters to ensure optimal displaytrue
showGet the user, specified by ID or screen nameUserString id: the ID or screen name of a usertrue

API wrapper methods

NameDescriptionReturn typeParameters
isLoggedInCheck if there are cached creditials from a session cookieboolean, true if there are cached creditialsnone
findCredentialsCalled by TwitterFilter to extract username/password from the session cookievoidcookies, array of cookies, possibly null
loginCalled by login controller actionboolean, true if successfulString username: Twitter login name, String password: Twitter password, request: http request, response: http response
logoutDelete cookie and reset cached credentialsvoidrequest: http request, response: http response

TwitterTagLib

The taglib's namespace is 'twitter', e.g. <twitter:directMessages>...</twitter:directMessages>. See src/templates/index.gsp for sample usage of all tags.

Most tags are iterative, i.e. they call TwitterService to get a List of Statuses, Users, or Messages and loop through them, invoking the tag's body on each instance. The variable name inside the tag body is 'it'.

All taglib code is wrapped in a try/catch since Twitter fails sporadically (the 'fail whale'). When this happens the taglib logs the error and exposes the exception as a request attribute 'twitterException' and renders no output.

Tags

Tag nameDescriptionAttributes
directMessagesGets direct messages and loops through them'since' (Date) and 'sinceId' (long), both optional, used to limit the message count
recentDirectMessagesGets recent direct messages and loops through themnone
repliesGets reply messages and loops through themnone
followersGets followers and loops through themnone
friendsGets friends (people you follow) and loops through themif the 'username' attribute (login name or numeric id) is present it finds that user's friends, otherwise it finds the logged-in user's
featuredGets Twitter 'featured users' and loops through themnone
userGets a single user'userId', username or numeric ID
statusGets the current status for a userIf the 'username' attribute (login name) is present it finds that user's friends, otherwise if the 'userId' attribute (numeric id) is present it finds that user's friends, otherwise it finds the logged-in user's
friendsTimelineGets the 20 most recent statuses posted in the last 24 hours from the authenticated user and that user's friendsif the 'userId' attribute (login name or numeric id) is present it finds that user's statuses, otherwise it finds the logged-in user's; if the 'since' attribute (Date) is present it limits results to only those after that date
publicTimelineGets the 20 most recent statuses from non-protected users who have set a custom user iconnone
userTimelineGets the 20 most recent statuses posted in the last 24 hours from the authenticated userIf the 'userId' attribute (login name or numeric id) is present it finds that user's statuses, otherwise it finds the logged-in user's; if the 'since' attribute (Date) is present it limits results to only those after that date; if the 'count' attribute (int) is present it limits results to no more than that number
profileImageRenders an <img> tag for a user's profile image'user', the user; 'alt', String - optional - for the tag's 'alt' attribute; 'border', int - optional - for the tag's 'border' attribute (defaults to 0); all other attributes are rendered in the html tag
publicTimelineConvert urls to clickable links and @username to clickable Twitter homepage links'text', String - the text to mark up; 'links', boolean - to specify whether to mark up links (defaults to true); 'usernames', boolean - to specify whether to mark up @username (defaults to true)
userLinkRenders a link to a user's twitter.com page'name', String - the user's login name; 'text', String - optional - the link text (defaults to the user's login name); all other attributes are passed through to the tag
tweetLinkRenders a link to a tweet (status) twitter.com page'name', String - the user's login name; 'id', long - the status id; all other attributes are passed through to the tag
tweetLinkRenders a link for a URL with a target of '_blank' (new window). If the 'url' attribute is null, nothing is rendered'url', URL - the url of the link; 'text', String- the link text to display (defaults to the URL); all other attributes are passed through to the tag
rateLimitStatusGets the remaining number of API requests available to the authenticating user before the API limit is reached for the current hournone

Author

Burt Beckwith burt@burtbeckwith.com

Please report any issues to the Grails User mailing list and/or write up an issue in JIRA at http://jira.codehaus.org/browse/GRAILSPLUGINS under the Grails-Twitter component.

History

  • January 8, 2009
    • released version 0.2
  • January 5, 2009
    • released initial version 0.1