2009/02/28

第7回北海道開発オフ成果:Google TrendのHottrendをTwitter投稿する

Google Trend 急上昇ワードを取得してParseして@dabesaに喋らせる。


#! /usr/bin/ruby -Ku

require 'open-uri'
require 'rexml/document'

require 'net/http'
require 'rubygems'
gem 'twitter4r'
require 'twitter'
require 'pit'

# Twitter4Rバグ回避
require 'cgi'
class Hash
def to_http_str
self.map{|key,value| "#{key}=#{CGI.escape(value.to_s)}"}.join("&")
end
end

# TinyURL化メソッド
def tinyurl(link)
url = "http://tinyurl.com/api-create.php?url=" + link
open(url) do |http|
res = http.read
return res
end
end

begin

uri="http://www.google.com/trends/hottrends/atom/hourly"
xml = open(uri).read
eventlist=Array.new

REXML::Document.new(xml).root.elements.each("entry") do |elm|
eventlist << elm.elements['content'].text.to_s
end

i = eventlist[0].index("href=")
i = i + 6
j = eventlist[0].index("&sa=X")
j = j + 4
url = eventlist[0][i..j]
turl = tinyurl(url)

i = eventlist[0].index("&sa=X")
i = i + 7
j = eventlist[0].index("<\/a>")
j = j - 1
keyword = eventlist[0][i..j]

mess = "[Now Hottrend!] \"" + keyword + "\" => " + turl

config = Pit.get("dabesa")
cl = Twitter::Client.new(config)
cl.status(:post,mess)

wmess = 'status=' + URI.escape(mess)
req = Net::HTTP::Post.new("/statuses/update.json?")
req.basic_auth "dabesa","PASSWORD"
Net::HTTP.start('api.wassr.jp',80) {|http|
response = http.request(req,wmess)
}

rescue
print "RuntimeError: ", $!, "\n";
end