Welcome to Etherpad!

This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!

Get involved with Etherpad at http://etherpad.org
# to run this script in irc channel
# python bot_learning_definitions.py irc.freenode.net '#algolit' monster

from __future__ import division
import nltk
from nltk.corpus import wordnet as wn
from pattern.en import tag
import sys
from time import sleep
import irc.bot



# Functions

# transformation of the message
def rewriting(words):
    definitions = []
    # tokenize source and get Part-of-Speech tags for each word
    for word in words:
        # create tuple of tuples with pairs of word + POS-tag
        collection = tag(word)
        # transform tuple into list to be able to manipulate it
        collection = list(collection)
        # for each pair:
        for element in collection:
            # look for nouns & replace them with their definition
            if element[1] == "NN":
                synset = wn.synsets(element[0])
                definitions.append("<")
                definitions.append(synset[0].definition())
                definitions.append(">")
            else:
                # non-nouns are left as words
                definitions.append(element[0])
    # write the transformed sentence
    reply = " ".join(definitions)
    return reply
        



# 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]
        # splits chat message in wordlist
        words = msg.split()
        reply = rewriting(words)
        c.privmsg(self.channel, reply)

# Launch bot
if __name__ == "__main__":
    import sys
    if len(sys.argv) != 4:
        print "Usage: bot_learning_definitions.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()