Skip to content

Instantly share code, notes, and snippets.

@animist
Created June 3, 2013 11:50
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 animist/5697635 to your computer and use it in GitHub Desktop.
Save animist/5697635 to your computer and use it in GitHub Desktop.
Twitter のストリームを取得して垂れ流すサンプル
#!/usr/bin/env ruby
# coding: utf-8
#
# http://d.hatena.ne.jp/shibason/20090816/1250405491
# にあったものを https な 1.1 API に対応させた
require 'net/https'
require 'uri'
require 'rubygems'
require 'json'
require 'pp'
print "account: "
account = $stdin.gets.chomp
print "password: "
system "stty -echo"
pass = $stdin.gets.chomp
system "stty echo"
puts
uri = URI.parse('https://stream.twitter.com/1.1/statuses/sample.json')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
https.ca_file = '/System/Library/OpenSSL/cert.pem'
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
https.verify_depth = 5
https.start do
request = Net::HTTP::Get.new(uri.request_uri)
# Streaming APIはBasic認証のみ
request.basic_auth(account, pass)
https.request(request) do |response|
raise 'Response is not chuncked' unless response.chunked?
response.read_body do |chunk|
# 空行は無視する = JSON形式でのパースに失敗したら次へ
status = JSON.parse(chunk) rescue next
# 削除通知など、'text'パラメータを含まないものは無視して次へ
next unless status['text']
user = status['user']
puts "#{user['screen_name']}: #{status['text']}"
# pp status
end
end
end
@animist
Copy link
Author

animist commented Jun 3, 2013

Mac 以外で動くかは知らんよ。得に24行目

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment