basic_irc

Download source


#!/sw/bin/perl -w

use strict;
use warnings;
use POE qw(
    Component::IRC
);

my $mynick = 'poebot',
my $channel = '#amsterdam.pm';

my $irc = POE::Component::IRC->spawn(
    nick => $mynick,
    server => "irc.perl.org",
    port => 6667,
    ircname => "Perl workshop demo-bot",
)
    or die "irc: $!\n";

POE::Session->create(
    package_states => [
        main => [ qw(_start _default irc_001 irc_public irc_msg) ],
    ],
    heap => {
        Irc => $irc,
        Channel => $channel,
    },
);

POE::Kernel->run();
exit 0;

sub _start {
    $irc->yield( register => 'all' );
    $irc->yield( connect => {} );
}

sub irc_001 {
    my($kernel, @args) = @_[KERNEL, ARG0 .. $#_];
    ### we're connected, make sure we join the channel
    $irc->yield( join => $channel );
    ### print stuff on debug
    $kernel->yield( _default => 'irc_001', \@args );
}

sub irc_public {
    my($kernel, $heap, $who, $where, $what) =
        @_[KERNEL, HEAP, ARG0, ARG1, ARG2];
    my $nick = ( split /!/, $who )[0];
    my $channel = $where->[0];

    print "$channel <$nick> $what\n";
}

sub irc_msg {
    my($kernel, $heap, $who, $what) = @_[KERNEL, HEAP, ARG0, ARG2];
    my $nick = ( split /!/, $who )[0];

    print "$nick whispers: $what\n";
}

sub _default {
    my($event, $args) = @_[ARG0, ARG1];
    my(@output) = ( "$event: " );
    for my $arg ( @$args ) {
        if ( ref($arg) eq 'ARRAY' ) {
            push @output, "[" . join(", ", @$arg) . "]";
        } else {
            push @output, "'$arg'";
        }
    }
    print "@output\n";
}