Tweet active Safari tab from command line

Mar 09, '09 07:30:00AM

Contributed by: Anonymous

I wrote a small Ruby script which allows me to post my currently-active Safari tab on Twitter, including the possibility of adding hashtags. Here's the code, though you you'll find any updates to the script over here, and a bit more detail can be found in this blog post.

#!/usr/bin/ruby -W0
 
=begin
Quick and dirty way to tweet the currently active
Safari tab (title + shortened URL). Hashtags get
passed in as parameters (the hash sign gets added
by the script, so don't do it yourself)
 
Adapt to your needs!
=end
 
# I don't believe in requiring rubygems itself
#require 'rubygems'
require 'highline'
require 'rbosa'
require 'ShortURL'
gem('twitter4r', '0.3.0')
require 'time'
require 'twitter'
 
# OSA stuff to get to the active Safari tab
OSA.utf8_strings = true
tab = OSA.app('Safari').windows.first.current_tab
 
tweet = "#{tab.name} - #{ShortURL.shorten(tab.url)} "
ARGV.each { |tag| tweet << "##{tag} " }
 
unless tweet.length < 140
  puts "Tweet too long :-("
  exit 1
end
 
# I didn't feel like having my pw in the file
# therefore using highline to ask for it
hl = HighLine.new
twitter_user = 'your_twitter_username'
twitter_pass = hl.ask('Enter password: ') { |q| q.echo = "*" }
 
# post tweet
client = Twitter::Client.new(:login => twitter_user, :password => twitter_pass)
Twitter::Status.create(:text => tweet, :client => client)
This script uses the RubyOSA bridge for AppleScript support from within Ruby, as well as quite a few other gems (why reinvent the wheel?).

[robg adds: If (like me) you're not a Ruby user, it will take a bit of effort to get this script to work. First, save the above as a text file somewhere on your path and make it executable (chmod a+x tweetsafari.rb). In order to get it working on my machine, I had to uncomment the require 'rubygems' line, and edit the twitter_user = 'your_twitter_username'. I also had to install some of the listed gems from the script. You can do this with the sudo gem install gem_name command. On my machine, I had to install rubyosa, shorturl, and twitter4r in order to get the script to work. Once I had all those bits, though, it worked as described, and tweeted a shortened URL version of my active Safari tab.]

Comments (1)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20090305105308797