# to run this script in irc channel
# python monkbot.py irc.freenode.net '#algolit' monk

from __future__ import division
import sys
import irc.bot



# Functions

# transformation of the message
def writing(msg):
    with open("monk.txt", "a") as logbook:
        logbook.write(msg)
    return logbook




# Actions bot
class MyBot(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)
        print "join"

    def on_privmsg(self, c, e):
        pass

    def on_pubmsg(self, c, e):
        # e.target, e.source, e.arguments, e.type
        # captures last line in chat
        print e.arguments
        msg = e.arguments[0]
        # writes message to logbook
        logbook = writing(msg)

# Launch bot
if __name__ == "__main__":
    import sys
    if len(sys.argv) != 4:
        print "Usage: monkbot.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 = MyBot(channel, nickname, server, port)
    bot.start()