Created
August 24, 2011 01:52
-
-
Save takuo/1167121 to your computer and use it in GitHub Desktop.
Twitterのoauthしてaccess tokenを取得するだけのスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# | |
# usage: | |
# ./twitter-oauth.rb <CONSUMER_KEY> <CONSUMER_SECRET> <user> <password> | |
# | |
require 'rubygems' | |
require 'oauth' | |
CONSUMER_KEY=ARGV[0] | |
CONSUMER_SEC=ARGV[1] | |
USER=ARGV[2] | |
PASS=ARGV[3] | |
def get_access_token( consumer, user, pass ) | |
rt = consumer.get_request_token | |
u = URI::parse( rt.authorize_url ) | |
http = Net::HTTP.new( u.host, u.port ) | |
http.use_ssl = true | |
req = Net::HTTP::Post.new( u.request_uri ) | |
res = http.request( req ) | |
raise RuntimeError, "HTTP: #{res.code}" if res.code != "200" | |
at = ot = nil | |
res.body.each_line do |line| | |
if /name="authenticity_token" type="hidden" value="([^"]+)"/ =~ line | |
at = $1 | |
end | |
if /name="oauth_token" type="hidden" value="([^"]+)"/ =~ line | |
ot = $1 | |
end | |
break if at && ot | |
end | |
raise RuntimeError, "Could not get tokens" if at.nil? or ot.nil? | |
query = [ "authenticity_token=#{at}", | |
"oauth_token=#{ot}", | |
"session[username_or_email]=#{user}", | |
"session[password]=#{pass}", | |
"submit=Allow" ].join("&") | |
res = http.post( u.request_uri, query ) | |
raise RuntimeError, "HTTP: #{res.code}" if res.code != "200" | |
pin = nil | |
res.body.each_line do |line| | |
if /<code>(\d+)/ =~ line | |
pin = $1 | |
break | |
end | |
end | |
# puts "PIN: #{pin}" | |
raise RuntimeError, "Could not get PIN code" unless pin | |
token = rt.get_access_token( :oauth_verifier => pin ) | |
return token | |
end | |
params = { | |
:site => "https://api.twitter.com" | |
} | |
consumer = OAuth::Consumer.new( CONSUMER_KEY, CONSUMER_SEC, params ) | |
puts "CONSUMER_KEY : #{CONSUMER_KEY}" | |
puts "CONSUMER_SECRET: #{CONSUMER_SEC}" | |
at = get_access_token( consumer, USER, PASS ) | |
puts "ACCESS_TOKEN : #{at.token}" | |
puts "ACCESS_TOKEN_SECRET: #{at.secret}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment