Tuesday, January 19, 2010

Twitter API And Extending Rails Contacts Gem To Invite Friends

Introduction:

Yet to install contacts gem?
OR, how to get it to play as plugin?
Follow this link...
Extending Ruby on Rails Contacts Gem to invite Facebook users
Got through?
Put twitter.rb into "#{RAILS_ROOT}/vendor/plugins/contacts/lib/contacts" containing...
class Contacts
 class Twitter < Base
  
  URL = "http://twitter.com"
  LOGIN_URL = "http://twitter.com/account/verify_credentials."
  ONTACT_URL = "http://twitter.com/statuses/friends."
  DMESSAGE_URL = "http://twitter.com/direct_messages/new."
  LOGOUT_URL = "http://twitter.com/account/end_session."
  PROTOCOL_ERROR = "Twitter has changed its protocols, please upgrade this library."
    
  def real_connect
   format = 'xml'
   api_url = LOGIN_URL + format
   url = URI.parse(api_url)
   req = Net::HTTP::Get.new(url.path)
   req.basic_auth(@login, @password)
   resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
     
   if resp.code_type == Net::HTTPUnauthorized
    raise AuthenticationError, "Username and password do not match!"
   elsif resp.code_type != Net::HTTPOK
    raise ConnectionError, PROTOCOL_ERROR
   end
     
   return true
  end
   
  def contacts
   format = 'json'
   api_url = CONTACT_URL + format
   url = URI.parse(api_url)
   req = Net::HTTP::Get.new(url.path)
   req.basic_auth(@login, @password)
   resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
     
   if resp.code_type != Net::HTTPOK
    raise ConnectionError, PROTOCOL_ERROR
   end
      
   data = resp.body
   data = Contacts.parse_json(data) if data
   return [] if data.empty?
   contacts = []
   data.each do |d|
    contacts << [d['name'],d['id']]
   end
   return contacts
      
  end
   
  def send_message(contact, msg, format = 'json')
   return "Direct Message must been less than 140 characters." if msg && msg.length > 160
   return "Direct Message must have something in it..." if msg.nil? || msg.length < 1
     
   api_url = DMESSAGE_URL + format
   url = URI.parse(api_url)
   req = Net::HTTP::Post.new(url.path)
   req.basic_auth(@login, @password)
   req.set_form_data({'user' => contact.last, 'text'=> msg }, '&')
   resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
   return true if resp.code_type == Net::HTTPOK
   return false
  end
   
  def logout
   #...
  end
   
 end
 TYPES[:twitter] = Twitter
end
We also need to pick appropriate JSON, if we are getting contacts in json format.
# Use ActiveSupport's version of JSON if available
if !Object.const_defined?('ActiveSupport')
  require 'json/add/rails'
end

class Contacts
  def self.parse_json(string)
    if Object.const_defined?('ActiveSupport') && ActiveSupport.const_defined?('JSON')
      ActiveSupport::JSON.decode(string)
    elsif Object.const_defined?('JSON')
      JSON.parse(string)
    else
      raise 'Contacts requires JSON or Rails (with ActiveSupport::JSON)'
    end
  end
end
Don't forget to add this into lib/contacts.rb
require 'twitter'
Done!

Usage

C:\Me\Workspace\contacts>ruby script/console
Loading development environment (Rails 2.3.4)
>> twitter=Contacts::Twitter.new('twitter-id','password')
...
...
>> contacts = twitter.contacts
=> [["Jeremy Piven", 20221159], ["The Next Web", 10876852], ["bob saget", 38536306], ["Joel Stein", 24608680], ["Moin Haidar", 38841828]]
>> contacts.each{|c|twitter.send_message(c, 'Your Message')}
All should be well :)

1 comment: