mixiボイスに書き込むスクリプト

とりあえずRuby1.9.1とRuby1.8.7で動いたので載せる。特に設計とか考えずに書いたのでまだ改善の余地あり。

# vim:set fileencoding=UTF-8:

require 'net/http'
require 'uri'

class MixiVoice
  def initialize mail,pass,key
    @cookie = ""
    @key = key
    @req = Net::HTTP.start "mixi.jp"
    login mail,pass
  end

  def login mail,pass
    res = @req.post "/login.pl", "email=#{mail}&password=#{pass}&next_url=/home.pl"
    @cookie = res["set-cookie"].split(",").join(";")
  end

  def add_echo text
    res = @req.post "/add_echo.pl", "body=#{encode_text(text)}&post_key=#{@key}&redirect=recent_echo", "cookie" => @cookie
    res.code
  end

  def encode_text text
    euc = ""
    if RUBY_VERSION > "1.9"
      euc = text.encode "EUC-JP"
    else
      require 'kconv'
      euc = Kconv.toeuc text
    end
    URI.encode(euc)
  end
end

if __FILE__ == $0
  require "rubygems"
  require "pit"

  conf = Pit.get "mixi"
  vo = MixiVoice.new conf["mail"],conf["pass"],conf["post_key"]
  res = vo.add_echo "Hello,world!"
  puts res
end

MixiVoice#add_echoは302が返ってきたらOKです。200だと失敗。