Created
September 21, 2008 20:28
-
-
Save mislav/11897 to your computer and use it in GitHub Desktop.
Ruby script to fetch user's latest update from Twitter (for Adium integration)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## gets the latest Twitter update from a user | |
require 'rubygems' | |
require 'json' | |
require 'yaml' | |
require 'open-uri' | |
CONFIG_FILE = ENV["HOME"] + "/.twitter" | |
CACHE_FILE = "/tmp/.#{ENV["LOGNAME"]}_TwitterAdium.txt" | |
DEFAULTS = { 'interval' => 300, 'limit' => 3 } | |
unless File.exist?(CONFIG_FILE) | |
File.open(CONFIG_FILE, 'w') do |config| | |
config.write(<<-EOF) | |
username: | |
# in seconds: | |
interval: #{DEFAULTS['interval']} | |
# how many updates can be fetched at once while | |
# searching for an update that isn't an @-reply: | |
limit: #{DEFAULTS['limit']} | |
EOF | |
end | |
end | |
config = DEFAULTS.merge YAML::load(open(CONFIG_FILE)) | |
if config["username"].nil? | |
system %(open #{CONFIG_FILE.inspect}) | |
puts "[Twitter Adium]: Please edit your ~/.twitter file to contain your username" | |
exit(1) | |
end | |
if File.exist?(CACHE_FILE) | |
status_id, status_text = File.read(CACHE_FILE).split(' ', 2) | |
# is cache still fresh? | |
if File.mtime(CACHE_FILE) > Time.now - config['interval'] | |
puts status_text | |
exit(0) | |
end | |
else | |
status_id = status_text = nil | |
end | |
twitter_url = "http://twitter.com/statuses/user_timeline/#{config["username"]}.json?count=#{config['limit']}" | |
twitter_url += "&since_id=#{status_id}" if status_id | |
page = 1 | |
begin | |
updates = JSON.parse open(twitter_url + "&page=#{page}").read | |
status = updates.find { |update| update["text"].index('@') != 0 } | |
page += 1 | |
end while status.nil? and updates.length > 0 | |
if status | |
status_text = status["text"] | |
File.open(CACHE_FILE, 'w') { |f| f << status['id'] << ' ' << status_text } | |
end | |
puts status_text |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment