落書きノート

ふと自分が気になった事を書いてます

RubyでラッパーなしにTwitter APIを扱う。user_timeline.jsonを利用する。

こんな感じになりました。json便利ですね。

require 'net/http'
require 'uri'
require 'base64'
require 'json'

url_oauth2 = "https://api.twitter.com/oauth2/token"
url_usertimeline = "https://api.twitter.com/1.1/statuses/user_timeline.json?count=100&screen_name=your_account_name"
consumer_key = "your_consumer_key"
consumer_secret_key = "your_consumer_secret_key"
bearer_token = consumer_key + ":" + consumer_secret_key
base64_bearer_token = Base64.strict_encode64(bearer_token)

uri = URI.parse(url_oauth2)
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req["Authorization"] = "Basic #{base64_bearer_token}"
req["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8"
req.body = "grant_type=client_credentials"
res = https.request(req)

res_json = JSON.parse(res.body)

req = Net::HTTP::Get.new(url_usertimeline)
req['Authorization'] = "Bearer #{res_json["access_token"]}"
res = https.request(req)

res_json = JSON.parse(res.body)

res_json.each do |status|
  puts status['text']
end

%e3%82%b9%e3%82%af%e3%83%aa%e3%83%bc%e3%83%b3%e3%82%b7%e3%83%a7%e3%83%83%e3%83%88-2016-09-16-14-06-21