atomutilを使ってrubyでライブドアのブログに投稿する方法
前回は、rubyではてなダイアリーに投稿しました(atomutilを使ってrubyではてなダイアリーに投稿する方法 - 水清無魚(すいせいむぎょ))。
なので、こんどはライブドアのブログに投稿してみたいと思います。
ちなみに、ライブドアのブログもAtomPubで投稿ができるので、atomutilを使用します。
基本的には、はてなダイアリーの時と同じなんですが、カテゴリの設定などのために、見る人から見れば突っ込みどころ満載のことをしていますが、そのあたりは適宜好みの方法に変更してください。
# -*- coding: utf-8 -*- # @see : http://d.hatena.ne.jp/lyokato/20071211/1197353609 # gem install atomutil require 'atomutil' require 'cgi' # Livedoorブログやアメブロ対策のためオーバーライドし、戻り値としてLocationではなくステータスコードを返却するようにする class Atompub::Client def create_entry(post_uri, entry, slug=nil) unless entry.kind_of?(Atom::Entry) entry = Atom::Entry.new :stream => entry end service = @service_info.get(post_uri) # Livedoorブログの場合、serviceが取得できなくてservice.allows_category?でエラーになるので、if serviceでくくる if service unless entry.categories.all?{ |c| service.allows_category?(c) } raise RequestError, "Forbidden Category" end end create_resource(post_uri, entry.to_s, Atom::MediaType::ENTRY.to_s, slug) return @res.code rescue Atompub::ResponseError #=> rs # アメブロでは正常に投稿できても@res['Location']が空になってResponseErrorになるので捕獲する return @res.code end end # カテゴリを設定するためにオーバーライド class REXML::Attribute alias :_to_s :to_s def to_s value = _to_s value = value.encode("BINARY", "BINARY") if value.encoding != "UTF-8" return value end end def entry(id, password, title, content, category=nil) auth = Atompub::Auth::Wsse.new :username => id, :password => password client = Atompub::Client.new :auth => auth # ライブドアブログの場合は、自動改行にはならない(ブログ側の設定次第?) content = content.gsub(/\n/, '<br/>'); # ライブドアブログの場合は、htmlのescapeも必要 content = CGI.escapeHTML(content) new_entry = Atom::Entry.new new_entry.title = title.encode("BINARY", "BINARY") new_entry.content = content.encode("BINARY", "BINARY") if category new_category = Atom::Category.new new_category.term = category new_entry.category = new_category end puts new_entry return client.create_entry("http://livedoor.blogcms.jp/atom/blog/#{id}/article", new_entry) end title = "テスト" content =<<EOM <b>太字ですか?</b> 改行されていますか? EOM category = 'ツール' puts entry('<ログインID>', '<API KEY(※1)>', title, content, category)
※1)API KEYはブログ管理画面のブログ設定>その他>API Keyから確認できます。API KEYは半角英数字10字です。
以下のサイトを参考にしました。ありがとうございました。