Building an IRC bot in python

From XPUB & Lens-Based wiki

Somewhat redundant to example given on the IRC page.

The irc module provides a number of useful hooks/classes for writing python IRC bots.

sudo pip install irc

Here's a simple "hello" bot which responds to all chat messages by replying "HELLO".

import irc.bot

class HelloBot(irc.bot.SingleServerIRCBot):
    def __init__(self, channel, nickname, server, port=6667):
        irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
        self.channel = channel

    def on_welcome(self, c, e):
        c.join(self.channel)

    def on_privmsg(self, c, e):
        pass

    def on_pubmsg(self, c, e):
        # e.target, e.source, e.arguments, e.type
        print e.arguments
        c.privmsg(self.channel, "HELLO")


if __name__ == "__main__":
    import sys
    if len(sys.argv) != 4:
        print "Usage: hellobot.py <server[:port]> <channel> <nickname>"
        sys.exit(1)
    s = sys.argv[1].split(":", 1)
    server = s[0]
    if len(s) == 2:
        try:
            port = int(s[1])
        except ValueError:
            print "Error: Erroneous port."
            sys.exit(1)
    else:
        port = 6667
    channel = sys.argv[2]
    nickname = sys.argv[3]
    bot = HelloBot(channel, nickname, server, port)
    bot.start()