RubyからTwitter APIを呼び出してツイッターのトレンド情報を取得するプログラム
require 'open-uri'
require 'json'
require 'timeout'
json = nil
begin
timeout(10) {
url = "http://api.twitter.com/1/trends/23424856.json"
json = URI(url).read
}
rescue Timeout::Error
puts "サーバーに接続出来ませんでした。"
rescue
puts "サーバーに接続出来ませんでした。"
else
hash = JSON.parse(json)
hash[0]["trends"].each { |trends|
name = trends["name"]
print(name,"\n")
}
end
RubyからTwitter APIを呼び出して検索文字列にヒットしたツイートを表示するプログラム
require 'open-uri'
require 'json'
require 'timeout'
class Twit
def initialize
@usr = "";
@date = ""
@text = ""
end
def SetItem(section)
@user = section["from_user"]
@date = section["created_at"]
@text = section["text"]
end
def DispItem
print(@user," ",@date,"\n")
print(@text,"\n")
end
end
def getTwitJson(search,page)
begin
timeout(10) {
url = "http://search.twitter.com/search.json?q=" + URI.encode(search) + "&rpp=100" + "&page=" + page.to_s
twitJson = URI(url).read
return twitJson
}
rescue Timeout::Error
puts "Timeout Error"
return nil
rescue
puts "サーバーに接続出来ませんでした。"
return nil
end
end
def getTwitItem(twitJson,twit)
loop = 1
hash = JSON.parse(twitJson)
hash["results"].each { |section|
twit.SetItem(section)
twit.DispItem
key = gets.chomp
if key == "q"
loop = 0;
break;
end
}
return loop
end
print("検索文字 = ")
search = gets.chomp
twit = Twit.new
page = 1
while true
twitJson = getTwitJson(search,page)
if twitJson == nil
break;
else
if getTwitItem(twitJson,twit) == 0
break;
end
end
print("最新:0 次ページ:1 終了 : q = ");
key = gets.chomp
if key == "1"
page += 1
elsif key == "q"
break;
else
page = 1
end
end