Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active August 29, 2015 14:10
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 komasaru/6e5a2dadb59808b1e96f to your computer and use it in GitHub Desktop.
Save komasaru/6e5a2dadb59808b1e96f to your computer and use it in GitHub Desktop.
Ruby script to get tweet statuses by twitter-stream gem library.
#! /usr/local/bin/ruby
# coding: utf-8
#
# Ruby script to get tweet statuses by twitter-stream gem library.
#
require 'json'
require 'twitter/json_stream'
# Twitter OAuth keys
CONS_KEY = "<your_consumer_key>"
CONS_SEC = "<your_consumer_secret>"
ACCS_KEY = "<your_access_token_key>"
ACCS_SEC = "<your_access_token_secret>"
# EventMachine 実行
EventMachine::run do
stream = Twitter::JSONStream.connect(
host: "stream.twitter.com",
path: "/1.1/statuses/sample.json",
oauth: {
consumer_key: CONS_KEY,
consumer_secret: CONS_SEC,
access_key: ACCS_KEY,
access_secret: ACCS_SEC
},
ssl: true
)
stream.each_item do |item|
json = JSON.parse(item)
#p json; exit # <= JSON データの構造を知りたい場合はコメント解除
# "user" 存在しなければ次へ、
# 存在すれば "name", "screen_name", "text" を取得
next unless user = json["user"]
name, screen_name, text = user["name"], user["screen_name"], json["text"]
# "lang" が "ja" でなければ次へ
next unless user["lang"] == "ja"
# コンソール出力
puts "\n**** #{name} [ #{screen_name} ]"
puts text
end
stream.on_error do |message|
# No need to worry here. It might be an issue with Twitter.
# Log message for future reference. JSONStream will try to reconnect after a timeout.
end
stream.on_max_reconnects do |timeout, retries|
# Something is wrong on your side. Send yourself an email.
end
stream.on_no_data do
# Twitter has stopped sending any data on the currently active
# connection, reconnecting is probably in order
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment