jamin on February 25th, 2003

My friend, Max, was interested in writing an IRC bot. I suggested he either write it in Perl or C#, listing advantages of each. Click below to see my very simple examples of about the most basic bot possible. Both bots don’t really do anything other than connect to an IRC server, join a channel, and greet everyone.

Perl using Net::IRC

Install the Perl module Net::IRC

And then your code might look something like this:


#!/usr/bin/perl
use Net::IRC;
$irc = new Net::IRC;
$conn = $irc->newconn(
      Nick    => 'kosbot',
      Server  => 'boston.ma.us.galaxynet.org',
      Port    => '6667',
      Ircname => 'Some witty comment.');
# Add our handlers here
$conn->add_global_handler('376', &on_connect);
$irc->start;

sub on_connect {
  my $self = shift;
  print "Joining #kos";
  $self->join("#kos");
  $self->privmsg("#kos", "Hi there.");
}

Obivously you’d want to add more. But basically you can see that I’m creating an irc connection, starting it, adding a handler to join the channel on connection. The meat of the bot would be in an on_public handler which would respond to things said in the channel.

C# using Thresher

Install Mono and download Thresher. The only thing you need from the Thresher file is the IRC.dll which you’ll copy to /usr/lib

Here’s code for a very simple bot (like the perl one above) in c#:


using System;
using Sharkbite.Irc;
namespace TestCode.KosBot
{
  public class KosBot
  {
    private Connection connection;
    public KosBot()
    {
      ConnectionArgs cargs = new ConnectionArgs("kosbot", "boston.ma.us.galaxynet.org");
      connection = new Connection( cargs, false, false );
      // Set up our handlers
      connection.Listener.OnRegistered += new RegisteredEventHandler( OnRegistered );
    }
    static void Main(string[] args)
    {
      KosBot bot = new KosBot();
      bot.connection.Connect();
      Console.WriteLine("KosBot connected.");
    }
    public void OnRegistered()
    {
      connection.Sender.Join( "#kos" );
      connection.Sender.PublicMessage( "#kos",  "Hi There." );
    }
  }
}

You’d compile this code like this:

mcs /r:IRC.dll KosBot.cs

and run it like this:

mono KosBot.exe

Tags: