Saturday, June 6, 2009

Tweeting from the Command Line with Perl and Net::Twitter

The Net::Twitter module implements the entire Twitter API. This gives us the ability to create Perl scripts, small and large, to interact with Twitter.

Although I use Twitter a bit, I'm not that heavy a user that I need a massive application to tweet from. Instead I usually just use the web interface. But sometimes even that's too much if the tweet is short. Here's some code to tweet from the command line:

#!/usr/bin/env perl

use warnings;
use strict;
use Config::ApacheFormat;
use Net::Twitter;
use Term::ANSIColor;

use constant TWEETRC => "$ENV{HOME}/.tweetrc";

die "usage: tweet <message>\n" unless @ARGV == 1;

die "tweet: Unable to locate ~/.tweetrc file\n"
    unless -e TWEETRC;

my $tweet = shift;

if ( length $tweet > 140 ) {
    print "error: tweet is longer than 140 characters\n";
    print color 'green';
    print substr( $tweet, 0, 140 );
    print color 'bold red';
    print substr( $tweet, 140 );
    print color 'reset';
    print "\n";
    exit 1;

my $config = new Config::ApacheFormat;

my $username = $config->username;
my $password = $config->password;

my $twitter = Net::Twitter->new(
    {   username => $username,
        password => $password

my $result = $twitter->update( { status => $tweet } );

unless ( defined $result ) {
    printf "error updating status: %s\n",
    exit 1;
To use it, create a .tweetrc file in your home directory. Add something like this:
username foo
password bar

Replace 'foo' and 'bar' with your Twitter username and password, respectively. Make sure you set permissions correctly so other users can't read your .tweetrc.

And that's it. I place the script in my ~/bin directory, which is in my $PATH, under the name tweet with executable privileges and then run it like this:

tweet "I am a BANANA!"
Originally I didn't want to have to have to put quotes around the message, but shell meta-characters (like single quotes as an apostrophe) were getting in the way, so this was the safest alternative short of reading from standard input.

UPDATE: The code in this post has a problem which I have posted about here.

No comments:

Post a Comment