by shigemk2

当面は技術的なことしか書かない

はてなAPIを利用して投稿する

はてなのAPIを利用してエントリーを投稿してみた。
はてなダイアリーAtomPub - Hatena Developer Center

サンプルコードはこんな感じ。
atomutilをgem installしたらいいです。

hatena.rb

require 'rubygems'
require 'atomutil'

module Atompub
  class HatenaClient < Client
    def publish_entry(uri)
      @hatena_publish = true
      update_resource(uri, ' ', Atom::MediaType::ENTRY.to_s)
    ensure
      @hatena_publish = false
    end

    private
    def set_common_info(req)
      req['X-Hatena-Publish'] = 1 if @hatena_publish
      super(req)
    end
  end
end
auth = Atompub::Auth::Wsse.new :username => 'はてなID', :password => 'hatena_password'
client = Atompub::HatenaClient.new :auth => auth
service = client.get_service 'http://d.hatena.ne.jp/%s/atom' % 'はてなID'
collection_uri = service.workspace.collections[1].href

entry = Atom::Entry.new(
  :title => 'My Entry Title', # タイトル
  :updated => Time.now
)

# 本文
entry.content = <<EOF
エントリー本文だよ
EOF
puts client.create_entry collection_uri, entry

コードを見たらどこにタイトルと本文を入力したらいいか分かると思う。

で、

$ ruby hatena.rb

とすると、記事が投稿されます。