O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
IRC Hacks
By Paul Mutton
July 2004
More Info

HACK
#38
Extend the Python IRCLib
Not every program needs the same features from an IRC library. Extend IRCLib for your specific purposes
The Code
[Discuss (0) | Link to this hack]

The Code

Save this as helloworld.py anywhere in your Python path:

import irc

dependencies=[]
IRC_Object=None

def send_hi(self, channel):
    self.send_string("PRIVMSG %s :Hello World!" % channel) 

def handle_parsed(prefix, command, params):
    if command=="PRIVMSG":
        if params[1]=='hi':
            IRC_Instance.active.events['hi'].call_listeners(params[0])
        
def initialize( ):
    irc.IRC_Connection.send_hi=send_hi

def initialize_connection(connection):
    connection.add_event("hi")
    connection.events['parsed'].add_listener(handle_parsed)

The first line is the import irc needed to get access to the IRCLib classes.

The first variable defined in this extension script is dependencies. If your extension depends on other extensions to work, you can put the names of the extensions in this list. IRCLib will then load these extensions first before loading yours. IRC_Instance is a reference to the IRC_Object instance in the program that is loading your extension.

The script then continues to define four functions:

send_hi

This function will get added to the IRC_Connection class. It sends the string "Hello World!" to the channel specified by channel.

handle_parsed

This is an event handler for the 'parsed' event. It's used to get the parsed lines from IRCLib. If the line matches with "hi," all listeners for the 'hi' event are called. The destination of the message (was it said in a channel or private message?) is given to the event handlers as the first argument. Note that it's using IRC_Instance.active to get the connection that triggered the event. This variable exists so you don't have to pass IRC_Connection references to each event handler.

initialize

This function is called immediately after the script is loaded. This sets the send_hi function as a method for the class IRC_Connection.

initialize_connection

This function is called each time a new connection is created, with the IRC_Connection instance as its only argument. The first line of the function adds a 'hi' event to each connection. The second line connects 'handle_parsed' to the 'parsed' event for each connection.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.