Twitter

The Twitter Module

The Twitter module in KRL gives you programmatic access to the Twitter API from within KRL rulesets. As currently implemented, this access is read-only. That is, none of the timeline update functions in the API have been exposed. Kynetx anticipates that as we and KRL developers get more experience with using Twitter inside KRL apps, that the update functions will also be made available.

OAuth

The Twitter module provides access to the timelines and information for individual users using OAuth. When properly designed, rulesets using the Twitter module will check to see if the user has authorized the ruleset to access the user's Twitter information. If so, the the app continues, and if not, it uses the twitter:authorize action to initiate an OAuth session with Twitter so that the user can make the authorization.

To have your ruleset use Twitter via OAuth, you will need to register your application with Twitter and obtain the consumer token and consumer secret from Twitter. These are entered in the ruleset meta section using a key pragma:

meta {
  key twitter {
    "consumer_key" : "skfjldfajsdkfaj",
    "consumer_secret" : "fjfoiasjf;asdfjpaodifjosdfjadoifjsdopfasdjfoa"
  }
}

You should use a different consumer key and secret for each Kynetx application you write so that users can authorize applications and revoke access individually.

In the application:

  • Use the same image for Twitter OAuth that you use in your card in AppBuilder for visual continuity.
  • You can say that it is a KRL application and that it's powered by Kynetx, but do not represent yourself as Kynetx.
  • You can use you app's description page in the Kynetx App Directory as the application homepage if you like.
  • Choose "browser" as the application type. You cannot leave the callback URL blank even though what you put there will NOT be used. Twitter's page is broken and if this is left blank, it will assume you want a "client" app instead of a "browser" app and that won't work. Put any URL you like there.
  • Use "read-only" as the access type and you won't need to do logins from the account.
  • After you save your changes, click back in and make sure they stuck.

Note that you can see all your Twitter apps and edit the values of these later if they need to change.

Example

This example shows the "authorize, initialize, populate" pattern that will be common to many rulesets that use the Twitter module. We'll assume that the meta section of the ruleset contains a valid consumer token and secret.

The first thing we do is get the friends_timeline from Twitter if the user has authorized the ruleset access to their Twitter information in the global block:

global {
  tweets = twitter:authorized() => twitter:friends_timeline({"count" : 4})
                                 | [];
}

The authorize rule runs the twitter:authorize() action if the user hasn't authorized the ruleset access. Note the fired postlude that executes last so that this is the last rule fired in this ruleset if the rule fired:

rule authorize is active {
  select using ".*" setting ()

  if not twitter:authorized()
  then
    twitter:authorize()
      with
        opacity = 1 and
        sticky = true;

 fired {
   last;
 }
}

The init_tweetdom rule is responsible for setting up an HTML <div/> element inside a notification box:

rule init_tweetdom is active {
  select using ".*" setting ()

  pre {
    init_div = <<
<div id="tweet_list">  </div>
 >>;
  }

  notify("Friends Tweets", init_div)
    with
      sticky = true and
      opacity = 1;
}

Remember that this rule (and any others in the ruleset) only execute if the authorize rule does not fire.

The populate_tweetdom rule is responsible for using the Twitter information from the global block to populate the <div/> element set up by the init_tweetdom rule with tweets. Note that the foreach runs the action in this rule (an append) once for every element of the array tweets:

rule populate_tweetdom is active {
  select using ".*" setting ()
    foreach tweets setting (tweet)

      pre {
        text = tweet.pick("$..text");
        div = "<div style='background-color:#666;margin:2px'>" + text + "</div>";
      }

      append("#tweet_list", div);
}

Performance

Remember that any data you access in a KRL ruleset is turned into Javascript and sent to the browser and the Twitter API is verbose. So retrieving several large timelines and using them will result is large data definitions being downloaded to the browser and consequent performance penalties.

Checking for authorization can take several seconds, so the initial authorization request can appear slow at times depending on Twitter performance.

Twitter rate limits their API for each user. You ruleset may run into these limitations.

Predicates

The only predicate available inside the Twitter module is the authorized predicate. It takes no parameters and should be proceeded by the namespace designation twitter:

twitter:authorized() => twitter:friends_timeline({"count" : 4})
                      | [];

This predicate can be used as part of any valid KRL expression.

Actions

The only action available inside the Twitter module is the authorize action. It takes no parameters and should be proceeded by the namespace designation twitter:

twitter:authorize()
  with
    opacity = 1 and
    sticky = true;

The authorize action is a special case of the notify action and takes the same options, but no parameters. This is an example of what the authorize action places on the page:

Twitter_OAuth_notification

The application name, author, and description are all taken from the meta section of the ruleset. Users will be more likely to grant your application access if the information in the meta section is good and descriptive.

Twitter API Functions

Once the user has authorized the ruleset to access their Twitter data, the functions described below can be used to interact with the Twitter API. Remember that the data returned is specific to the user who authorized the access unless otherwise noted (e.g. the public_timeline function).

The functions are based on the Net::Twitter::Lite Perl library. I have blatantly stolen the description of the functions from that document. You may also find the documentation for the Twitter API helpful in understanding how to interact with Twitter.

The following descriptions of the functions list parameters that the function takes and notes any that are required. The only way to pass arguments to the Twitter API functions is as a hash with the name of the parameter and the value like so:

twitter:friends_timeline({"count" : 4})

This would access the friends_timeline and retrieve the last four tweets.

Methods that support the page parameter expect page numbers > 0. Twitter silently ignores invalid page values. So { "page": 0 } produces the same result as { "page":1 }.

Several of these functions accept a user ID as the id parameter. The user ID can be either a screen name, or the users numeric ID. To disambiguate, use the screen_name or user_id parameters, instead.

All of these should be proceeded by the twitter namespace in use as seen in the previous examples.

blocking()

Returns an array of user objects that the authenticating user is blocking.

  • Parameters: page
  • Required: none
  • Returns: array

blocking_ids()

Returns an array of numeric user ids the authenticating user is blocking.

  • Parameters: none
  • Required: none
  • Returns: array

favorites()

Returns the 20 most recent favorite statuses for the authenticating user or user specified by the ID parameter.

  • Parameters: id, page
  • Required: none
  • Returns: array

followers()

Returns a reference to an array of the user's followers. If id, user_id, or screen_name is not specified, the followers of the authenticating user are returned. The returned users are ordered from most recently followed to least recently followed.

Use the optional cursor parameter to retrieve users in pages of 100. When the cursor parameter is used, the return value is a reference to a hash with keys previous_cursor, next_cursor, and users. The value of users is a reference to an array of the user's friends. The result set isn't guaranteed to be 100 every time as suspended users will be filtered out. Set the optional cursor parameter to -1 to get the first page of users. Set it to the prior return's value of previous_cursor or next_cursor to page forward or backwards. When there are no prior pages, the value of previous_cursor will be 0. When there are no subsequent pages, the value of next_cursor will be 0.

  • Parameters: id, user_id, screen_name, cursor
  • Required: none
  • Returns: arrray

followers_ids(id)

Returns a reference to an array of numeric IDs for every user following the specified user.

Use the optional cursor parameter to retrieve IDs in pages of 5000. When the cursor parameter is used, the return value is a reference to a hash with keys previous_cursor, next_cursor, and ids. The value of ids is a reference to an array of IDS of the user's followers. Set the optional cursor parameter to -1 to get the first page of IDs. Set it to the prior return's value of previous_cursor or next_cursor to page forward or backwards. When there are no prior pages, the value of previous_cursor will be 0. When there are no subsequent pages, the value of next_cursor will be 0.

  • Parameters: id, user_id, screen_name, cursor
  • Required: id
  • Returns: array

friends()

Returns a reference to an array of the user's friends. If id, user_id, or screen_name is not specified, the friends of the authenticating user are returned. he returned users are ordered from most recently followed to least recently followed.

Use the optional cursor parameter to retrieve users in pages of 100. When the cursor parameter is used, the return value is a reference to a hash with keys previous_cursor, next_cursor, and users. The value of users is a reference to an array of the user's friends. The result set isn't guaranteed to be 100 every time as suspended users will be filtered out. Set the optional cursor parameter to -1 to get the first page of users. Set it to the prior return's value of previous_cursor or next_cursor to page forward or backwards. When there are no prior pages, the value of previous_cursor will be 0. When there are no subsequent pages, the value of next_cursor will be 0.

  • Parameters: id, user_id, screen_name, cursor
  • Required: none
  • Returns: array

friends_ids(id)

Returns a reference to an array of numeric IDs for every user followed the specified user.

Use the optional cursor parameter to retrieve IDs in pages of 5000. When the cursor parameter is used, the return value is a reference to a hash with keys previous_cursor, next_cursor, and ids. The value of ids is a reference to an array of IDS of the user's friends. Set the optional cursor parameter to -1 to get the first page of IDs. Set it to the prior return's value of previous_cursor or next_cursor to page forward or backwards. When there are no prior pages, the value of previous_cursor will be 0. When there are no subsequent pages, the value of next_cursor will be 0.

  • Parameters: id, user_id, screen_name, cursor
  • Required: id
  • Returns: array

friends_timeline()

Returns the 20 most recent statuses posted by the authenticating user and that user's friends. This is the equivalent of /home on the Web.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

friendship_exists(user_a, user_b)

Tests for the existence of friendship between two users. Will return true if user_a follows user_b, otherwise will return false.

  • Parameters: user_a, user_b
  • Required: user_a, user_b
  • Returns: Bool

home_timeline()

Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

mentions()

Returns the 20 most recent mentions (statuses containing \@username) for the authenticating user.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

public_timeline()

Returns the 20 most recent statuses from non-protected users who have set a custom user icon. Does not require authentication. Note that the public timeline is cached for 60 seconds so requesting it more often than that is a waste of resources.

  • Parameters: none
  • Required: none
  • Returns: array

rate_limit_status()

Returns the remaining number of API requests available to the authenticated user before the API limit is reached for the current hour.

  • Parameters: none
  • Required: none
  • Returns: hash

retweeted_by_me()

Returns the 20 most recent retweets posted by the authenticating user.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

retweeted_of_me()

Returns the 20 most recent tweets of the authenticated user that have been retweeted by others.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

retweeted_to_me()

Returns the 20 most recent retweets posted by the authenticating user's friends.

  • Parameters: since_id, max_id, count, page
  • Required: none
  • Returns: array

retweets(id)

Returns up to 100 of the first retweets of a given tweet.

  • Parameters: id, count
  • Required: id
  • Returns: array

saved_searches()

Returns the authenticated user's saved search queries.

  • Parameters: none
  • Required: none
  • Returns: array

sent_direct_messages()

Returns a list of the 20 most recent direct messages sent by the authenticating user including detailed information about the sending and recipient users.

  • Parameters: since_id, max_id, page
  • Required: none
  • Returns: array

show_friendship(id)

Returns detailed information about the relationship between two users.

  • Parameters: source_id, source_screen_name, target_id, target_id_name
  • Required: id
  • Returns: relationship

show_saved_search(id)

Retrieve the data for a saved search, by ID, owned by the authenticating user.

  • Parameters: id
  • Required: id
  • Returns: SavedSearch

show_status(id)

Returns a single status, specified by the id parameter. The status's author will be returned inline.

  • Parameters: id
  • Required: id
  • Returns: status

show_user(id)

Returns extended information of a given user, specified by ID or screen name as per the required id parameter. This information includes design settings, so third party developers can theme their widgets according to a given user's preferences. You must be properly authenticated to request the page of a protected user.

  • Parameters: id
  • Required: id
  • Returns: ExtendedUser

trends_available()

Returns the locations with trending topic information. The response is an array of "locations" that encode the location's WOEID (a Yahoo! Where On Earth ID) and some other human-readable information such as a the location's canonical name and country.

When the optional lat and long parameters are passed, the available trend locations are sorted by distance from that location, nearest to farthest.

Use the WOEID returned in the location object to query trends for a specific location.

  • Parameters: lat, long
  • Required: none
  • Returns: array

trends_location(woeid)

Returns the top 10 trending topics for a specific location. The response is an array of "trend" objects that encode the name of the trending topic, the query parameter that can be used to search for the topic on Search, and the direct URL that can be issued against Search. This information is cached for five minutes, and therefore users are discouraged from querying these endpoints faster than once every five minutes. Global trends information is also available from this API by using a WOEID of 1.

  • Parameters: woeid
  • Required: woeid
  • Returns: array

user_id()

Returns the user_id.

  • Parameters: none
  • Required: none
  • Returns: integer

user_timeline()

Returns the 20 most recent statuses posted from the authenticating user. It's also possible to request another user's timeline via the id parameter. This is the equivalent of the Web /archive page for your own user, or the profile page for a third party.

  • Parameters: id, user_id, screen_name, since_id, max_id, count, page
  • Required: none
  • Returns: array

users_search(q)

Run a search for users similar to Find People button on Twitter.com; the same results returned by people search on Twitter.com will be returned by using this API (about being listed in the People Search). It is only possible to retrieve the first 1000 matches from this API.

  • Parameters: q, per_page, page
  • Required: q
  • Returns: array

search(q)

Returns a HASH reference with some meta-data about the query including the next_page, refresh_url, and max_id. The statuses are returned in results. To iterate over the results, use something similar to:

  • Parameters: q, callback, lang, rpp, page, since_id, geocode, show_user
  • Required: q
  • Returns: hash

trends()

Returns the top ten queries that are currently trending on Twitter. The response includes the time of the request, the name of each trending topic, and the url to the Twitter Search results page for that topic.

  • Parameters: none
  • Required: none
  • Returns: array

trends_current()

Returns the current top ten trending topics on Twitter. The response includes the time of the request, the name of each trending topic, and query used on Twitter Search results page for that topic.

  • Parameters: exclude
  • Required: none
  • Returns: hash

trends_daily()

Returns the top 20 trending topics for each hour in a given day.

  • Parameters: date, exclude
  • Required: none
  • Returns: hash

trends_weekly()

Returns the top 30 trending topics for each day in a given week.

  • Parameters: date, exclude
  • Required: none
  • Returns: hash

Return Values

ExtendedUser

Some functions return an extended user object. This includes detailed information about the user including their most recent status. Here is an example of the extended user object for @windley:

{
     description: "I build things; I write code; I void warranties"
     profile_text_color: "000000"
     profile_image_url: http://a3.twimg.com/profile_images/525686087/windley_2009_145_normal.jpg
     status: {
          o favorited: false
          o in_reply_to_user_id: null
          o in_reply_to_status_id: null
          o in_reply_to_screen_name: null
          o source: "<a href="http://friendfeed.com/" rel="nofollow">FriendFeed</a>"
          o id: 7508660428
          o truncated: false
          o text: "HDR Tutorial | High Dynamic Range Tutorial http://ff.im/dYJC9"
          o created_at: "Fri Jan 08 05:44:50 +0000 2010"
      }
     profile_background_image_url: http://a3.twimg.com/profile_background_images/3343255/blue-water-drops.jpg
     statuses_count: 6246
     profile_link_color: "0000ff"
     screen_name: "windley"
     following: false
     profile_background_tile: false
     followers_count: 2036
     profile_background_color: "001E4C"
     notifications: false
     friends_count: 604
     geo_enabled: false
     profile_sidebar_fill_color: "e0ff92"
     protected: false
     url: http://www.windley.com
     favourites_count: 10
     location: "Lehi, Utah"
     name: "Phil Windley"
     time_zone: "Mountain Time (US & Canada)"
     profile_sidebar_border_color: "87bc44"
     id: 1878461
     verified: false
     utc_offset: -25200
     created_at: "Thu Mar 22 14:04:00 +0000 2007"
}