Categories
Posts

An IRC Experiment – raifbot

Toward the end of 2010 I really got the itch to experiment with new/different coding projects. The first thing this led me to was to write an IRC bot.

While I use IRC daily, it has been years since I’ve been any deeper besides casual use. So I started with writing a simple library to speak to IRC servers. That didn’t hold my interest for very long, so I retired that code and started building on top of the Net_SmartIRC package from Pear. I was writing this bot in PHP, in part because I wanted to play with a few new language feature, specifically – anonymous functions. More on those in a minute.

From that effort was born raifbot, which hangs on out #uphpu on freenode. It’s been fun hooking up bot commands to various features and servers, you can see the list of currently support commands at http://raifbot.wordpress.com/. Many of the popular commands are just fun little diversions: $lart, $8ball, $chuck-fact. Others reach out to online services to provide info, like $weather.

Now back to the idea of using anonymous functions. All of the command functions in raifbot have this style:

[sourcecode lang=”php”]
$_commands[‘rot13’] = function ( $channel, $nick, $msg ) {
global $bot;

if ( empty( $msg ) ) {
return;
}

$reply = "{$nick} – rot13( ‘{$msg}’ ) : " . str_rot13( $msg );
$bot->send_message( $channel, $reply );
};
[/sourcecode]

Each command function definition is just an entry in the global $_commands array.

I used this approach because I had a particular feature in mind, the ability to add new commands and update existing ones without having to restart the bot process. In the end I choose anonymous functions to accomplish this, which allowed me to avoid eval and other odd language hacks.

When I send a HUP signal to the bot process that triggers a reload of all the command files. At that point updating a command function definition is just a matter of updating an entry in an array. No errors and no fuss. I add new commands and update existing ones without having to ever take down the bot process. So far this has worked very well.

If you want to interact with raifbot join the #uphpu channel on freenode and give a spin. Remember all of the commands start with $ and the list of supported commands is http://raifbot.wordpress.com/.

In addition to raifbot I’ve started a few other experimental projects. Some more successful than others. Though one I started last week I’m particularly excited about, I’ll post more on that after I’ve added a few more features.