Previous Section  < Day Day Up >  Next Section

Hack 37 IRC with Python and IRCLib

figs/moderate.gif figs/hack37.gif

Rather than reinventing the wheel each time you want to make a Python IRC bot, use an IRC library such as the IRCLib module.

While IRCLib is relatively new and doesn't have support for the entire IRC protocol yet, it offers a powerful API. It also has support for extensions so a programmer can add his own events and functions to the library. The latest IRCLib can be downloaded from http://irclib.bitlbee.org.

We'll assume you already know how to install Python modules, since explaining that is beyond the scope of this book. To find out how to install modules, take a look at the excellent documentation available at http://www.python.org/topics/learn.

5.8.1 The Code

Writing clients with IRCLib is really easy. Take a look at the following example:

import irc



MyIRC=irc.IRC_Object( )

MyConn=MyIRC.new_connection( )



MyConn.nick="MauBot"

MyConn.ident="maubot"

MyConn.server=("irc.freenode.net", 6667)

MyConn.realname="Maurits his bot"



while 1:

    MyIRC.main_loop( )

The first line of this example imports the irc module. You need this line to be able to use any of IRCLib's functions and classes.

The script starts by creating an instance of the IRC_Object class. This class could be seen as the main object of IRCLib—it creates and destroys connections and lets them know when there's data to read and write. The next line creates an instance of the IRC_Connection class. This class represents a single connection to an IRC server (a single client). You can create as many connections as you like.

The next block of code sets the client information for the connection you just created. nick is the nickname to use on IRC, ident is the Ident part of your host mask (nick!ident@host), server is the server to connect to, and realname is the name you want to show when somebody performs a /whois on you.

The rest of the program just sets the IRC client in action, connecting to the server you specified and doing whatever you told it to do (in this case, nothing).

5.8.2 Event Handlers

Having an IRC bot is fantastic, but what's the point if it doesn't do anything? To allow a client to respond to things that happen on IRC, IRCLib uses an event model. Again, it's probably best to demonstrate this by adding some functionality to our previous example:

import irc



# Define event listeners.

def handle_state(newstate):

    if newstate==4:

        MyConn.send_string("JOIN #irchacks")



def handle_raw(line):

    print line



def handle_parsed(prefix, command, params):

    if command=="PRIVMSG":

        if(params[0]=="#irchacks" and params[1]=="hi"):

            MyConn.send_string("PRIVMSG #irchacks :Hello World!")



# Connect as usual.

MyIRC=irc.IRC_Object( )

MyConn=MyIRC.new_connection( )



MyConn.nick="MauBot"

MyConn.ident="maubot"

MyConn.server=("irc.freenode.net", 6667)

MyConn.realname="Hoi"



# Before starting the main loop, add the event listeners.

MyConn.events['state'].add_listener(handle_state)

MyConn.events['raw'].add_listener(handle_raw)

MyConn.events['parsed'].add_listener(handle_parsed)



while 1:

    MyIRC.main_loop( )

The program now starts by defining the event handlers. Event handlers are functions that are called each time an event of a specific type occurs. This bot will listen for three different events:


State

This handler lets you check the bot's current connection state . This is used to see when the client is connected (state 4).


Raw

This one is used to print whatever the client is reading from the server. This is useful for debugging purposes.


Parsed

This one is used to receive parsed irc commands, sent to the client by the server. This is probably the most useful event. In this case, the bot is waiting to receive a message saying "hi" in the channel #irchacks. Whenever this message is received, the bot will send the message "Hello World" back to the channel.

Before the bot enters its main loop, you must connect the event handlers to their specified events. With these three lines, you're telling IRCLib to call the correct event handler whenever an event of the specified type occurs.

5.8.3 Learning More About IRCLib

So, that's all the code that is needed to write a simple IRC bot. For a complete overview of all the things IRCLib can do, see the documentation at http://irclib.bitlbee.org. If you want to learn about writing an extension for IRCLib, this is detailed in the following hack.

Maurits Dijkstra

    Previous Section  < Day Day Up >  Next Section