Twitter Script with Snarl

I am going to start following some people on twitter. I haven't found any twitter clients that just notify you when new status come in -- the way that I want, so I wrote one. To use, you need ruby, Snarl, and you see the ruby gem dependencies(twitter, ruby-snarl, json, hpricot). And curl, you'll need curl, you can get it here or get it with cygwin. And then you need a .twitter a the top of your home directory that is a YAML doc consisting of email and password key and value pairs, then you need up set up a scheduled job to run it periodically(btw, make sure you use rubyw.exe instead of ruby.exe so that the command window doesn't showup...yes, this is windows only) =):

require 'rubygems'
require 'twitter'
 'snarl'
require 'json'
require 'yaml'
require 'fileutils'

home = (ENV['USERPROFILE'] || ENV['HOMEPATH']).gsub(/\\/, '/')
TWITTERME_DIR = home + '/.twitterme'
config = YAML::load open(home + "/.twitter")
SAVE_FILE = TWITTERME_DIR + '/current_statuses'

def save status
    open(SAVE_FILE,'w') do |f|
        f.write(to_map(status).to_json)
    end
end

def to_map current
    map = {}
    current.each do |f|
        map[f.id] = { :user => f.name, :status => f.status.text, :status_id => f.status.id }
    end
    map
end

def whats_new old, current
    if old.nil? then return current end
    new_stuff = []
    current.each do |f|
        if old[f.id].nil? or old[f.id]['status'] != f.status.text
            new_stuff << f
        end
    end
    new_stuff
end

def picture_path friend
    "#{TWITTERME_DIR}/#{friend.id}.png"
end

def download_picture friend
    puts "downloading picture for #{friend.name}"
    system %|curl "#{friend.profile_image_url}" > "#{TWITTERME_DIR}/#{friend.id}.png"|
end

def has_picture? friend
    File.exist?("#{TWITTERME_DIR}/#{friend.id}.png")
end

def initAppDir
    if not File.exist?(TWITTERME_DIR) then
        FileUtils.mkdir(TWITTERME_DIR)
    end
end

begin
    initAppDir
    friends = Twitter::Base.new(config['email'], config['password']).friends
    friends.each do |f|
       if not has_picture?(f) then
           download_picture f
       end
    end
    saved_status = JSON.parse(open(SAVE_FILE) { |f|f.read() }) unless not File.exist?(SAVE_FILE)
    save(friends)
    whats_new(saved_status, friends).each do |u|    
        Snarl.show_message u.name, u.status.text, picture_path(u), 40
    end
rescue Exception
    Snarl.show_message 'TwitterMe Error', ($!).to_s, nil, Snarl::NO_TIMEOUT
end

Update: Added support for profile images
Update #2: bug fix(adding new friend breaks it), added error handling if something goes wrong - it gives you a popup to let you know

blog comments powered by Disqus