Sending Twitter status updates with Ruby

Although there is a Twitter-gem to talk to the Twitter webservices you can save that dependency. The interface of the Twitter update service is very simple so you can update Twitter accounts very easily without a library.

Here is the code I use for sending updates of my little weather station to my twitter account. You get the response from the Twitter service as a Ruby hashtable for easy access.

#!/usr/bin/ruby

require 'net/http'
require 'uri'

def sendtwitter(userid,password,status)
  url=URI.parse('http://twitter.com/statuses/update.json')
  req=Net::HTTP::Post.new(url.path)
  req.basic_auth(userid, password)
  req.set_form_data({'status'=> status},';')

  res=Net::HTTP.new(url.host,url.port).start {|http| http.request(req)}

  case res
  when Net::HTTPSuccess, Net::HTTPRedirection
    null=nil; jsonobj = eval(res.body.gsub(/(["'])\s*:\s*(['"0-9tfn\[{])/){"#{$1}=>#{$2}"})
    jsonobj
  else
    res.error!
  end
end

puts sendtwitter('userid','password','Teststatus')['id']

Post new comment

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.