Esempio n. 1
0
 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)
Esempio n. 2
0
 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)
Esempio n. 3
0
File: ki.py Progetto: otfbot/otfbot
 def reply(self, msg):
     """replies to msg, and learns it
     @param    msg: the string to reply to
     @type    msg: string
     @rtype: string
     @returns the answer of the megahal bot
     """
     string = msg.encode("iso-8859-15")
     return unicode(mh_python.doreply(string), "iso-8859-15")
Esempio n. 4
0
 def reply(self, msg):
     """replies to msg, and learns it
     @param    msg: the string to reply to
     @type    msg: string
     @rtype: string
     @returns the answer of the megahal bot
     """
     string = msg.encode("iso-8859-15")
     return str(mh_python.doreply(string), "iso-8859-15")
Esempio n. 5
0
	def robot(self, jsons):
		data = json.loads(jsons)

		data = data[0]
		if data['event'] == 'privmsg' or data['event'] == 'action':
			if data['channel'].lower() == '#geekblogtv':
				if data['message'].find('Lisa209') >= 0:
					result = mh_python.doreply(data['message'])

					self.callback(json.dumps([{
						'event': 'say',
						'channel': '#geekblogtv',
						'message': result}]))
Esempio n. 6
0
File: pyborg.py Progetto: vrx/idia
  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)
Esempio n. 7
0
    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
Esempio n. 8
0
File: ki.py Progetto: Farthen/OTFBot
 def reply(self, msg):
     """replies to msg, and learns it
     @param    msg: the string to reply to
     @type    msg: string
     @rtype: string
     @returns the answer of the megahal bot
     """
     try:
         string = unicode(msg, "UTF-8").encode("iso-8859-15")
     except UnicodeEncodeError:
         return ""
         #pass
     except UnicodeDecodeError:
         return ""
         #pass
     return unicode(mh_python.doreply(string), "iso-8859-15").encode("UTF-8")
Esempio n. 9
0
    def parse_message(self, event):
        """Parses any public messages to add it to the brain,
        as well as look for users who are talking to the bot
        by detecting users who type the bot's name in chat.

        TODO: Do we want to add text when people are talking to the bot?

        """

        bot_nick = self.server.get_nickname()
        message = event['message']
        
        # check if the bot's name was used
        m = re.search(bot_nick, message)
        if m:
            # we don't want the bot to learn its own nick
            message = re.sub(bot_nick, '', message)
            
            # get the megaHAL reply
            reply = "%s, %s" % (event['nick'], mh_python.doreply(message))
            self.msg(event['target'], reply)
            
        self.learn_message(message)
Esempio n. 10
0
    def parse_message(self, event):
        """Parses any public messages to add it to the brain,
        as well as look for users who are talking to the bot
        by detecting users who type the bot's name in chat.

        TODO: Do we want to add text when people are talking to the bot?

        """

        bot_nick = self.server.get_nickname()
        message = event['message']

        # check if the bot's name was used
        m = re.search(bot_nick, message)
        if m:
            # we don't want the bot to learn its own nick
            message = re.sub(bot_nick, '', message)

            # get the megaHAL reply
            reply = "%s, %s" % (event['nick'], mh_python.doreply(message))
            self.msg(event['target'], reply)

        self.learn_message(message)
Esempio n. 11
0
def chatter(query):
    return mh_python.doreply(query)
Esempio n. 12
0
	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)
Esempio n. 13
0
    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)
Esempio n. 14
0
 def reply(self, body):
     return mh_python.doreply(body)
Esempio n. 15
0
 def reply(self, body):
     return mh_python.doreply(body)
Esempio n. 16
0
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)
Esempio n. 17
0
    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)
Esempio n. 18
0
    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)