Knit your own Tweets

16 Feb

The Perl scripts that I was fiddling about with seem to be working the way I wanted them to (even if what’s calling them isn’t always), so here they are for anybody else who wants to use them.


use DateTime;
use Sys::Hostname;

my $time = DateTime->now()->strftime("%F %T");
my $tweet = "$time\n";
my $hostname = hostname;

$tweet .= "$hostname\n";

    $tweet .= $line;

$tweet .= "%%\n";

#print $tweet


open(QUEUE,">>$tweetqueuefile") || die("Cannot open tweet queue");
print QUEUE $tweet;


use File::Copy;
use Net::Netrc;
use LWP::UserAgent;


open(QUEUE,"$tweetqueuefile") || die("Cannot open tweet queue");

# Read lines of first tweet

my $tweet;

    if($line eq "%%\n"){
        # Exit loop
    $tweet .= $line;

if($tweet != ""){
#	print "Sending tweet:\n$tweet";
    $netrc = Net::Netrc->lookup($machine);
    my $ua = LWP::UserAgent->new;
    my $req = HTTP::Request->new(POST => '');
    $req->authorization_basic($netrc->login, $netrc->password);
    my $result = $ua->request($req)->as_string;
#	print $result;


open(TEMP,">$tempfile") || die("Cannot open temporary file");

    print TEMP $line;


copy("$tempfile", "$tweetqueuefile") || die("Cannot overwrite tweet queue");

(As I’ve mentioned before, it’s a long time since I’ve written any Perl, so I’ve probably made any number of schoolboy errors. Still, they seem to do the trick.) reads from stdin to queue a tweet, and reads and sends the first tweet from the queue each time it’s called. You’ll need your credentials for in your .netrc file.

For example, I’ve got the following entries in my crontab:

# Send any pending tweets
*/5 * * * * /usr/local/bin/

# Log disk temperatures
30 */4 * * * /usr/sbin/hddtemp /dev/sda /dev/sdb | /usr/local/bin/

# Motherboard temperatures
35 */4 * * * /usr/bin/sensors | /bin/grep Temp | /usr/bin/cut -c 1-21 | /usr/local/bin/

Let me know if you use them for anything more interesting than tweeting your system temperatures, or if you’ve got any (constructive) criticisms of my Perl code…

1 Comment

Posted by on Tuesday 16 February 2010 in Geeky stuff


Tags: , ,

One response to “Knit your own Tweets

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: