Twittering Around in Ruby

Written on 6:37:00 PM by S. Potter

I just spent 2 minutes hacking around with twitter.com and thought I would share since a friend of mine wanted to use twitter to automate a few tasks for his websites in a similar vain to Urban Dictionary's use of twitter: require 'net/http' require 'uri' require 'json' HOST='twitter.com' PORT=80 URI='/statuses/friends_timeline.json' Net::HTTP.start(HOST, PORT) do |http| request = Net::HTTP::Get.new(URI) request.basic_auth('login', 'password') response = http.request(request) #Do something with the response. puts "Code: #{response.code}" puts "Message: #{response.message}" puts "Body:\n #{response.body}" # to parse the JSON do something like: #hash = JSON.parse(response.body) #and then do something with it. end Prep work before you run this Ruby code is:

$ sudo gem install json
WARNING: The fastest Rails application on the web, Twitter aint! I tried running against SSL, but got timed out too many times to test. Though if you aren't having problems you can try the SSL version of the code: require 'net/https' require 'uri' require 'json' HOST='twitter.com' PORT=443 URI='/statuses/friends_timeline.json' http = Net::HTTP.new(HOST, PORT) http.use_ssl = true http.start do |http| request = Net::HTTP::Get.new(URI) request.basic_auth('login', 'password') response = http.request(request) #Do something with the response. puts "Code: #{response.code}" puts "Message: #{response.message}" puts "Body:\n #{response.body}" # to parse the JSON do something like: #hash = JSON.parse(response.body) #and then do something with it. end You will get a warning when running it like the following:
warning: peer certificate won't be verified in this SSL session
Though if you refer to the Net::HTTP rdoc you will find how to work with this if you wish. I should also mention that you can edit the URI to the following values to get at different types of data:
  • /statuses/public_timeline.json - JSON representation of public timeline on twitter
  • /statuses/friends.json - JSON representation of friends and their current messages on twitter
  • /statuses/followers.json - JSON representation of your followers and current messages on twitter
Two things to note with the above:
  1. By substituting .json with .xml twitter will send back XML format.
  2. /statuses/update.json can be used in a HTTP POST request sent with a status=message+url+encoded name-value pair to update your own status. To accomplish this you will just need to swap out the request = Net::HTTP::GET.new line of code with something like the following:   request = Net::HTTP::Post.new(URI, {'status' => 'my new message'})
Hope this helps!

If you enjoyed this post Subscribe to our feed

No Comment

Post a Comment