<< Back
Next >>

Google リーダーのメモを Tweet する

2010-07-25 22:04 JST @sadayuki

Google リーダーのメモから Tweet を作成するサービスである Reader2Twitter を使っている。これは便利なのだが、時々、更新が止まる。どこが具合が悪いのか不明である。なので、自作してみることにした。

SADAYUKI の共有アイテム のページに、Atom フィード のリンクがある。ここのフィードの更新を監視して、更新があれば Tweet することを考えた。どこまで Tweet したか記録するために、DB を使うことに。最近の個人的なブームである Sinatra + Active Record 。で、DB 定義。

class CreateNotes < ActiveRecord::Migration
  def self.up
    create_table :notes do |t|
      t.string :title, :google_id, :tweet_id, :content, :uri

      t.timestamps
    end
    add_index :notes, :google_id, :unique => true
  end

  def self.down
    drop_index :notes, :google_id
    drop_table :notes
  end
end

open-uri を使って Atom フィードの URL をオープンし、feed を XML 形式で取得する。で、あとは取得した XML をパースして DB に格納する。

url = 'http://www.google.com/reader/public/atom/user/09691029617997612992/state/com.google/broadcast'
doc = REXML::Document.new(open(url).read)
REXML::XPath.each(doc, '//entry') do |e|
  n = Note.new
  n.google_id = e.elements["id"].text
  n.title = e.elements["title"].text
  n.content = e.elements["gr:annotation/content"].text
  n.uri = e.elements["link[@rel='alternate']/@href"].value
  n.save
end

ノートの内容が [/feed/entry/gr:annotation/content] 。サイトの URL が [/feed/entry/link[@rel='alternate']/@href] 。タイトルが [/feed/entry/title] 。Tweet したノートには id を入力するので、tweet_id が入っていないレコードを検索して Tweet する。

Note.find(:all, :conditions=>{:tweet_id => nil}).each do |n|
  begin
    res = rubytter.update("#{n.content} :: #{n.title} - #{shorten(n.uri)}")
    n.tweet_id = "#{res.id}"
    n.save
  rescue Rubytter::APIError
    # エラーの場合長すぎたと判断してタイトルを除いて再度Tweet
    res = rubytter.update("#{n.content} - #{shorten(n.uri)}")
    n.tweet_id = "#{res.id}"
    n.save
  end
end

記事の URL は bit.ly で短縮するが、それでも長すぎる場合がある。なので、エラーが出たら長すぎると判断しているが、クジラだった場合はエラーになってしまう。ここはもう少し工夫が必要。

まあ、動くから良しとしよう。ひとまずね。

id: 1427/
uuid: 963a064a-7549-4982-9b7c-324d00e1285d
tag:
permalink: /20100725/google_リーダーのメモを_tweet_する
tweet: 19494864028

<< Back
Next >>

Google 検索

フィード

Amazon

最近 1ヶ月の投稿

過去の投稿

Amazon アソシエイト

Google AdSense

楽天アフィリエイト