Talking to Twitter

"Twitter" Gem for Ruby

Readers of this column know that I love the Ruby language, so it won't come as a surprise to hear that I intend to use Ruby for my examples. However, there are Twitter API clients in virtually every modern language, making it easy to access from whatever you prefer to use in your programming.

The twitter Ruby gem, as is the case for all Ruby gems (libraries), is available for installation via the gem program, which comes with modern versions of Ruby. The gem currently is maintained by Erik Michaels-Ober, also known as "sferik" on GitHub. You can type:


gem install twitter -V

and the gem should be installed. On many systems, including those not running a Ruby version manager like rvm, you need to execute the above line while logged in as root.

Once you have installed the gem, you can use it. There are three parts to this process: bringing the gem into the program, configuring it to use your keys and secrets, and then executing a Twitter command. The first is handled with the Ruby require command, which looks at installed gems, as well as the Ruby core and standard libraries.

Configuration of the client is handled fairly straightforwardly from within a block that looks like this (filling in the values you got from Twitter's API documentation):


twitter_client = Twitter::REST::Client.new do |config|
  config.consumer_key = CONSUMER_KEY
  config.consumer_secret = CONSUMER_SECRET
  config.oauth_token = OAUTH_TOKEN
  config.oauth_token_secret = OAUTH_SECRET
end

Notice that you are not merely executing the "new" method on Twitter::REST::Client, but that you also are returning a value. Thus, in contrast to previous versions of Ruby's Twitter gem, you should accept the returned object, which is then the basis for all of the additional actions you wish to take.

Finally, you send the tweet with the "update" method:


tweet = twitter_client.update("Hello, world. Tweet tweet.")

Invoking the #update method has the effect of sending the message to Twitter. If you go to the Web page for your Twitter user, you'll find that a new message has been sent, as if you had typed it.

If you capture the return value from the invocation of twitter_client.update, you'll see that it is an instance of Twitter::Tweet, a Ruby object that represents a tweet. This object provides the functionality that you would want and expect from something associated from Twitter. For example:


tweet.user          # tells us who wrote the tweet
tweet.retweeted?    # indicates whether it was retweeted
tweet.favorited?    # indicates whether it was marked as a favorite

Now, it's also possible that you will not get a tweet object back at all, but rather that the "update" method will raise an exception. For example, Twitter forbids users from sending an identical tweet, at least within a short period of time. Thus, if you send the above "Hello, world" tweet (from the example above) a second time, you'll get an exception:


Twitter::Error::Forbidden: Status is a duplicate.

Of course, you can catch such errors with:


begin
  tweet = twitter_client.update("Hello again, 
  ↪@reuvenmlerner  Tweet tweet.")
rescue Twitter::Error::Forbidden => e
  puts "You already tweeted that."
rescue => e
  puts e.class    # Twitter::Error::Forbidden
  puts e.message  # 'Status is a duplicate.'
end

If you include a Twitter @username, hashtag or URL in your tweet, the appropriate magic will happen automatically. Thus:


tweet = twitter_client.update("Go to @reuvenmlerner's 
 ↪site at http://lerner.co.il/")

In the above tweet, the URL automatically will be shortened, using Twitter's standard t.co domain. Similarly, the @reuvenmlerner (my Twitter handle) will turn into a link. You can access both of these using methods on your tweet:


tweet.urls           # returns an array of Twitter::Entity::URI
tweet.user_mentions  # returns an array of 
                     # Twitter::Entity::UserMention

You can more generally ask Twitter for information about tweets. For example, you can get the most recent tweets a user has sent with:


twitter_client.user_timeline("reuvenmlerner")

which returns an array of tweet objects. You can apply the "text" method to the first element, thus getting the text back from the user's most recent tweet:


twitter_client.user_timeline("reuvenmlerner")[0].text

If there are URLs embedded in the tweet, you can get those back:


twitter_client.user_timeline("reuvenmlerner")[1].urls

This method returns an array of Twitter::Entity::URI objects, each of which has attributes, such as "url" and "expanded URL".

______________________

Reuven M. Lerner, Linux Journal Senior Columnist, a longtime Web developer, consultant and trainer, is completing his PhD in learning sciences at Northwestern University.

Webinar
One Click, Universal Protection: Implementing Centralized Security Policies on Linux Systems

As Linux continues to play an ever increasing role in corporate data centers and institutions, ensuring the integrity and protection of these systems must be a priority. With 60% of the world's websites and an increasing share of organization's mission-critical workloads running on Linux, failing to stop malware and other advanced threats on Linux can increasingly impact an organization's reputation and bottom line.

Learn More

Sponsored by Bit9

Webinar
Linux Backup and Recovery Webinar

Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.

In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.

Learn More

Sponsored by Storix