#!/arch/unix/bin/perl
####################
# By: Ventz Petkov #
# Date: 10-07-05   #
# Del.icio.us Bot  #
####################
use warnings;
use strict;
use lib '/home/ventz/perl';

package GingerBot;
use base qw(Bot::BasicBot);
use WWW::Mechanize;
use Net::Delicious;
use URI::Title qw( title );
use WWW::Shorten::Metamark;
use Regexp::Common; 

my $mech = WWW::Mechanize->new();
$mech->agent_alias( 'Mac Safari' );
my $nickofbot = "gingerbot";
my $site = "http://del.icio.us/ginger";
my $del = Net::Delicious->new({user=>"ginger", pswd=>"ginger"});
my $lasttime = $del->update();

our $channel = '#ginger';
#our $channel = '#gingerbot';

sub tick {
    my $self = shift; my $mess = shift;
    my $time = $del->update;
    if(defined($lasttime) and defined($time)) {
        if($lasttime ne $time) {
            $lasttime = $time;
            my %hash = (tag => "", count => 1);
            my @recenturl = $del->recent_posts(\%hash);
            for(@recenturl) {
                my $url = $_->href();
                my $title = $_->description();
                my $shorturl = makeashorterlink($_);
                $self->say(channel => $channel, body => "$title - $shorturl");
            } 
        }
    }
    else {
        $lasttime = $time = $del->update;
    }
    return 5;
}

sub said {
    my $self = shift; my $mess = shift;
    my $msg = $mess->{body};
    my $who = $mess->{who};
    my $to = $mess->{address};
    #print STDERR $self->nick." : ".$msg."\n";

    if( ($to) and (($to =~ /$nickofbot/) or ($to =~ /msg/)) ) { 
        if( $msg eq "die" ) { exit(0); } 
        else {
            my %hash = (tag => $msg, count => 20);
            my @posts = $del->recent_posts(\%hash);
            for(@posts) {
                my $url = $_->href();
                my $title = $_->description();
                my $shorturl = makeashorterlink($_);
                $self->say(channel => $channel, body => "$title - $shorturl");
            }
        }
    }

    else {
        my ($url, @alltags) = split(/\s+/, $msg);
        my $tags = "";
        for(@alltags) { $tags = $tags." ".$_; }
        $tags =~ s/ //;

        if (defined $url and $url =~ m{ \A ($RE{URI}{HTTP}) \Z }sx ) {
            my $title = title($url);
            unless(defined($title)) { $title = $url; }
            my %hash = (url => $url, description => $title, tags => $tags);
            my $result = $del->add_post(\%hash);
        }
    } 
    return 0;
}

##############################################################
GingerBot->new(
#  server => "irc.ccs.neu.edu",
  server => "brat.ccs.neu.edu",
  channels => [ $channel ],
  nick => '$nickofbot',
  quit_message => "Good Bye!",
)->run();

