Skip to content

Instantly share code, notes, and snippets.

@m0wfo
Created June 18, 2011 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m0wfo/1033130 to your computer and use it in GitHub Desktop.
Save m0wfo/1033130 to your computer and use it in GitHub Desktop.
Quick Twitter client
require "openssl"
require "base64"
require "securerandom"
require "httparty"
require "cgi"
class Twitter
def self.escape(value)
CGI.escape(value.to_s).gsub("%7E", '~').gsub("+", "%20")
end
# Direct message endpoint
def self.dm
'https://api.twitter.com/1/direct_messages/new.json'
end
def self.get_header
params = {
:oauth_consumer_key => 'app_consumer_key',
:oauth_nonce => SecureRandom.hex(16),
:oauth_signature_method => 'HMAC-SHA1',
:oauth_timestamp => Time.now.to_i.to_s,
:oauth_token => 'oauth_token',
:oauth_version => '1.0'
}
status = escape("screen_name=screenname&text=foobar&user_id=123456")
base_string = 'POST&' + escape(dm) + '&' + params.map { |w| w[1] = escape(w[1]); w.join('%3D') }.join('%26') + status
p base_string
key = 'key&secret'
signature = escape(Base64.encode64(OpenSSL::HMAC.digest('sha1', key, base_string)).chomp)
header = 'OAuth ' + params.merge(:oauth_signature => signature).map { |e| e[0].to_s + '="' + e[1] + '"' }.join(', ')
header
end
include HTTParty
headers 'Authorization' => get_header
headers 'Content-Type' => 'application/x-www-form-urlencoded'
end
req = Twitter.post(Twitter.dm, {:body => {:screen_name => 'screenname', :text => 'foobar', :user_id => "123456"}})
p req
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment