Beispiel #1
0
    def resolve_type3_condition(self, client_context):
        try:
            for condition in self.children:
                value = self.get_condition_variable_value(client_context, condition.var_type, condition.name)
                if condition.value is not None:
                    condition_value = condition.value.resolve(client_context)

                    # Condition comparison is always case insensetive
                    if value.upper() == condition_value.upper():
                        resolved = client_context.brain.tokenizer.words_to_texts([child_node.resolve(client_context) for child_node in condition.children])
                        YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)

                        if condition.loop is True:
                            resolved = resolved.strip() + " " + self.resolve(client_context).strip()

                        return resolved

            default = self.get_default()
            if default is not None:
                resolved = client_context.brain.tokenizer.words_to_texts([child_node.resolve(client_context) for child_node in default.children])

                if default.loop is True:
                    resolved = resolved.strip() + " " + self.resolve(client_context).strip()

            else:
                resolved = ""

            YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
            return resolved

        except Exception as excep:
            YLogger.exception(client_context, "Failed to resolve type3 condition", excep)
            return ""
Beispiel #2
0
    def equals(self, client_context, words, word_no):
        word = words.word(word_no)

        if self.userid != '*':
            if self.userid != client_context.userid:
                return EqualsMatch(False, word_no)

        if self._pattern_template is not None:
            template = client_context.brain.regex_templates[self._pattern_template]
            if template is not None:
                result = template.match(word)
                if result is not None:
                    YLogger.debug(client_context, "Match word [%s] regex", word)
                    return EqualsMatch(True, word_no, word)
                else:
                    YLogger.error(client_context, "No word [%s] matched regex", word)
                    return EqualsMatch(False, word_no)
            else:
                return EqualsMatch(False, word_no)
        else:
            result = self.pattern.match(word)
            if result is not None:
                YLogger.debug(client_context, "Match word [%s] regex", word)
                return EqualsMatch(True, word_no, word)
            else:
                YLogger.error(client_context, "No word [%s] matched regex", word)
                return EqualsMatch(False, word_no)
Beispiel #3
0
    def execute(self, context, data):
        YLogger.debug(context, "GeoCode [%s]", data)

        words = data.split(" ")
        if words[0] == 'POSTCODE1':
            location = words[1]
        elif words[0] == 'POSTCODE2':
            location = words[1] + words[2]
        elif words[0] == 'LOCATION':
            location = " ".join(words[1:])
        else:
            return None

        googlemaps = self.get_geo_locator()

        latlng = googlemaps.get_latlong_for_location(location)
        if latlng is not None:
            str_lat = str(latlng.latitude)
            str_lng = str(latlng.longitude)

            lats = str_lat.split(".")
            lngs = str_lng.split(".")

            return "LATITUDE DEC %s FRAC %s LONGITUDE DEC %s FRAC %s"%(
                lats[0], lats[1],
                lngs[0], lngs[1]
            )

        return None
Beispiel #4
0
    def execute(self, client_context, data):
        YLogger.debug(client_context, "Transcript Admin - [%s]", data)

        show_props = True if data == "PROPERTIES" else False

        transcript = ""

        if client_context.bot.has_conversation(client_context):
            conversation = client_context.bot.conversation(client_context)

            transcript += "Questions:<br /><ul>"
            for question in conversation.questions:
                transcript += "<li>%s - %s</li>"%(question.combine_sentences(), question.combine_answers())
            transcript += "</ul>"
            transcript += "<br />"

            if data == "PROPERTIES":
                transcript += "Properties:<br /><ul>"
                for name, value in conversation.properties.items():
                    transcript += "<li>%s = %s</li>"%(name, value)
                transcript += "</ul>"
                transcript += "<br />"

        else:
            transcript += "No conversation currently available"

        return transcript
Beispiel #5
0
    def execute(self, client_context, data):
        YLogger.debug(client_context, "RDF Admin - [%s]", data)

        rdf = ""
        segments = data.split()
        if segments[0] == 'SUBJECTS':
            subjects = client_context.brain.rdf.subjects()
            if segments[1] == 'LIST':
                rdf += "<ul>"
                for subject in subjects:
                    rdf += "<li>%s</li>"%subject
                rdf += "</ul>"
            else:
                return str(len(subjects))

        elif segments[0] == "PREDICATES":
            subject = segments[1]
            predicates = client_context.brain.rdf.predicates(subject)
            rdf += "<ul>"
            for predicate in predicates:
                rdf += "<li>%s</li>" % predicate
            rdf += "</ul>"

        elif segments[0] == "OBJECT":
            subject = segments[1]
            predicate = segments[2]
            objects =  client_context.brain.rdf.objects(subject, predicate)
            rdf += "<ul>"
            for object in objects:
                rdf += "<li>%s</li>" % object
            rdf += "</ul>"

        return rdf
Beispiel #6
0
    def handle_message(self, message):

        try:
            if self.configuration.client_configuration.debug is True:
                self.dump_request(message)
            self.renderer.print_payload("Incoming", message)

            # Facebook Messenger ID for user so we know where to send response back to
            recipient_id = self.get_recipitent_id(message)
            if recipient_id:
                client_context = self.create_client_context(recipient_id)

                message_text = self.get_message_text(message)

                # We have been send a text message, we can respond
                if message_text is not None:
                    response_text = self.handle_text_message(client_context, message_text)

                # else if user sends us a GIF, photo,video, or any other non-text item
                elif self.has_attachements(message):
                    response_text = self.handle_attachement(client_context, message)

                # otherwise its a general error
                else:
                    YLogger.error(client_context, "Facebook general error handling message")
                    response_text = "Sorry, I do not understand you!"

                YLogger.debug(client_context, "Facebook message response: [%s]", response_text)
                self.render_response(client_context, response_text)

        except Exception as e:
            YLogger.exception(None, "Error handling facebook message", e)
Beispiel #7
0
    def load_users(self, yaml_data):
        users = {}
        if 'users' in yaml_data:
            for user_name in yaml_data['users'].keys():

                user = User(user_name)

                yaml_obj = yaml_data['users'][user_name]
                if 'roles' in yaml_obj:
                    roles_list = yaml_obj['roles']
                    splits = roles_list.split(",")
                    for role_name in splits:
                        role_name = role_name.strip()
                        if role_name not in user.roles:
                            user.roles.append(role_name)
                        else:
                            YLogger.debug(self, "Role [%s] already exists in user [%s]", role_name, user_name)

                if 'groups' in yaml_obj:
                    groups_list = yaml_obj['groups']
                    splits = groups_list.split(",")
                    for group_name in splits:
                        group_name = group_name.strip()
                        if group_name not in user.groups:
                            user.groups.append(group_name)
                        else:
                            YLogger.debug(self, "Group [%s] already exists in user [%s]", group_name, user_name)

                users[user.userid] = user
        return users
Beispiel #8
0
    def wait_and_answer(self):
        running = True
        try:
            self._client_connection = self._server_socket.accept_connection()

            receive_payload = self._client_connection.receive_data()

            question = self.extract_question(receive_payload)
            userid = self.extract_userid(receive_payload)

            client_context = self.create_client_context(userid)
            answer = self.process_question(client_context, question)

            self.render_response(client_context, answer)

        except KeyboardInterrupt:
            running = False
            YLogger.debug(self, "Cleaning up and exiting...")

        except Exception as e:
            if self._client_connection is not None:
                self._client_connection.send_error(e)

        finally:
            if self._client_connection is not None:
                self._client_connection.close()

        return running
Beispiel #9
0
 def resolve_to_string(self, client_context):
     conversation = client_context.bot.get_conversation(client_context)
     question = conversation.current_question()
     sentence = question.current_sentence()
     resolved = sentence.matched_context.topicstar(self.index)
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Beispiel #10
0
 def check_spelling_before(self, each_sentence):
     # TODO Move this to spelliing base class
     if self.configuration.spelling.check_before is True:
         text = each_sentence.text()
         corrected = self.spell_checker.correct(text)
         YLogger.debug(self, "Spell Checker corrected [%s] to [%s]", text, corrected)
         each_sentence.replace_words(corrected)
Beispiel #11
0
    def _parse_node_with_attribs(self, graph, expression, attribs):

        attribs_found = []
        for attrib in attribs:
            attrib_name = attrib[0]
            if attrib_name in expression.attrib:
                self.set_attrib(attrib_name, expression.attrib[attrib_name])
                attribs_found.append(attrib_name)

        self.parse_text(graph, self.get_text_from_element(expression))

        for child in expression:
            tag_name = TextUtils.tag_from_text(child.tag)

            for attrib in attribs:
                attrib_name = attrib[0]
                if tag_name == attrib_name:
                    self.set_attrib(attrib[0], self.get_text_from_element(child))
                else:
                    graph.parse_tag_expression(child, self)

            self.parse_text(graph, self.get_tail_from_element(child))

        for attrib in attribs:
            attrib_name = attrib[0]
            if attrib_name not in attribs_found:
                if attrib[1] is not None:
                    YLogger.debug(self, "Setting default value for attrib [%s]", attrib_name)
                    self.set_attrib(attrib_name, attrib[1])
Beispiel #12
0
    def resolve_to_string(self, client_context):
        srai_text = self.resolve_children_to_string(client_context)
        YLogger.debug(client_context, "[%s] SRAI Text [%s]", self.to_string(), srai_text)

        resolved = client_context.bot.ask_question(client_context, srai_text, srai=True)
        YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
        return resolved
Beispiel #13
0
    def match_sentence(self, client_context, pattern_sentence, topic_pattern, that_pattern):

        topic_sentence = Sentence(client_context.brain.tokenizer, topic_pattern)
        that_sentence = Sentence(client_context.brain.tokenizer, that_pattern)

        YLogger.debug(client_context, "AIML Parser matching sentence [%s], topic=[%s], that=[%s] ",
                          pattern_sentence.text(), topic_pattern, that_pattern)

        sentence = Sentence(client_context.brain.tokenizer)
        sentence.append_sentence(pattern_sentence)
        sentence.append_word('__TOPIC__')
        sentence.append_sentence(topic_sentence)
        sentence.append_word('__THAT__')
        sentence.append_sentence(that_sentence)
        YLogger.debug(client_context, "Matching [%s]", sentence.words_from_current_pos(0))

        context = MatchContext(max_search_depth=client_context.bot.configuration.max_search_depth,
                               max_search_timeout=client_context.bot.configuration.max_search_timeout,
                               tokenizer=client_context.brain.tokenizer)

        template = self._pattern_parser._root_node.match(client_context, context, sentence)

        if template is not None:
            context._template_node = template

            context.list_matches(client_context)

            # Save the matched context for the associated sentence
            pattern_sentence.matched_context = context

            return context

        return None
Beispiel #14
0
 def schedule_as_cron(self, userid, clientid, action, text, year='*', month='*', day='*', week='*', day_of_week='*',
                      hour='*', minute='*', second='*'):
     YLogger.debug(None, "Scheduler scheduling cron")
     job_id = self.create_job_id(userid, clientid, action, text)
     self.remove_existing_job(job_id)
     self._scheduler.add_job(scheduled, 'cron', [self.name, userid, clientid, action, text], id=job_id, year=year, month=month, day=day,
                             week=week, day_of_week=day_of_week, hour=hour, minute=minute, second=second)
Beispiel #15
0
    def send_response(self, userid, answer):
        return_payload = {"result": "OK", "answer": answer, "userid": userid}
        json_data = json.dumps(return_payload)

        YLogger.debug(self, "Sent %s:", json_data)

        self._clientsocket.send(json_data.encode('utf-8'))
Beispiel #16
0
 def add_set(self, name, the_set):
     # Set names always stored in upper case to handle ambiquity
     set_name = name.upper()
     if set_name in self._sets:
         raise Exception("Set %s already exists" % set_name)
     YLogger.debug(self, "Adding set [%s[ to set group", set_name)
     self._sets[set_name] = the_set
Beispiel #17
0
 def resolve_to_string(self, client_context):
     string = self.resolve_children_to_string(client_context)
     query = {'q': string}
     encoded = urlencode(query)
     resolved = "https://www.google.co.uk/search?" + encoded
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Beispiel #18
0
 def _follow_new_followers(self, followers, friends):
     for follower in followers:
         YLogger.debug(self, "Checking follower [%s]", follower.screen_name)
         if follower.id not in friends:
             YLogger.debug(self, "Following %s", follower.screen_name)
             follower.follow()
             self._api.send_direct_message(follower.id, text=self._welcome_message)
Beispiel #19
0
    def resolve_to_string(self, client_context):
        conversation = client_context.bot.get_conversation(client_context)

        if conversation.has_current_question():

            current_question = conversation.current_question()

            current_sentence = current_question.current_sentence()

            matched_context = current_sentence.matched_context
            if matched_context is None:
                YLogger.error(client_context, "Star node has no matched context for clientid %s", client_context.userid)
                resolved = ""
            else:
                try:
                    resolved = matched_context.star(self.index)
                    if resolved is None:
                        YLogger.error(client_context, "Star index not in range [%d]", self.index)
                        resolved = ""
                except Exception:
                    YLogger.error(client_context, "Star index not in range [%d]", self.index)
                    resolved = ""
        else:
            resolved = ""

        YLogger.debug(client_context, "Star Node [%s] resolved to [%s]", self.to_string(), resolved)
        return resolved
Beispiel #20
0
 def _get_response_as_json(self, url):
     YLogger.debug(self, "GoogleMaps Request = [%s]", url)
     response = urllib.request.urlopen(url)
     content = response.read()
     decoded = content.decode('utf8')
     YLogger.debug(self, "GoogleMaps Response = [%s]", decoded)
     return json.loads(decoded)
Beispiel #21
0
    def _get_news_feed_articles(url, max_articles, sort, reverse):
        YLogger.debug(None, "News API URL: [%s]", url)
        response = NewsAPI._news_api_api.get_news(url)
        articles = []
        if response.status_code == 200:
            header_splits = response.headers['content-type'].split(";")
            if header_splits[0] == 'application/json':
                json_data = response.json()
                if 'articles' in json_data:
                    for article_data in json_data['articles']:
                        article = NewsArticle()
                        article.parse_json(article_data)
                        articles.append(article)
                        YLogger.debug(None, article.description)

                    if sort is True:
                        YLogger.debug(None, "Sorting articles,, reverse=%s", str(reverse))
                        articles.sort(key=lambda article: article.published_at, reverse=reverse)

                    if max_articles != 0:
                        YLogger.debug(None, "Returning max_articles %d articles", max_articles)
                        articles = articles[:max_articles]
                    else:
                        YLogger.debug(None, "Returning all articles")
                else:
                    YLogger.error(None, "NewAPI payload contains no articles attribute")
            else:
                YLogger.error(None, "NewsAPI request none JSON object")

        else:
            YLogger.error(None, "NewsAPI request returned error code %d", response.status_code)

        return articles
Beispiel #22
0
 def resolve_to_string(self, client_context):
     result = self.resolve_children_to_string(client_context)
     first = result[:1]
     rest = result[1:]
     resolved = first.upper() + rest.lower()
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Beispiel #23
0
 def resolve_variable(self, client_context):
     name = self.name.resolve(client_context)
     value = TemplateGetNode.get_property_value(client_context, self.local, name)
     if self.local:
         YLogger.debug(client_context, "[%s] resolved to local: [%s] <= [%s]", self.to_string(), name, value)
     else:
         YLogger.debug(client_context, "[%s] resolved to global: [%s] <= [%s]", self.to_string(), name, value)
     return value
Beispiel #24
0
 def get_userid(self, request):
     userid = request.cookies.get(self.configuration.client_configuration.cookie_id)
     if userid is None:
         userid = str(uuid.uuid4().hex)
         YLogger.debug(self, "Setting userid cookie to :%s" % userid)
     else:
         YLogger.debug(self, "Found userid cookie : %s" % userid)
     return userid
Beispiel #25
0
 def resolve(self, client_context):
     try:
         resolved = self.resolve_children_to_string(client_context)
         YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
         return resolved
     except Exception as excep:
         YLogger.exception(client_context, "Failed to resolve", excep)
         return ""
Beispiel #26
0
    def _process_direct_message_question(self, userid, text):

        YLogger.debug(self, "Direct Messages: %s -> %s", userid, text)

        client_context = self.create_client_context(userid)
        response = client_context.bot.ask_question(client_context, text, responselogger=self)

        self._api.send_direct_message(userid, text=response)
Beispiel #27
0
    def mark_question_start(self, question):
        YLogger.debug(self, "##########################################################################################")
        YLogger.debug(self, "Question (%s): %s", self._client.id, question)

        if self._question_depth == 0:
            self._question_start_time = datetime.datetime.now()
            
        self._question_depth += 1
Beispiel #28
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, 'facebook', argument_parser)

        YLogger.debug(self, "Facebook Client is running....")

        self._facebook_bot = self.create_facebook_bot()

        print("Facebook Client loaded")
Beispiel #29
0
    def scheduled_event(name, userid, clientid, action, text):
        YLogger.debug(None, "Received Scheduled Event [%s] [%s] [%s] [%s] [%s]", name, userid, clientid, action, text)

        if name in ProgramyScheduler.schedulers:
            scheduler = ProgramyScheduler.schedulers[name]
            scheduler.scheduled(userid, clientid, action, text)
        else:
            YLogger.error(None, "Unknown scheduler [%s]", name)
Beispiel #30
0
 def wait_loop(self, period=5):
     try:
         while True:
             time.sleep(period)
     except:
         YLogger.debug(None, "Scheduler shutting down...")
     finally:
         self.stop()
Beispiel #31
0
    def resolve_to_string(self, client_context):
        resolved = ""
        conversation = client_context.bot.get_conversation(client_context)
        slotName = self._slotName.resolve(client_context)
        itemName = self._itemName.resolve(client_context)
        try:
            slotIndex = int(self._index.resolve(client_context))
        except Exception:
            slotIndex = 0

        slots = None
        try:
            value = conversation.current_question().property(
                "__SYSTEM_NLUDATA__")
            json_dict = json.loads(value)
            slots = json_dict["slots"]
        except Exception:
            YLogger.error(
                self, "TemplateNluSlotNode failed to load __SYSTEM_NLUDATA__")
            return resolved

        slotsKeyName = "slot"

        slotKeys = [slot.get(slotsKeyName) for slot in slots]
        if itemName == "count":
            if slotName == "*":
                resolved = str(len(slotKeys))
            else:
                resolved = str(slotKeys.count(slotName))

            YLogger.debug(client_context, "nluslot [%s] resolved to [%s]",
                          itemName, resolved)
            return resolved

        index = None
        try:
            if slotName == "*":
                index = 0
                if slotIndex != 0:
                    index = slotIndex
            else:
                if slotIndex != 0:
                    slotCounter = 0
                    targetCounter = 0
                    for name in slotKeys:
                        if name == slotName:
                            if targetCounter == slotIndex:
                                index = slotCounter
                                break
                            targetCounter += 1
                        slotCounter += 1
                else:
                    index = slotKeys.index(slotName)
        except Exception:
            YLogger.debug(client_context, "nluslot non search keys:%s",
                          slotName)

        if index is not None:
            YLogger.debug(client_context, "nluintent index[%s]", index)
            try:
                if itemName in slots[index]:
                    resolved = str(slots[index].get(itemName))
            except Exception:
                YLogger.debug(client_context, "nluslot non search item:%s",
                              itemName)

        if resolved == '':
            YLogger.debug(client_context, "nluslot failed slot=[%s] item=[%s]",
                          slotName, itemName)
            resolved = TemplateGetNode.get_default_value(client_context)

        YLogger.debug(client_context, "nluslot [%s] resolved to [%s:%s]",
                      slotName, itemName, resolved)

        return resolved
Beispiel #32
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, 'google', argument_parser)

        YLogger.debug(self, "Google Client is running....")

        print("Google Client loaded")
Beispiel #33
0
 def _brain_pre_process_question(self, client_context, text):
     pre_processed = client_context.brain.pre_process_question(client_context, text)
     YLogger.debug(client_context, "Pre Processed (%s): %s", client_context.userid, pre_processed)
     return pre_processed
Beispiel #34
0
 def load_email(self):
     if self._configuration.client_configuration.email is not None:
         YLogger.debug(None, "Loading Email Manager")
         self._email = EmailSender(
             self._configuration.client_configuration.email)
Beispiel #35
0
 def execute_oob_command(self, client_context):
     YLogger.debug(client_context,
                   "CameraOutOfBandProcessor: Setting camera to=%s",
                   self._command)
     return "CAMERA"
Beispiel #36
0
 def aiml_response(self, response):
     payload = response['response']['payload']
     result = payload['AbstractText']
     YLogger.debug(self, result)
     return result
Beispiel #37
0
 def load_initial_variables(self, variables_collection):
     for pair in variables_collection.pairs:
         YLogger.debug(self, "Setting variable [%s] = [%s]", pair[0],
                       pair[1])
         self._properties[pair[0]] = pair[1]
Beispiel #38
0
 def resolve_to_string(self, client_context):
     resolved = str(client_context.brain.aiml_parser.num_categories)
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Beispiel #39
0
 def process(self, context, word_string):
     YLogger.debug(context, "Stemming sentence...")
     unstemmed_words = context.brain.tokenizer.texts_to_words(word_string)
     stemmed_words = [Stemmer.stem(x) for x in unstemmed_words]
     return context.brain.tokenizer.words_to_texts(stemmed_words)
Beispiel #40
0
 def handle_text_message(self, client_context, message_text):
     YLogger.debug(client_context, "Facebook sent message: [%s]",
                   message_text)
     return self.ask_question(client_context, message_text)
Beispiel #41
0
    def consume(self, client_context, context, words, word_no, match_type,
                depth):

        tabs = self.get_tabs(client_context, depth)

        #TODO uncomment this section
        # if context.search_time_exceeded() is True:
        #     YLogger.error(client_context, "%sMax search time [%d]secs exceeded", tabs, context.max_search_timeout)
        #     return None

        if context.search_depth_exceeded(depth) is True:
            YLogger.error(client_context, "%sMax search depth [%d] exceeded",
                          tabs, context.max_search_depth)
            return None

        context_match = Match(match_type, self, None)
        context.add_match(context_match)
        matches_added = 1

        match = self.check_child_is_wildcard(tabs, client_context, context,
                                             words, word_no, match_type, depth)
        if match is not None:
            return match

        word = words.word(word_no)

        if self._children:
            for child in self._children:

                result = child.equals(client_context, words, word_no)
                if result.matched is True:
                    word_no = result.word_no
                    YLogger.debug(client_context,
                                  "%sWildcard child matched %s", tabs,
                                  result.matched_phrase)

                    context_match2 = Match(Match.WORD, child,
                                           result.matched_phrase)

                    context.add_match(context_match2)
                    matches_added += 1

                    match = child.consume(client_context, context, words,
                                          word_no + 1, match_type, depth + 1)
                    if match is not None:
                        return match

                    if self.invalid_topic_or_that(tabs, client_context, word,
                                                  context,
                                                  matches_added) is True:
                        return None

            YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                          self._wildcard, word)
            context_match.add_word(word)

            match = super(PatternZeroOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no + 1, match_type, depth + 1)
            if match is not None:
                return match

            word_no += 1
            word = words.word(word_no)

            if self.invalid_topic_or_that(tabs, client_context, word, context,
                                          matches_added) is True:
                return None

            YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                          self._wildcard, word)
            context_match.add_word(word)

            match = super(PatternZeroOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no + 1, match_type, depth + 1)
            if match is not None:
                return match

            word_no += 1
            if word_no >= words.num_words():
                context.pop_matches(matches_added)
                return None
            word = words.word(word_no)

        YLogger.debug(client_context,
                      "%sNo children, consume words until next break point",
                      tabs)
        while word_no < words.num_words() - 1:
            match = super(PatternZeroOrMoreWildCardNode,
                          self).consume(client_context, context, words,
                                        word_no, match_type, depth + 1)
            if match is not None:
                return match

            if self.invalid_topic_or_that(tabs, client_context, word, context,
                                          matches_added) is True:
                return None

            YLogger.debug(client_context, "%sWildcard %s matched %s", tabs,
                          self._wildcard, word)
            context_match.add_word(word)

            word_no += 1
            word = words.word(word_no)

        match = super(PatternZeroOrMoreWildCardNode,
                      self).consume(client_context, context, words, word_no,
                                    match_type, depth + 1)

        if match is not None:
            return match
        context.pop_matches(matches_added)
        return None
Beispiel #42
0
 def resolve_to_string(self, client_context):
     selection = randint(0, (len(self._children) - 1))
     resolved = self._children[selection - 1].resolve(client_context)
     YLogger.debug(client_context, "[%s] resolved to [%s]",
                   self.to_string(), resolved)
     return resolved
Beispiel #43
0
 def resolve_to_string(self, client_context):
     string = self.resolve_children_to_string(client_context)
     resolved = client_context.brain.denormals.denormalise_string(string)
     YLogger.debug(client_context, "[%s] resolved to [%s]",
                   self.to_string(), resolved)
     return resolved
Beispiel #44
0
 def empty(self):
     YLogger.debug(self, "Defaulting root to PatternRootNode")
     self._empty_children(self._root_node)
     self._root_node = self._pattern_factory.get_root_node()
Beispiel #45
0
 def execute_oob_command(self, client_context):
     YLogger.debug(client_context, "EmailOutOfBandProcessor: Emailing=%s", self._to)
     return "EMAIL"
Beispiel #46
0
    def _published_Bot_interface(self, client_context):
        self.locale = None
        self.time = None
        self.userId = None
        self.topic = None
        self.deleteVariable = None
        self.metadata = None
        self.config = None

        if self._userId is not None:
            self.userId = self._userId.resolve(client_context)
        if self._locale is not None:
            self.locale = self._locale.resolve(client_context)
        if self._time is not None:
            self.time = self._time.resolve(client_context)
        if self._topic is not None:
            self.topic = self._topic.resolve(client_context)
        if self._deleteVariable is not None:
            self.deleteVariable = self._deleteVariable.resolve(client_context)
        if self._config is not None:
            shift_text = self._config.resolve(client_context)
            self.config = self._delete_shift_code(shift_text)
        if self._metadata is not None:
            self.metadata = self._metadata.resolve(client_context)

        bot_service = ServiceFactory.get_service(self.SERVICE_PUBLISHED_BOT)

        botInfo = client_context.brain.botnames.botInfo(self.botName)
        if botInfo is None:
            error_msg = "sraix subagent-bot : botName[%s] not found" % self.botName
            YLogger.debug(client_context, error_msg)
            raise Exception(error_msg)

        conversation = client_context.bot.get_conversation(client_context)
        exec_botInfo = copy.copy(botInfo)

        error_msg = None
        if self.userId is None or self.userId == '':
            self.userId = conversation.current_question().property('__USER_USERID__')
        if self.userId is None or self.userId == '':
            error_msg = "sraix subagent-bot : no userId parameter"
        if error_msg is None and self.locale is not None:
            if exec_botInfo.set_locale(self.locale) is False:
                error_msg = "sraix subagent-bot : invalid locale parameter [%s]" % self.locale
        if error_msg is None and self.time is not None:
            if exec_botInfo.set_time(self.time) is False:
                error_msg = "sraix subagent-bot : invalid time parameter [%s]" % self.time
        if error_msg is None and self.topic is not None:
            if exec_botInfo.set_topic(self.topic) is False:
                error_msg = "sraix subagent-bot : invalid topic parameter [%s]" % self.topic
        if error_msg is None and self.deleteVariable is not None:
            if exec_botInfo.set_deleteVariable(self.deleteVariable) is False:
                error_msg = "sraix subagent-bot : invalid deleteVariable parameter [%s]" % self.deleteVariable
        if error_msg is None and self.config is not None:
            if exec_botInfo.set_config(self.config) is False:
                error_msg = "sraix subagent-bot : invalid config parameter [%s]" % self.config
        if error_msg is None and self.metadata is not None:
            if exec_botInfo.join_metadata(self.metadata) is False:
                error_msg = "sraix subagent-bot : invalid metadata parameter [%s]" % self.metadata

        if error_msg is not None:
            YLogger.debug(client_context, error_msg)
            raise Exception(error_msg)

        resolved = self.resolve_children_to_string(client_context)
        YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)

        bot_service.botInfo = exec_botInfo
        bot_service.userId = self.userId
        response = bot_service.ask_question(client_context, resolved)
        YLogger.debug(client_context, "SRAIX botName [%s] return [%s]", self._botName, response)

        status_code = ''
        try:
            status_code = bot_service.get_status_code()
        except NotImplementedError:
            pass
        if conversation.has_current_question() is True:
            conversation.current_question().set_property('__SUBAGENT_STATUS_CODE__', status_code)

        if response is not None:
            if conversation.has_current_question() is False:
                if response == '' and self.default is not None:
                    response = self.default
            else:
                variableName = "__SUBAGENT_EXTBOT__"
                if response != '':
                    try:
                        response_dic = json.loads(response)
                        save_dic = {self._botName: response_dic}
                        conversation.current_question().set_property(variableName, json.dumps(save_dic, ensure_ascii=False))
                        response_data = response_dic['response']
                        if type(response_data) is dict:
                            response = json.dumps(response_data, ensure_ascii=False)
                        else:
                            response = response_data
                    except Exception:
                        if self.default is not None:
                            response = self.default
                        else:
                            response = ''
                else:
                    if self.default is not None:
                        response = self.default
                    variableName += ".%s" % self._botName
                    conversation.current_question().set_property(variableName, response)
        return response
Beispiel #47
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, "line", argument_parser)

        self.create_line_bot()

        YLogger.debug(self, "Line Client is running....")
 def _load_file_contents(self, parser, filename):
     YLogger.debug(self, "Loading file contents from [%s]", filename)
     try:
         parser.parse_from_file(filename, userid="*")
     except Exception as excep:
         YLogger.exception(self, "Failed to load cat [%s]", excep, filename)
Beispiel #49
0
 def load_scheduler(self):
     if self.configuration.client_configuration.scheduler is not None:
         YLogger.debug(None, "Loading Scheduler")
         self._scheduler = ProgramyScheduler(
             self, self.configuration.client_configuration.scheduler)
         self._scheduler.start()
Beispiel #50
0
 def receive_data(self):
     json_data = self._clientsocket.recv(self._max_buffer).decode()
     YLogger.debug(self, "Received: %s", json_data)
     return json.loads(json_data, encoding="utf-8")
Beispiel #51
0
 def load_trigger_manager(self):
     if self._configuration.client_configuration.triggers is not None:
         YLogger.debug(None, "Loading Trigger Manager")
         self._trigger_mgr = TriggerManager.load_trigger_manager(
             self._configuration.client_configuration.triggers)
Beispiel #52
0
 def add_document(self, document):
     YLogger.debug(self, "Adding document to collection [%s]",
                   self.collection_name())
     collection = self.collection()
     document.id = self._add_to_collection(collection, document)
     return bool(document.id is not None)
Beispiel #53
0
 def resolve(self, client_context):
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), client_context.client.id)
     if client_context.client.id is not None:
         return client_context.client.id
     return ""
Beispiel #54
0
 def empty_named(self, name):
     YLogger.debug(self, "Empting set [%s]", name)
     collection = self.collection()
     collection.remove({MongoSetsStore.NAME: name})
Beispiel #55
0
 def resolve_to_string(self, client_context):
     resolved = self.resolve_children_to_string(client_context)
     YLogger.debug(client_context, "[%s] resolved to [%s]",
                   self.to_string(), resolved)
     return ""
Beispiel #56
0
    def log_answer(self, client_context, text, answer, responselogger):
        YLogger.debug(client_context, "Processed Response (%s): %s",
                      client_context.userid, answer)

        if responselogger is not None:
            responselogger.log_response(text, answer)
Beispiel #57
0
 def process(self, context, word_string):
     YLogger.debug(context, "Removing punctuation...")
     return TextUtils.strip_none_terminating_punctuation(word_string)
Beispiel #58
0
 def handle_split(self, client_context, split):
     YLogger.debug(client_context, "Handling split...")
Beispiel #59
0
 def dump_request(self, request):
     YLogger.debug(self, str(request))
Beispiel #60
0
    def consume(self, client_context, context, words, word_no, match_type, depth):

        tabs = self.get_tabs(client_context, depth)

        if context.search_time_exceeded() is True:
            if context.is_error is False:
                context.is_error = True
                raise LimitOverException("%sMax search time [%d]secs exceeded" % (tabs, context.max_search_timeout))
            return None

        if context.search_depth_exceeded(depth) is True:
            if context.is_error is False:
                context.is_error = True
                raise LimitOverException("%sMax search depth [%d] exceeded" % (tabs, context.max_search_depth))
            return None

        if word_no >= words.num_words():
            if self._0ormore_hash is not None:
                child_template = self._0ormore_hash.template
            elif self._0ormore_arrow is not None:
                child_template = self._0ormore_arrow.template
            else:
                child_template = self._template

            if child_template is not None:
                YLogger.debug(client_context, "%sFound a template, success!", tabs)
                return child_template
            else:
                YLogger.debug(client_context, "%sNo more words and no template, no match found!", tabs)
                return None

        if self._topic is not None:
            match = self._topic.consume(client_context, context, words, word_no, Match.TOPIC, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched topic, success!", tabs)
                return match
            if words.word(word_no) == PatternNode.TOPIC:
                YLogger.debug(client_context, "%s Looking for a %s, none give, no match found!", tabs, PatternNode.TOPIC)
                return None

        if self._that is not None:
            match = self._that.consume(client_context, context, words, word_no, Match.THAT, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched that, success!", tabs)
                return match
            if words.word(word_no) == PatternNode.THAT:
                YLogger.debug(client_context, "%s Looking for a %s, none give, no match found!", tabs, PatternNode.THAT)
                return None

        match, word_no = self.match_children(client_context, self._priority_words, "Priority", words, word_no, context, match_type, depth)
        if match is not None:
            return match

        if self._0ormore_hash is not None:
            match = self._0ormore_hash.consume(client_context, context, words, word_no, match_type, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched 0 or more hash, success!", tabs)
                return match

        if self._1ormore_underline is not None:
            match = self._1ormore_underline.consume(client_context, context, words, word_no, match_type, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched 1 or more underline, success!", tabs)
                return match

        match, word_no = self.match_children(client_context, self._children, "Word", words, word_no, context, match_type, depth)
        if match is not None:
            return match

        if self._0ormore_arrow is not None:
            match = self._0ormore_arrow.consume(client_context, context, words, word_no, match_type, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched 0 or more arrow, success!", tabs)
                return match

        if self._1ormore_star is not None:
            match = self._1ormore_star.consume(client_context, context, words, word_no, match_type, depth+1)
            if match is not None:
                YLogger.debug(client_context, "%sMatched 1 or more star, success!", tabs)
                return match

        YLogger.debug(client_context, "%sNo match for %s, trying another path", tabs, words.word(word_no))
        return None