twitterの発言をmixiエコーにコピーするrubyスクリプト

自分の発言をコピーするrubyスクリプト作りました。

#!/usr/local/bin/ruby

$KCODE = 'u'
require 'rubygems'
require 'mechanize'
require 'twitter'
require 'kconv'
require 'net/http'
require 'cgi'
require 'yaml'
require 'optparse'

class Twitter2Mixi

  def initialize
    Net::HTTP.version_1_2
    option_parse
    set_options
    twitter_base
    twitter_update
  end

  def option_parse
    @option_parameter = Hash.new
    opt = OptionParser.new
    opt.on("-c", "--configfile=CONFIGFILE") {|v| @configfile = v }
    opt.on("-e", "--email=EMAIL") {|v| @option_parameter[:email] = v }
    opt.on("-p", "--password=PASSWORD") {|v| @option_parameter[:password] = v }
    opt.on("-d", "--debug") {|v| @debug = true}
    opt.parse(ARGV)
  end

  def set_options
    @configfile ||= File.join(File.dirname(__FILE__), "config.yaml")
    yaml = YAML.load(File.read(@configfile))
    account = yaml["account"] || Hash.new
    account.each do | key, value | 
      @option_parameter[key.to_sym] ||= value
    end
  end

  def twitter_base
    httpauth = Twitter::HTTPAuth.new(@option_parameter[:email], @option_parameter[:password])
    @twitter = Twitter::Base.new(httpauth)
  end

  def twitter_update
    timelines = @twitter.user_timeline(:since => CGI.escape("Sat Mar 13 05:29:08 +0000 2010"))
    last_time = get_last_time
    timelines.reverse.each do | s | 
      now_time = Time.parse s.created_at
      unless last_time >= now_time
        last_time = now_time
        unless /(^@)|(RT)|(QT)/ =~  s.text
          sendmixi(s.text)
          puts "send #{ s.text}" 
        end
      end
    end
    @timefile ||= File.join(File.dirname(__FILE__), "timefile")
    file =  File.open(@timefile, "w")
    file.puts last_time
    file.close
  end
 
  def get_last_time 
    @timefile ||= File.join(File.dirname(__FILE__), "timefile")
    time_string =  File.read(@timefile)
    Time.parse(time_string) 
  end

  def sendmixi(text)
    mixi_login unless @mixi_login 
    page = @mixi_login.get("http://mixi.jp/recent_echo.pl")
    form = page.forms[2]
    form['body'] = text.toeuc
    form.submit
  end

  def mixi_login
    @mixi_login = WWW::Mechanize.new()
    page = @mixi_login.get("http://mixi.jp/")
    form = page.forms.first
    form['email'] = @option_parameter[:mixi_email] 
    form['password'] = @option_parameter[:mixi_password]
    form.submit
 end
end
Twitter2Mixi.new

こちらを保存して
プログラムのファイルと同じディレクトリにconfig.yamlという名前で

account: 
  email: twitterのメアド
  password: twitterのパスワード
  mixi_email: mixiのメアド
  mixi_password: mixiのパスワード

と記載して保存してやればOKです
一時ファイルとしてtimefileって名前のファイルが出来ます。
前回実行した時間を記録しておいて、新しい発言だけコピーする様にしてます。


だいぶ前に小江戸らぐの活動報告会中に作ったんだけど今更公開。