Skip to content
MurdockHM edited this page Mar 25, 2017 · 1 revision

Using the IRC library

Connecting

To connect to a server, you need to create an instance of the irc.client.Reactor object.

reactor = irc.client.Reactor()

Then you will need to create a connection object, with these 3 arguments.

connection = reactor.server().connect(server, port, nickname)

Now you'll most likely want to add handlers for events. They are explained in their own section on the wiki.

connection.add_global_handler("welcome", on_connect)
connection.add_global_handler("join", on_join)
connection.add_global_handler("disconnect", on_disconnect)
connection.add_global_handler("pubmsg", on_pubmsg)

And finally, you will need the reactor object to process data it receives. You could either use reactor.process_forever() to use its internal loop, but in MO we'll require control over when the data is processed, so we'll have to call reactor.process_once() at scheduled intervals.

Now, this will only connect us to the server, but if we want to join a channel, we have to call the join method on the connection object that's received by the event handlers. It's best done in the on_connect handler.

def on_connect(connection, event):
    if irc.client.is_channel(channel):
        connection.join(channel)

irc.client.is_channel() is a helper function that returns true when the given channel exists (so it's an actual channel, not some random string for example).

Events

The irc library specifies a large number of events our program can react to. The full list can be found here.

Adding a handler to an event means specifying what function should be called when a given event occurs. For example:

c.add_global_handler("welcome", on_connect)

The function on_connect will be called when we connect to a server. welcome is just how the server connection event is called in the irc library. Then we can define the on_connect function.

def on_connect(connection, event):
    print("Yay, I'm connected to a server.)

As you can see, the handler function receives two arguments: connection and event, however you can name them however you want. The short names c and e are preferred.