Ejemplo n.º 1
0
 def __init__(self, *args, **kwargs):
     super(HyacinthBot, self).__init__(*args, **kwargs)
     self.password = config.password
     self.karma_store = KarmaStore(config.karma_db_path)
     self.eightball = EightBall(config.eightball_answers_path)
     self.markov = Markov(config.markov_db_path)
     self.roller = Roller()
     self.rate_limiter = RateLimiter()
     self.greeter = Greeter(config.greetings_path,
                            config.greeting_probability)
Ejemplo n.º 2
0
 def __init__(self, *args, **kwargs):
     super(HyacinthBot, self).__init__(*args, **kwargs)
     self.password = config.password
     self.karma_store = KarmaStore(config.karma_db_path)
     self.eightball = EightBall(config.eightball_answers_path)
     self.markov = Markov(config.markov_db_path)
     self.roller = Roller()
     self.rate_limiter = RateLimiter()
     self.greeter = Greeter(config.greetings_path, config.greeting_probability)
class MarkovLineEvaluator(LineEvaluator):
    """
    Evaluate a haiku line based on it's fit with our markov model
    """
    def __init__(self, weight=1, prefix=None):
        self.prefix = prefix or getattr(settings, "MARKOV_DATA_PREFIX", "goodlines")
        self.markov_data = Markov(prefix=self.prefix, **getattr(settings, 'REDIS', {}))
        super(MarkovLineEvaluator, self).__init__(weight=weight)
        
    def evaluate(self, line):        
        return self.markov_data.score_for_line(line.split())
Ejemplo n.º 4
0
    def handle(self, *args, **options):
        """
        Seed our markov model with phrases from the nps_chat corpus
        """
        redis_conf = getattr(settings, 'REDIS', False)
        if redis_conf:
            print redis_conf
            client = redis.Redis(**redis_conf)
        else:
            client = redis.Redis()

        if client.exists("train_nps"):
            print "Already trained on nps data!"
        else:
            pattern = re.compile('([a-zA-Z0-9\-]*User\d+|ACTION)')
            markov_data = Markov(prefix=getattr(settings, "MARKOV_DATA_PREFIX", "goodlines"), **redis_conf)
            for line in nltk.corpus.nps_chat.xml_posts():
                if line.text not in ['JOIN','PART','<empty>'] and len(line.text.split()) > 2:
                    if re.search(pattern, line.text) is None:
                        good_line = HaikuText(line.text.lower()).filtered_text().split()
                        if len(good_line) > 0:
                            markov_data.add_line_to_index(good_line)
            client.incr("train_nps")
Ejemplo n.º 5
0
class HyacinthBot(BaseIRCBot):
    """An IRC bot."""

    nickname = config.nickname

    def __init__(self, *args, **kwargs):
        super(HyacinthBot, self).__init__(*args, **kwargs)
        self.password = config.password
        self.karma_store = KarmaStore(config.karma_db_path)
        self.eightball = EightBall(config.eightball_answers_path)
        self.markov = Markov(config.markov_db_path)
        self.roller = Roller()
        self.rate_limiter = RateLimiter()
        self.greeter = Greeter(config.greetings_path, config.greeting_probability)

    # callbacks for events
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]
        self.logger.log(msg)

        # Check to see if they're sending me a private message
        if channel == self.nickname:
            msg = "It isn't nice to whisper!  Play nice with the group."
            self.msg(user, msg)
            return

        # Otherwise check to see if it is a message directed at me
        if msg.startswith(self.nickname + ":"):
            msg = "%s: I am the little death that brings total oblivion" % user
            self.msg(channel, msg)
            self.logger.log("<%s> %s" % (self.nickname, msg))
            return

        self.process_message(user, channel, msg)

    def userJoined(self, user, channel):
        """Greets a user when they join the channel"""
        greeting = self.greeter.greet(user)
        if greeting:
            self.msg(channel, greeting)

    def process_message(self, user, channel, msg):
        self.record_karmas(user, channel, msg)
        self.markov.add_single_line(msg)

        if msg.startswith('!'):
            self.rate_limiter.add_request(user)
            if not self.rate_limiter.is_rate_limited(user):
                self.process_command(user, channel, msg)
        else:
            self.send_markov_sentence(user, channel, msg)

    def process_command(self, user, channel, msg):
        """Decide how to act upon a message, given that it is a command
        i.e. begins with !, e.g. "!karma"
        """

        if msg.startswith('!karma'):
            self.process_karmastring(user, channel, msg)
        elif msg.startswith('!8ball') and msg.endswith('?'):
            self.msg(channel, self.eightball.get_answer())
        elif msg.startswith('!markov'):
            new_msg = msg.replace('!markov', '')
            self.send_markov_sentence(user, channel, new_msg, force=True)
        elif msg.startswith('!roll'):
            new_msg = msg.replace('!roll', '')
            self.roll(user, channel, new_msg)
        elif msg.startswith('!commands'):
            self.msg(channel, '!karma, !8ball, !markov, !roll, !commands')

    def send_markov_sentence(self, user, channel, message, force=False):
        thing_to_say = self.markov.generate_sentence(message)
        if force or (len(thing_to_say.split()) > 5 and random.random() > 0.995):
            self.msg(channel, thing_to_say)

    def process_karmastring(self, user, channel, msg):
        # this is a stupid hack, since if there's not a space at the end
        # it fails strangely
        msg = msg + ' '
        split_msg = msg.split(' ')
        if len(split_msg) == 1:
            requested_user = user
        else:
            requested_user = split_msg[1]
        msg = self.karma_store.get_karma(requested_user)
        self.msg(channel, str(msg))

    def record_karmas(self, user, channel, msg):
        karmas = karma_regex.findall(msg)

        if not karmas:
            return

        for karma in karmas:
            recipient = karma[:-2] # on account of the ++ or --
            if recipient == user:
                self.msg(channel, 'no altering your own karma, %s' % user)
                continue
            if karma.endswith('--'):
                self.karma_store.record_karma(recipient, up=False)
            else:
                self.karma_store.record_karma(recipient, up=True)

    def roll(self, user, channel, msg):
        die, value = self.roller.roll(msg)
        roll_string = '%s rolls %s... %d' % (user, die, value)
        self.msg(channel, roll_string)
Ejemplo n.º 6
0
class HyacinthBot(BaseIRCBot):
    """An IRC bot."""

    nickname = config.nickname

    def __init__(self, *args, **kwargs):
        super(HyacinthBot, self).__init__(*args, **kwargs)
        self.password = config.password
        self.karma_store = KarmaStore(config.karma_db_path)
        self.eightball = EightBall(config.eightball_answers_path)
        self.markov = Markov(config.markov_db_path)
        self.roller = Roller()
        self.rate_limiter = RateLimiter()
        self.greeter = Greeter(config.greetings_path,
                               config.greeting_probability)

    # callbacks for events
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]
        self.logger.log(msg)

        # Check to see if they're sending me a private message
        if channel == self.nickname:
            msg = "It isn't nice to whisper!  Play nice with the group."
            self.msg(user, msg)
            return

        # Otherwise check to see if it is a message directed at me
        if msg.startswith(self.nickname + ":"):
            msg = "%s: I am the little death that brings total oblivion" % user
            self.msg(channel, msg)
            self.logger.log("<%s> %s" % (self.nickname, msg))
            return

        self.process_message(user, channel, msg)

    def userJoined(self, user, channel):
        """Greets a user when they join the channel"""
        greeting = self.greeter.greet(user)
        if greeting:
            self.msg(channel, greeting)

    def process_message(self, user, channel, msg):
        self.record_karmas(user, channel, msg)
        self.markov.add_single_line(msg)

        if msg.startswith('!'):
            self.rate_limiter.add_request(user)
            if not self.rate_limiter.is_rate_limited(user):
                self.process_command(user, channel, msg)
        else:
            self.send_markov_sentence(user, channel, msg)

    def process_command(self, user, channel, msg):
        """Decide how to act upon a message, given that it is a command
        i.e. begins with !, e.g. "!karma"
        """

        if msg.startswith('!karma'):
            self.process_karmastring(user, channel, msg)
        elif msg.startswith('!8ball') and msg.endswith('?'):
            self.msg(channel, self.eightball.get_answer())
        elif msg.startswith('!markov'):
            new_msg = msg.replace('!markov', '')
            self.send_markov_sentence(user, channel, new_msg, force=True)
        elif msg.startswith('!roll'):
            new_msg = msg.replace('!roll', '')
            self.roll(user, channel, new_msg)
        elif msg.startswith('!commands'):
            self.msg(channel, '!karma, !8ball, !markov, !roll, !commands')

    def send_markov_sentence(self, user, channel, message, force=False):
        thing_to_say = self.markov.generate_sentence(message)
        if force or (len(thing_to_say.split()) > 5
                     and random.random() > 0.995):
            self.msg(channel, thing_to_say)

    def process_karmastring(self, user, channel, msg):
        # this is a stupid hack, since if there's not a space at the end
        # it fails strangely
        msg = msg + ' '
        split_msg = msg.split(' ')
        if len(split_msg) == 1:
            requested_user = user
        else:
            requested_user = split_msg[1]
        msg = self.karma_store.get_karma(requested_user)
        self.msg(channel, str(msg))

    def record_karmas(self, user, channel, msg):
        karmas = karma_regex.findall(msg)

        if not karmas:
            return

        for karma in karmas:
            recipient = karma[:-2]  # on account of the ++ or --
            if recipient == user:
                self.msg(channel, 'no altering your own karma, %s' % user)
                continue
            if karma.endswith('--'):
                self.karma_store.record_karma(recipient, up=False)
            else:
                self.karma_store.record_karma(recipient, up=True)

    def roll(self, user, channel, msg):
        die, value = self.roller.roll(msg)
        roll_string = '%s rolls %s... %d' % (user, die, value)
        self.msg(channel, roll_string)
 def __init__(self, weight=1, prefix=None):
     self.prefix = prefix or getattr(settings, "MARKOV_DATA_PREFIX", "goodlines")
     self.markov_data = Markov(prefix=self.prefix, **getattr(settings, 'REDIS', {}))
     super(MarkovLineEvaluator, self).__init__(weight=weight)