2009/03/04

@LastFmRankの週刊ランキング機能をRuby化

関連:[-*煙猴*-] @LastFmRankをRuby化

@LastFmRankの週刊ランキング機能もRuby化。連想配列周りで結構手こずりました。


#! /usr/bin/ruby -Ku

require 'rubygems'
gem 'twitter4r'
require 'time'
require 'twitter'
require 'pit'

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

require 'kconv'
$KCODE = "UTF8"

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

begin
userlist = Array.new
tracks = Hash.new
list = Array.new

doc = Nokogiri::HTML(open('http://twitter.g.hatena.ne.jp/keyword/Last.fm%E9%83%A8'))
doc.xpath('//a[@href]').each do |href|
user = href.get_attribute("href")
if user =~ /.*http:\/\/www\.last.*\/user\// then
user.gsub!(/.*\/user\//,"")
user.gsub!(/\//,"")
userlist << user
end
end

apikey = "APIKEY"
userlist.each do |uname|
begin
open('http://ws.audioscrobbler.com/2.0/?method=user.weeklyartistchart&user=' + uname + '&api_key=' + apikey) do |http|
xml = http.read
doc=nil
doc=REXML::Document.new xml
artist = doc.elements['/lfm/weeklyartistchart/artist/name'].text
tracks[artist] = tracks[artist].to_i + doc.elements['/lfm/weeklyartistchart/artist/playcount'].text.to_i
end
sleep 3
rescue
next
end
end

list = tracks.to_a
list.sort! {|x,y| y[1] <=> x[1]}
config = Pit.get("LastFmRank")
cl = Twitter::Client.new(config)
9.downto(0) do |i|
j = i+1
txt = "今週のついったー部週間アーティスト 第" + j.to_s + "位! 【" +list[i][0] + "】 play count:" + list[i][1].to_s
mess = Kconv.kconv(txt,Kconv::UTF8)
cl.status(:post,mess)
sleep 60
end

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