Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Twitterのoauthしてaccess tokenを取得するだけのスクリプト
#!/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