#!/usr/bin/perl
# 
# Written in about 3 minutes, includes updates from I)ruid
#

use Net::Twitter;
use strict;
use Irssi;
use vars qw($VERSION %IRSSI @DoW @MoY %MoY);
@DoW = qw(Sun Mon Tue Wed Thu Fri Sat);
@MoY = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@MoY{@MoY} = (1..12);

$VERSION = '1.00';
%IRSSI = (
    authors     => 'Brian Caswell',
    contact     => 'bmc@shmoo.com',
    name        => 'twitter this',
    description => 'Send a twitter message',
    license     => 'Public Domain',
);

my $twit = Net::Twitter->new(username=>'evilcazz', password=>'password', source=>'From irssi');
my $date = time2str(time() - 3600);

Irssi::command_bind 'tweet' => sub {
    my ($data, $server, $witem) = @_;
    return unless $witem;

    if ($data eq '') {
        $witem->print("tweet: example:  /tweet <my message>");
        return;
    }

    $twit->update($data);
    twits(@_);
};

Irssi::command_bind 'twits' => \&twits;

sub twits (;$) {
    my ($data, $server, $witem) = @_;
    return unless $witem;

    my $friends = $twit->friends_timeline({'since' => $date});
    if ($friends) {
        foreach my $msg (reverse @{ $friends }) {
            $witem->print("tweet from \033[0;31m" .  $msg->{'user'}{'screen_name'} . "\033[0m: \033[0;32m" . $msg->{'text'} .  "\033[0m");
        }
    } else {
        $witem->print("twitter: your friends are too busy to tweet.  WTF?");
    }
    $date = time2str();
}

sub time2str (;$) {
    my ($time) = @_;
    $time = time unless $time;
    my ($sec, $min, $hour, $mday, $mon, $year, $wday) = gmtime($time);
    return sprintf("%s, %02d %s %04d %02d:%02d:%02d GMT", $DoW[$wday], $mday, $MoY[$mon], $year+1900, $hour, $min, $sec);
}
