#!/usr/bin/ruby -Ku require 'rubygems' require 'twitter' # マニュアルはhttp://route477.net/w/?RubyTwitterJa require 'time' require 'uri' require 'open-uri' UNAME = "TeX_Eq" PASSWD = "xxxxxxxxxxxxxxx" CACHE_FNAME = 'texeq_cache.dat' cache_data = {} if FileTest::exist?(CACHE_FNAME) then open(CACHE_FNAME){|io| cache_data = Marshal::load(io.read) } end last_tweet_time = cache_data[:last_tweet_time] || (Time::now - 24 * 60 * 60) httpauth = Twitter::HTTPAuth.new(UNAME, PASSWD) client = Twitter::Base.new(httpauth) replies = client.replies.sort{|a, b| # 最新順に念のため並べ替え Time::parse(b[:created_at]) <=> Time::parse(a[:created_at]) } replies.each{|tweet| if Time::parse(tweet[:created_at]) <= last_tweet_time then break end target = tweet[:user][:screen_name] next unless tweet[:text] =~ /@#{UNAME} */i eq = $' prefix = $` next if prefix =~ /RT:/ options = {} prefix.split(/ +/).each{|item| case item when 'RT' next when 'T' options['chf'] = 'bg,s,FFFFFF00' when /\d+(?:x\d+)?/ options['chs'] = $& end } options_str = '' unless options.empty? then options.each{|k, v| options_str += "#{k}=#{v}&"} end eq_url = "http://chart.apis.google.com/chart?cht=tx&#{options_str}chl=#{URI::escape(eq, /[^-_.!~*'()a-zA-Z\d?@]/n)}" eq_url.gsub!(/%23/, '%2523') eq_url.gsub!(/%3B/, '%253B') eq_url.gsub!(/%2B/, '%252B') begin shorten_url = OpenURI::open_uri("http://is.gd/api.php?longurl=#{eq_url}").read p shorten_url client.update("@#{target} #{shorten_url}") rescue p $! p $@ end } unless replies.empty? then cache_data[:last_tweet_time] = Time::parse(replies[0][:created_at]) end File::open(CACHE_FNAME, 'w'){|io| io << Marshal::dump(cache_data) }