< Day Day Up > |
Hack 38 Extend the Python IRCLib
Not every program needs the same features from an IRC library. Extend IRCLib for your specific purposes. This hack shows you how to write an extension for IRCLib [Hack #37] . Extensions are simply Python scripts that add events and/or methods to the IRCLib classes. This allows you to have a modular, incremental approach to creating bots, adding one feature at a time. Let's take a look at an example. 5.9.1 The CodeSave 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:
5.9.2 Loading Your ExtensionsNow that you have an extension, let's use it in an IRCLib program: import irc
def handle_hi(destination):
MyConn.send_hi(destination)
MyIRC=irc.IRC_Object( )
MyIRC.load_extension("helloworld")
MyConn=MyIRC.new_connection( )
MyConn.nick="MauBot"
MyConn.ident="maubot"
MyConn.server=("irc.oftc.net", 6667)
MyConn.realname="Hoi"
MyConn.events['hi'].add_listener(handle_hi)
while 1:
MyIRC.main_loop( ) This example doesn't contain much new code, except for the MyIRC.load_extension("helloworld") line. As you've probably guessed, this call loads the 'helloworld' extension. Later on in the script, you add an event handler for the type 'hi' (added by the extension script). This causes the 'handle_hi' method to be called whenever the 'hi' event happens. This event handler uses the 'send_hi' method (also added by the extension) to send back a response. 5.9.3 Built-in ExtensionsIRCLib comes with a number of built-in extensions. To see a complete list of the extensions you can load, consult the IRCLib web site at http://irclib.bitlbee.org. There are also a number of advanced features, such as event handler priorities and the blocking of events. —Maurits Dijkstra |
< Day Day Up > |