Simple Twitter client (fetch twits only) with ruby

Do you twitter? lots of follower? following others a lot? feeling lazy just to open twitter just to find the latest twits? I know I do…
Then I got this idea “it’ll be nice to have a program that let you know whenever there are new twits without the need to open twitter“…
Also, I want the program to be really simple, just pop up a notification on ubuntu system tray ( I’m using ubuntu 8.10 ) and written in ruby
And so I found this ruby-libnotify that do just what I want, along with ruby twitter gem. After looking at the ruby-libnotify and twitter gem examples, I come up with this script. Basically it just going to loop forever (sleep for 5 minutes for each loop) and fetch the latest twits and display those twits with the notification bubble on ubuntu system tray, I find this quite handy :)
This script could use some improvement though…

#!/usr/bin/ruby

require 'rubygems'
require 'twitter'
require 'RNotify'

email = 'your-email@example.com'
password = 'your-twitter-password'

class LatestTwit
  def initialize(twit)
    @twit = twit
    @first = true
    @retry = 0
    @latest_twits = nil
  end

  def latest
    begin
      if @first
        @first = false
        @latest_twits = @twit.timeline
        @latest_id = @latest_twits.first.id
      else
        new_twits = @twit.timeline
        ids = new_twits.collect { |t| t.id }
        index = ids.index(@latest_id)
        @latest_id = new_twits.first.id
        @latest_twits = new_twits[0...index]
      end
      @latest_twits

    rescue Twitter::CantConnect
      @retry = @retry.next
      puts 'retry #{@retry}'
      exit if @retry > 3
      []
    end
  end

end

twitter = LatestTwit.new(Twitter::Base.new(email,password))
while true
  twits = twitter.latest
  unless twits.empty?
    msg = ''
    twits.each do |twit|
      msg << "#{twit.user.name}\n#{twit.text}\n\n"
    end
    Notify.init('twitter_notification')
    notify = Notify::Notification.new("Latest Twit", msg, nil, nil)
    notify.timeout= Notify::Notification::EXPIRES_NEVER
    notify.show
    sleep(10)
    notify.close
    Notify.uninit
  end
  sleep(300)
end

improvement are more than welcome… :)

latest-twit screenshot

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s