Building an IRC bot in python

From XPUB & Lens-Based wiki
Revision as of 13:13, 20 April 2014 by Michael Murtaugh (talk | contribs) (Created page with " sudo pip install irc <source lang="python"> import irc.bot class HelloBot(irc.bot.SingleServerIRCBot): def __init__(self, channel, nickname, server, port=6667): ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
sudo pip install irc
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()