def _response(self, msg, prb, reply): if random.randint(0, 100) < prb: response = megahal.doreply(msg) if self._translations.has_key(response): response = self._translations[response] reply(response, prefixNick=False) else: megahal.learn(msg)
def __init__(self, name): mongo = MongoClient() db = mongo.lisa.logs msgs = db.find({'event': 'privmsg'}) mh_python.initbrain() for msg in msgs: mh_python.learn(msg['message'].encode('utf-8'))
def privmsg(bot, user, target, msg): if msg[0] != '!': mh_python.learn(msg) if responce_config == False and msg.split()[0] == bot.memory['nick']: query = msg.split(' ', 1)[1] bot.msg(target, chatter(query)) if responce_config == True: query = msg bot.msg(target, chatter(query))
def learn(self, msg): """learns msg without responding @type msg: string @param msg: the string to learn """ try: msg = unicode(msg, "UTF-8").encode("iso-8859-15") except UnicodeEncodeError: return #pass except UnicodeDecodeError: return #pass mh_python.learn(msg)
def process_msg(self, io_module, body, replyrate, learn, args, owner=0): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " # Parse commands if body[0] == "!": self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting # body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if randint(0, 99) < replyrate: if self.settings.process_with == "pyborg": message = self.reply(body) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) # single word reply: always output if len(message.split()) == 1: io_module.output(message, args) return # empty. do not output if message == "": return # else output if owner==0: time.sleep(.2*len(message)) io_module.output(message, args)
def process_line(self): data = self.fifo_pop() reply = None msg = data[1] if msg.split()[0].endswith(':'): msg = ' '.join(msg.split()[1:]) if not data[0]: mh_python.learn(msg) else: reply = mh_python.doreply(msg) if reply: self.send(data[0].split('!')[0].strip() + ': ' + reply) mh_python.cleanup() return
def invalidCommand(self, irc, msg, tokens): if not msg.args[0].startswith('#'): # It is a private message # Actually, we would like to answer, but : # 1) It may be a mistyped identify command (or whatever) # 2) MegaHAL can't reply without learning return message = msg.args[1] usedToStartWithNick = False if message.startswith(message): parsed = re.match('(.+ |\W)?(?P<message>\w.*)', message) message = parsed.group('message') usedToStartWithNick = True if self.registryValue('answer.commands') or usedToStartWithNick: self._response(message, self.registryValue('answer.probabilityWhenAddressed', msg.args[0]), irc.reply) elif self.registryValue('learn.commands'): megahal.learn(message)
def invalidCommand(self, irc, msg, tokens): if not msg.args[0].startswith('#'): # It is a private message # Actually, we would like to answer, but : # 1) It may be a mistyped identify command (or whatever) # 2) MegaHAL can't reply without learning return message = msg.args[1] usedToStartWithNick = False if message.startswith(message): parsed = re.match('(.+ |\W)?(?P<message>\w.*)', message) message = parsed.group('message') usedToStartWithNick = True if self.registryValue('answer.commands') or usedToStartWithNick: print msg.args[0] self._response(message, self.registryValue('answer.probabilityWhenAddressed', msg.args[0]), irc.reply) elif self.registryValue('learn.commands'): megahal.learn(message)
def learn(self, body): return mh_python.learn(body)
def process_msg(self, io_module, body, replyrate, learn, args, owner=0, not_quiet=1): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. If not_quiet==0 Only respond with taught responses """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " # Parse commands if body[0] == "!": self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if randint(0, 99) < replyrate: message = "" # Look if we can find a prepared answer if dbread(body): message = unfilter_reply(dbread(body)) elif not_quiet == 1: for sentence in self.answers.sentences.keys(): pattern = "^%s$" % sentence if re.search(pattern, body, re.IGNORECASE): message = self.answers.sentences[sentence][randint(0, len(self.answers.sentences[sentence])-1)] message = unfilter_reply(message) break else: if body in self.unfilterd: self.unfilterd[body] = self.unfilterd[body] + 1 else: self.unfilterd[body] = 0 if message == "": if self.settings.process_with == "pyborg": message = self.reply(body) message = unfilter_reply(message) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) else: return # single word reply: always output if len(message.split()) == 1: io_module.output(message, args) return # empty. do not output if message == "": return # else output if len(message) >= 25: # Quicker response time for long responses time.sleep(5) else: time.sleep(.2*len(message)) io_module.output(message, args)
#!/usr/bin/python # MegaHAL quick learning script. # By Laurent Fousse <*****@*****.**> GPL 2003 # # Usage: quick-learn < text-file # reads text-file linewise and feeds it to megahal import mh_python import sys mh_python.initbrain() while 1: ligne = sys.stdin.readline() if not ligne: break mh_python.learn(ligne) mh_python.cleanup()
def learn(self, msg): """learns msg without responding @type msg: string @param msg: the string to learn """ mh_python.learn(msg.encode("iso-8859-15"))
def process_msg(self, io_module, body, replyrate, learn, args, owner = 0): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " # Parse commands if body[0] == self.settings.command_char: self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if random.randint(0, 99) < replyrate: message = "" #Look if we can find a prepared answer for sentence in self.answers.sentences.keys(): pattern = "^%s$" % sentence if re.search(pattern, body): message = self.answers.sentences[sentence][random.randint(0, len(self.answers.sentences[sentence]) - 1)] break else: if body in self.unfilterd: self.unfilterd[body] = self.unfilterd[body] + 1 else: self.unfilterd[body] = 0 if message == "": if self.settings.process_with == "pyborg": message = self.reply(body) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) message.replace(" i "," I ") message.replace(" Im "," I'm ") message.replace(" cant "," can't ") message.replace(" arent "," aren't ") message.replace(" wont "," won't ") message.replace(" hes "," he's ") message.replace(" shes "," she's ") message.replace(" theyre "," they're ") message = message[:1].upper() + message[1:] ending = message[-1:] if message != "" and ending != "." and ending != "!" and ending != "?": message += "." # single word reply: always output if len(message.split()) == 1: io_module.output(message, args) return # empty. do not output if message == "": return # else output if owner == 0: time.sleep(.2 * len(message)) io_module.output(message, args)
def main(): cfgparser = ConfigParser() success = cfgparser.read('config.cfg') if not success: cfgparser = get_default_config() write_config(cfgparser) response_rate = cfgparser.getfloat('General', 'response rate') argparser = argparse.ArgumentParser( description="Slack chatbot using MegaHAL") argparser.add_argument("-t", "--token", type=str, help="Slack token", required=True) argparser.add_argument("--debug", help="Output raw events to help debug", action="store_true") args = vars(argparser.parse_args()) token = args['token'] debug = args['debug'] sc = SlackClient(token) mh.initbrain() try: if sc.rtm_connect(): name = get_name(sc) print("Detected name: %s" % name) time_of_last_event = datetime.datetime.now() while True: for event in sc.rtm_read(): time_of_last_event = datetime.datetime.now() if debug: print(event) if 'type' in event and event['type'] == 'message' \ and 'text' in event: message = event['text'].encode('ascii', 'ignore') # lowercase message so we can search it # case-insensitively message = message.lower() print("Handling message: %s" % message) match = re.search( "%s, set response rate to [0-9]{2}(%%|)" % name, message) if match: words = match.group().split() num = words[-1] if num[-1] == '%': rate = float(num[:-1]) / 100 else: rate = float(num) response_rate = rate reply(sc, event, "Response rate set to %f" % rate) time.sleep(1) # sleep to avoid rate limit else: match = re.search( "%s, what is your response rate?" % name, message) if match: reply( sc, event, "My response rate is set at %f." % response_rate) time.sleep(1) # sleep to avoid rate limit elif name in message or random.random( ) < response_rate: response = mh.doreply(message) reply(sc, event, response) time.sleep(1) # sleep to avoid rate limit else: mh.learn(message) # avoid being disconnected by activity by pinging inactivity = datetime.datetime.now() - time_of_last_event if inactivity > datetime.timedelta(seconds=5): sc.server.ping() time.sleep(2) else: print("Connection Failed, invalid token?") finally: mh.cleanup() cfgparser.set('General', 'response rate', str(response_rate)) print('Saving config...') write_config(cfgparser)
def learn_message(self, message): """Passes the message to megahal brain to learn.""" mh_python.learn(message) mh_python.cleanup()
def process_msg(self, io_module, body, replyrate, learn, args, owner=0): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " # Parse commands if body[0] == "!": self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if randint(0, 99) < replyrate: message = "" #Look if we can find a prepared answer for sentence in self.answers.sentences.keys(): pattern = "^%s$" % sentence if re.search(pattern, body): message = self.answers.sentences[sentence][randint( 0, len(self.answers.sentences[sentence]) - 1)] break else: if body in self.unfilterd: self.unfilterd[body] = self.unfilterd[body] + 1 else: self.unfilterd[body] = 0 if message == "": if self.settings.process_with == "pyborg": message = self.reply(body) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) # single word reply: always output if len(message.split()) == 1: io_module.output(message, args) return # empty. do not output if message == "": return # else output if owner == 0: time.sleep(.2 * len(message)) io_module.output(message, args)
def process_msg(self, io_module, body, replyrate, learn, args, owner = 0): """ Process message 'body' and pass back to IO module with args. If owner==1 allow owner commands. """ try: if self.settings.process_with == "megahal": import mh_python except: self.settings.process_with = "pyborg" self.settings.save() print "Could not find megahal python library\nProgram ending" sys.exit(1) # add trailing space so sentences are broken up correctly body = body + " " #Check for contextual commands contextual = self.is_contextual_command(body) if contextual: print "It's a contextual command:" contextual[1](io_module, contextual[0], args, owner) pprint(contextual) return # Parse commands if body[0] == "!": self.do_commands(io_module, body, args, owner) return # Filter out garbage and do some formatting body = filter_message(body, self) # Learn from input if learn == 1: if self.settings.process_with == "pyborg": self.learn(body) elif self.settings.process_with == "megahal" and self.settings.learning == 1: mh_python.learn(body) # Make a reply if desired if random.randint(0, 99) < replyrate: message = "" #Look if we can find a prepared answer for sentence in self.answers.sentences.keys(): pattern = "^%s$" % sentence if re.search(pattern, body): message = self.answers.sentences[sentence][random.randint(0, len(self.answers.sentences[sentence]) - 1)] break else: if body in self.unfilterd: self.unfilterd[body] = self.unfilterd[body] + 1 else: self.unfilterd[body] = 0 if message == "": if self.settings.process_with == "pyborg": potential_replies = [] potential_replies = [self.reply(body) for x in range(0,3)] print "Got some potential replies:" pprint(potential_replies) message = potential_replies[0] if len(message) < len(potential_replies[1]): message = potential_replies[1] if len(message) < len(potential_replies[2]): message = potential_replies[2] #message = self.reply(body) elif self.settings.process_with == "megahal": message = mh_python.doreply(body) # single word reply: never output if len(message.split()) == 1: #io_module.output(message, args) return # empty. do not output if message == "": return # else output io_module.output(message, args)