I post to identica through BarnOwl using Nelson's Twitter extension. This generally means I want to shorten URLs in my posts ("dents" as they're called on identica) so it's easier to fit them into the 140-character limit.

Luckily, BarnOwl can be extended using Perl, which, combined with some libraries from CPAN, makes this task simple. Here's the snippet I wrote:

package ShortenURLs;
use BarnOwl::Editwin qw(:all);
use Text::FindLinks;
use WWW::Shorten 'Bitly', qw(:short);

my $bitly_username = 'YOUR_BITLY_USERNAME_HERE';
my $bitly_apikey = 'YOUR_BITLY_APIKEY_HERE';

sub shorten_urls {
    my $text = save_excursion {
    my $linkified_text = Text::FindLinks::markup_links(
        text => $text,
        handler => sub {
            my ($url, $before, $after) = @_;

            my $short_link = q{};

            # hack around Text::FindLinks including trailing )
            # characters in URLs, which 99% of the time I don't
            # want, since it probably means I've surrounded the
            # link in parens
            if ($before =~ m/\($/ && $url =~ m/\)$/) {
                $url =~ s/\)$//;
                $short_link .= ")";

            return short_link($url, $bitly_username, $bitly_apikey).$short_link;


BarnOwl::new_command('shorten-urls' => \&shorten_urls);
BarnOwl::bindkey(edit => 'C-l' => command => 'shorten-urls');


You'll need a bit.ly account, and to enter your username and API key from that account in the relevant locations. Paste the snippet into e.g. ~/.owl/barnowl-shortenurls.pl, and add require "$ENV{HOME}/.owl/barnowl-shortenurls.pl"; to your ~/.owlconf.

It has a sort of ridiculous dependency chain that I am too lazy to cull, which you'll need to install, probably using cpan. I recommend using local::lib if you're installing without root. (I found this to be a pretty good walkthrough). Installing WWW::Shorten::Bitly and Text::FindLinks should pull in all relevant dependencies.

And that's it! Hit C-l in the editwin and all the links in it will be replaced with shortened versions.


Awesome! I've been wanting this for a while, and I know others have too.

Have you considered packaging this as a full-on BarnOwl module? It's totally something the Twitter module would want to depend on, in addition to it being available on its own.

Comment by kevinr [free-dissociation.com] Thu 15 Apr 2010 03:00:30 AM UTC
comment 2

Hmmmm, do you really think it's worth it? It sure ain't a lot of code. :) I guess having it lumped together with its dependencies would be useful.

One thing I want to add/fix is excluding bit.ly URLs themselves from the shortener--sucks when you accidentally hit the shortening keybinding twice and lose your links!

Comment by christine-spang [myopenid.com] Fri 16 Apr 2010 04:33:50 AM UTC