Mechanize 版 はてダラ

  • config.txt
@id          = "xxxxx"
@password    = "xxxxx"
#@proxy_addr = "proxy.xxx"
#@proxy_port = 80
  • hatedara.rb
require 'rubygems'
require 'mechanize'
require 'optparse'

@agent = WWW::Mechanize.new

PConfig = Hash.new
opts = OptionParser.new
opts.on("-t"){|v| PConfig[:t] = true ; puts "trivial update on"} 
opts.parse!(ARGV)  

def eval_config
  eval open("config.txt"){|file| file.read}
  if @proxy_addr 
    puts "set proxy -> " + @proxy_addr + ":" + @proxy_port.to_s
    @agent.set_proxy(@proxy_addr , @proxy_port) 
  end
end
def login
  login_page  = @agent.get('https://www.hatena.ne.jp/login')
  login_form  = login_page.forms.first
  login_form["name"]       = @id
  login_form["password"]   = @password
  login_form["persistent"] = "true"
  res = login_form.submit
  if res.body =~ /.*error-message"\>.*\<p\>(.*?)\<\/p\>.*\<\/div\>/m
    puts "login error to " + @id
    exit
  else
    puts "login to " + @id
  end
end
def post
  time = touch_time
  Dir.foreach("."){|file|
    next if file !~ /\d\d\d\d-\d\d-\d\d\.txt/
    if File.stat(file).mtime.strftime("%Y%m%d%H%M%S") > time
      print "post " + file + " ... "
      edit_uri = 'http://d.hatena.ne.jp/' + @id  + '/edit'
      edit_page = @agent.get('http://d.hatena.ne.jp/' + @id  + '/edit')
      edit_form = edit_page.forms.first
      date = file.split("-")
      edit_form["year"]  = date[0]
      edit_form["month"] = date[1]
      edit_form["day"]   = date[2].sub(".txt","")
      body = open(file){|file| file.read.split("\n",2)}
      edit_form["title"] = body[0]
      edit_form["body"]  = body[1]
      if PConfig[:t]
        edit_form["trivial"] = "true"
      end
      edit_form.submit
      puts "end"
    end
  }
end
def touch_time
  if File.exist?("touch.txt")
    open("touch.txt"){|file| file.read}
  else
    Time.now.strftime("%Y%m%d%000000")
  end
end
def edit_touch_time
  open("touch.txt","w") {|file| file.puts Time.now.strftime("%Y%m%d%H%M%S")}
end

eval_config
login
post
edit_touch_time
  • 実行
ruby hatedara.rb
ちょっとだけ更新する場合
ruby hatedara.rb -t

テスト環境 : ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-cygwin]