Search code examples
perlcpanirc

How can I implement a simple IRC client in Perl?


I'm working on a tool that needs to send IRC messages to an internal IRC channel. This isn't a constantly running program, but rather a tool that will be invoked occasionally and needs to be able to notify the channel with a couple of messages when it's invoked.

I looked at Net::IRC, but it's been dead since 2004. So I looked at the alternatives that it lists (Bot::BasicBot and POE::Component::IRC) but both of those need to be run under POE and its event loop. The same problem occurs for something like Net::Async::IRC since it needs to be run in the IO::Async event loop.

I'm not writing a full fledged bot that needs to interact with anything, I just want to login to an irc server, join a channel, post some quick messages and then leave. I don't want to have to re-write this whole program to fit inside of some framework's event loop just to do this.

So, any recommendations for a library for a simple IRC client that won't make me rewrite my whole app?


Solution

  • Use AnyEvent::IRC::Client, while it is using the AnyEvent 'event loop', you don't have to rewrite your app to use it, you can do something like this:

    use AnyEvent;
    use AnyEvent::IRC::Client;
    

    with the rest of your module use lines; and something like this

    sub do_irc {
        my $log_chan = '#foobar';
        my $timer; 
        my $c = AnyEvent->condvar;
        my $con = new AnyEvent::IRC::Client;
    
        $con->reg_cb( join => sub {
            my ($con, $nick, $channel, $is_myself) = @_; 
            if ($is_myself && $channel eq $log_chan) {
               $con->send_chan( $channel, PRIVMSG => ($channel, 'my information') );
               $timer = AnyEvent->timer ( 
                    after => 1,
                    cb => sub {
                        undef $timer;
                        $con->disconnect('done');
                    });
            }
        });
    
        $con->connect($irc_serv, 6667, { nick => $your_nick } );
        $con->send_srv( JOIN => ($log_chan) );
        $c->wait;
        $con->disconnect;
    
    }
    

    to do the connection, it will only return once it is done (error handling left out for brevity). Nothing else in your app needs to use AnyEvent.