1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

How to Tweet From Ruby

Using POST Requests

By

Tweeting From Ruby

Tweeting from Ruby requires a POST request, instead of a GET request. This is almost the same, the only difference is the Net::HTTP::Post class is used and there's an extra step to set the form data. The only form data here is the status field, which is set to the value of the first argument passed to the script. If you're not running this from the command-line, replace this with anything you wish.

The API command for posting an update is /statuses/update.xml. This command will only be successful if you're properly authenticated, if the request is a POST request, and if there is a valid status field. The final few lines of the script accomplish this. With the twitter function, accessing any Twitter features are at most 4 lines of code!

Since most of the work is done by the twitter method discussed in the previous article, you'll probably want to skip to the bottom, where the actual update is posted.

 #!/usr/bin/env ruby
 require 'rubygems'
 require 'hpricot'
 require 'net/http'
 
 $username = 'aboutruby'
 $password = 'pass123'
 
 def twitter(command, opts={}, type=:get)
   # Open an HTTP connection to twitter.com
   twitter = Net::HTTP.start('twitter.com')
 
   # Depending on the request type, create either
   # an HTTP::Get or HTTP::Post object
   case type
   when :get
     # Append the options to the URL
     command << "?" + opts.map{|k,v| "#{k}=#{v}" }.join('&')
     req = Net::HTTP::Get.new(command)
 
   when :post
     # Set the form data with options
     req = Net::HTTP::Post.new(command)
     req.set_form_data(opts)
   end
 
   # Set up the authentication and
   # make the request
   req.basic_auth( $username, $password )
   res = twitter.request(req)
 
   # Raise an exception unless Twitter
   # returned an OK result
   unless res.is_a? Net::HTTPOK
     doc = Hpricot(res.body)
     raise "#{(doc/'request').inner_html}: #{(doc/'error').inner_html}"
   end
 
   # Return the request body
   return Hpricot(res.body)
 end
 
 xml = twitter(
   '/statuses/update.xml',
   { 'status' => ARGV[0] },
   :post
 )
 
 puts xml
 
  1. About.com
  2. Technology
  3. Ruby
  4. Networking
  5. Twitter--How to Tweet From Ruby

©2014 About.com. All rights reserved.