Skip to content

Instantly share code, notes, and snippets.

@mdaisuke
Created February 13, 2011 09:28
Show Gist options
  • Save mdaisuke/824563 to your computer and use it in GitHub Desktop.
Save mdaisuke/824563 to your computer and use it in GitHub Desktop.
require 'openssl'
require 'uri'
require 'net/http'
require 'yaml'
require 'pp'
app_info = YAML.load_file 'consumer_info.yml'
CONSUMER_KEY = app_info['consumer_key']
CONSUMER_SECRET = app_info['consumer_secret']
OAUTH_TOKEN = app_info['oauth_token']
OAUTH_TOKEN_SECRET = app_info['oauth_token_secret']
METHOD = 'POST'
UPDATE_URL = 'http://api.twitter.com/1/statuses/update.json'
def random_str
a = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
(Array.new(16){a[rand(a.size)]}).join
end
def sort_and_concat(params)
params.sort.map{|i|i.join("=")}.join("&")
end
def escape(str)
URI.escape(str,Regexp.new("[^a-zA-Z0-9._-]"))
end
def get_signature(params,method,url,oauth_token_secret=nil)
param_str = sort_and_concat(params)
value = [method,escape(url),escape(param_str)].join("&")
signature_key = "#{CONSUMER_SECRET}&#{oauth_token_secret.nil? ? "" : oauth_token_secret}"
sha1 = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, signature_key, value)
[sha1].pack('m').gsub(/\n/,'')
end
text = 'oppai'
params = {
"oauth_consumer_key" => CONSUMER_KEY,
"oauth_signature_method" => "HMAC-SHA1",
"oauth_timestamp" => Time.now.to_i.to_s,
"oauth_nonce" => random_str,
"oauth_version" => "1.0"
}
params['status'] = text
params['oauth_token'] = OAUTH_TOKEN
params['oauth_signature'] = escape get_signature(params,METHOD,UPDATE_URL,OAUTH_TOKEN_SECRET)
params.delete 'status'
uri = URI.parse(UPDATE_URL)
#proxy_class = Net::HTTP::Proxy(ARGV[0], 8080)
proxy_class = Net::HTTP::Proxy(nil, 8080)
http = proxy_class.new(uri.host)
http.start do |h|
param = sort_and_concat(params).gsub('&',',')
res = h.post(uri.path,"status=#{text}",{'Authorization' => "OAuth #{param}"})
if res.code == "200"
puts res.code
puts res.body
else
puts res.code
puts res.body
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment