Exemple #1
0
 def parse_oob_xml(self, oob: ET.Element):
     if oob is not None and oob.text is not None:
         self._location = oob.text
         return True
     else:
         YLogger.error(self, "Unvalid geomap oob command - missing location text!")
         return False
Exemple #2
0
    def create_viber_bot(self, viber_token):

        if viber_token is None:
            YLogger.error(self, "'viber_token' missing")
            return None

        name = self.configuration.client_configuration.name
        if name is None:
            YLogger.error(self, "'name' missing from Viber configuration")
            return None

        avatar = self.configuration.client_configuration.avatar
        if avatar is None:
            YLogger.error(self, "'avatar' missing from Viber configuration")
            return None

        webhook = self.configuration.client_configuration.webhook
        if webhook is None:
            YLogger.error(self, "'webhook' missing from Viber configuration")
            return None

        configuration = BotConfiguration(
            name=name,
            avatar=avatar,
            auth_token=viber_token
        )

        bot = self.create_viber_api(configuration)
        if bot is not None:
            YLogger.error(self, "'Failed to create Viber api")

        bot.set_webhook(webhook)
        return bot
Exemple #3
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
Exemple #4
0
 def parse_oob_xml(self, oob):
     if oob is not None and oob.text is not None:
         self._command = oob.text
         return True
     else:
         YLogger.error(self, "Unvalid clear oob command - missing command")
         return False
Exemple #5
0
 def load_single_file(self, configuration):
     start = datetime.datetime.now()
     self._aiml_loader.load_single_file_contents(configuration.files.aiml_files.file)
     stop = datetime.datetime.now()
     diff = stop - start
     YLogger.info(self, "Total processing time %.6f secs", diff.total_seconds())
     YLogger.info(self, "Loaded a single aiml file with %d categories", self.num_categories)
Exemple #6
0
    def parse_topic(self, topic_element, namespace):

        if 'name' in topic_element.attrib:
            name = topic_element.attrib['name']
            if name is None or not name:
                raise ParserException("Topic name empty or null", xml_element=topic_element)
            xml = "<topic>%s</topic>" % name
            YLogger.info(self, "Topic attrib converted to %s", xml)
            topic_pattern = ET.fromstring(xml)
        else:
            raise ParserException("Missing name attribute for topic", xml_element=topic_element)

        category_found = False
        num_category = 0
        for child in topic_element:
            tag_name, _ = self.tag_and_namespace_from_text(child.tag)
            if tag_name == 'category':
                self.parse_category(child, namespace, topic_pattern)
                category_found = True
                num_category += 1
            else:
                raise ParserException("Unknown child node of topic, %s" % child.tag, xml_element=topic_element)

        if category_found is False:
            raise ParserException("No categories in topic", xml_element=topic_element)

        return num_category
Exemple #7
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)
Exemple #8
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
Exemple #9
0
 def save_conversation(self, clientid):
     if self._conversation_storage is not None:
         if clientid in self._conversations:
             conversation = self._conversations[clientid]
             self._conversation_storage.save_conversation(conversation, clientid)
         else:
             YLogger.error(self, "Unknown conversation id type [%s] unable tonot persist!", clientid)
Exemple #10
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])
Exemple #11
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
Exemple #12
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
Exemple #13
0
 def parse_oob_xml(self, oob: ET.Element):
     if oob is not None and oob.text is not None:
         self._url = oob.text
         return True
     else:
         YLogger.error(self, "Unvalid url oob command - missing url!")
         return False
Exemple #14
0
 def _load_postprocessors(self, configuration):
     if configuration.files.postprocessors is not None:
         self._postprocessors.empty()
         total = self._postprocessors.load(configuration.files.postprocessors)
         YLogger.info(self, "Loaded a total of %d post processors", total)
     else:
         YLogger.warning(self, "No configuration setting for post processors")
Exemple #15
0
    def get_property_value(client_context, local, name):

        if local is True:

            value = None
            #TODO Why would you need this test, when is get_conversation(clientid) == None ?
            if client_context.bot.get_conversation(client_context) is not None:
                if client_context.bot.get_conversation(client_context).has_current_question():
                    value = client_context.bot.get_conversation(client_context).current_question().property(name)

        else:

            if name is not None and client_context.brain.dynamics.is_dynamic_var(name) is True:
                value = client_context.brain.dynamics.dynamic_var(client_context, name)
            else:
                value = client_context.bot.get_conversation(client_context).property(name)
                #if value is None:
                #    value = bot.brain.properties.property(name)

        if value is None:
            YLogger.error(client_context, "No property for [%s]", name)

            value = TemplateGetNode.get_default_value(client_context.bot)

        return value
Exemple #16
0
    def set_attrib(self, attrib_name, attrib_value):

        if attrib_name != 'index':
            raise ParserException("Invalid attribute name [%s] for this node" % (attrib_name))

        if isinstance(attrib_value, int):
            int_val = attrib_value
            self._sentence = int_val
        else:
            splits = attrib_value.split(",")
            if len(splits) == 1:
                try:
                    self._sentence = int(splits[0])
                except Exception as excep:
                    YLogger.exception(self, "Failed to split string", excep)
                    raise ParserException("None numeric format [%s] for this node [%s], either 'x' or 'x,y'",
                                          attrib_value, attrib_name)
            elif len(splits) == 2:
                try:
                    self._question = int(splits[0])
                    if splits[1] == '*':
                        self._sentence = -1
                    else:
                        self._sentence = int(splits[1])
                except Exception as excep:
                    YLogger.exception(self, "Failed to split string", excep)
                    raise ParserException("None numeric format [%s] for this node [%s], either 'x', 'x,y', or 'x,*'",
                                          attrib_value, attrib_name)

        if self._sentence == 0:
            raise ParserException("Sentence values are 1 based, cannot be 0")

        if self._question == 0:
            raise ParserException("Question values are 1 based, cannot be 0")
Exemple #17
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
Exemple #18
0
    def load_config_section(self, configuration_file, configuration, bot_root):
        scheduler = configuration_file.get_section(self._section_name, configuration)
        if scheduler is not None:
            self._name = configuration_file.get_option(scheduler, "name", missing_value=None)
            self._debug_level = configuration_file.get_int_option(scheduler, "debug_level", missing_value=0)
            self._add_listeners = configuration_file.get_bool_option(scheduler, "add_listeners", missing_value=False)
            self._remove_all_jobs = configuration_file.get_bool_option(scheduler, "remove_all_jobs", missing_value=False)

            if 'jobstore' in scheduler:
                self._jobstore = SchedulerJobStoreConfiguration()
                self._jobstore.load_config_section(configuration_file, scheduler, bot_root)

            if 'threadpool' in scheduler:
                self._threadpool = SchedulerThreadPoolConfiguration()
                self._threadpool.load_config_section(configuration_file, scheduler, bot_root)

            if 'processpool' in scheduler:
                self._processpool = SchedulerProcessPoolConfiguration()
                self._processpool.load_config_section(configuration_file, scheduler, bot_root)

            if 'job_defaults' in scheduler:
                self._job_defaults = SchedulerJobDefaultsConfiguration()
                self._job_defaults.load_config_section(configuration_file, scheduler, bot_root)
        else:
            YLogger.warning(self, "'scheduler' section missing from client config, using to defaults")
Exemple #19
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)
Exemple #20
0
 def resolve(self, client_context):
     try:
         data = self.resolve_to_string(client_context)
         return data
     except Exception as excep:
         YLogger.exception(client_context, "Failed to resolve", excep)
         return ""
Exemple #21
0
    def load_configuration(self, configuration_file, section, bot_root):
        if section is not None:
            bot_names = configuration_file.get_multi_option(section, "bot", missing_value="bot")
            first = True
            for name in bot_names:
                if first is True:
                    config = self._bot_configs[0]
                    first = False
                else:
                    config = BotConfiguration(name)
                    self._bot_configs.append(config)
                config.load_configuration(configuration_file, bot_root)

            self._license_keys = configuration_file.get_option(section, "license_keys")
            if self._license_keys is not None:
                self._license_keys = self.sub_bot_root(self._license_keys, bot_root)

            self._bot_selector = configuration_file.get_option(section, "bot_selector")

            self._scheduler.load_config_section(configuration_file, section, bot_root)

            self._renderer = configuration_file.get_option(section, "renderer")

        else:
            YLogger.warning(self, "No bot name defined for client [%s], defaulting to 'bot'.", self.section_name)
            self._bot_configs[0]._section_name = "bot"
            self._bot_configs[0].load_configuration(configuration_file, bot_root)
Exemple #22
0
    def receive_message(self, request):

        api_key_response = self.check_api_key(request)
        if api_key_response is not None:
            return api_key_response

        question = self.get_question(request)
        if question is None:
            YLogger.error(self, "'question' missing from request")
            abort(400)

        userid = self.get_userid(request)

        userid_expire_date = self.get_userid_cookie_expirary_date(self.configuration.client_configuration.cookie_expires)

        client_context = self.create_client_context(userid)
        try:
            answer = self.get_answer(client_context, question)
            rendered = self._renderer.render(client_context, answer)
            response_data = self.create_success_response_data(question, rendered)

        except Exception as excep:
            YLogger.exception(self, "Failed receving message", excep)
            response_data = self.create_error_response_data(client_context, question, str(excep))

        return self.create_response(response_data, userid, userid_expire_date)
Exemple #23
0
 def receive_message():
     try:
         return WEB_CLIENT.receive_message(request)
     except Exception as e:
         print(e)
         YLogger.exception(None, "Web client error", e)
         return "500"
Exemple #24
0
    def poll_and_answer(self):

        running = True
        try:
            (last_direct_message_id, last_status_id) = self._get_last_message_ids()

            self._poll(last_direct_message_id, last_status_id)

        except KeyboardInterrupt:
            running = False

        except RateLimitError:

            if self._configuration.client_configuration.rate_limit_sleep != -1:
                rate_limit_sleep = self._configuration.client_configuration.rate_limit_sleep
            else:
                rate_limit_sleep = self.FIFTEEN_MINUTES

            YLogger.error(self, "Rate limit exceeded, sleeping for %d seconds", rate_limit_sleep)

            self.sleep(rate_limit_sleep)

        except Exception as excep:
            YLogger.exception(self, "Poll and answer error", excep)

        return running
Exemple #25
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
Exemple #26
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
Exemple #27
0
 def resolve(self, client_context):
     try:
         client_context.bot.load_conversation(client_context.userid)
         return self.resolve_to_string(client_context)
     except Exception as excep:
         YLogger.exception(client_context, "Failed to resolve", excep)
         return ""
Exemple #28
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)
Exemple #29
0
    def load_security_services(self, configuration):
        if configuration.security is not None:
            if configuration.security.authentication is not None:
                if configuration.security.authentication.classname is not None:
                    try:
                        classobject = ClassLoader.instantiate_class(
                            configuration.security.authentication.classname)
                        self._authentication = classobject(configuration.security.authentication)
                    except Exception as excep:
                        YLogger.exception(self, "Failed to load security services", excep)
            else:
                YLogger.debug(self, "No authentication configuration defined")

            if configuration.security.authorisation is not None:
                if configuration.security.authorisation.classname is not None:
                    try:
                        classobject = ClassLoader.instantiate_class(
                            configuration.security.authorisation.classname)
                        self._authorisation = classobject(configuration.security.authorisation)
                    except Exception as excep:
                        YLogger.exception(self, "Failed to instatiate authorisation class", excep)
            else:
                YLogger.debug(self, "No authorisation configuration defined")

        else:
            YLogger.debug(self, "No security configuration defined, running open...")
Exemple #30
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)
Exemple #31
0
 def resolve_to_string(self, client_context):
     string = self.resolve_children_to_string(client_context)
     resolved = client_context.brain.person2s.personalise_string(string)
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Exemple #32
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, "line", argument_parser)

        self.create_line_bot()

        YLogger.debug(self, "Line Client is running....")
Exemple #33
0
 def receive_message():
     try:
         return LINE_CLIENT.receive_message(request)
     except Exception as e:
         YLogger.exception(None, e)
Exemple #34
0
 def add_user(self, userid, clientid):
     YLogger.info(self, "Adding user [%s] for client [%s]", userid,
                  clientid)
     user = User(userid, clientid)
     return self.add_document(user)
Exemple #35
0
 def receive_message():
     try:
         return TWILIO_CLIENT.receive_message(request)
     except Exception as e:
         YLogger.exception(None, "Twilio Error", e)
Exemple #36
0
 def execute_oob_command(self, client_context):
     YLogger.debug(client_context, "DialogOutOfBandProcessor: Dialog=%s",
                   self._title)
     return "DIALOG"
Exemple #37
0
    def load_authentication_service(self, client):
        try:
            self._load_authentication_class(client)

        except Exception as excep:
            YLogger.exception(self, "Failed to load security services", excep)
Exemple #38
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)
Exemple #39
0
 def resolve(self, client_context):
     try:
         return self.resolve_to_string(client_context)
     except Exception as excep:
         YLogger.exception(client_context, excep)
         return ""
Exemple #40
0
 def process(self, context, word_string):
     YLogger.debug(context, "Lemmatizing sentence...")
     unstemmed_words = context.brain.tokenizer.texts_to_words(word_string)
     stemmed_words = [Lemmatizer.lemmatize(x) for x in unstemmed_words]
     return context.brain.tokenizer.words_to_texts(stemmed_words)
Exemple #41
0
 def _unfollow_non_followers(self, friends, followers_ids):
     for friend_id in friends:
         if friend_id not in followers_ids:
             YLogger.debug(self, "Removing previous friendship with [%d]",
                           friend_id)
             self._api.destroy_friendship(friend_id)
Exemple #42
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, "kik", argument_parser)

        self.create_kik_bot()

        YLogger.debug(self, "Kik Client is running....")
 def save_duplicates(self, duplicates):
     YLogger.debug(self, "Saving duplicates to Mongo")
     for duplicate in duplicates:
         db_duplicate = Duplicate(duplicate=duplicate[0], file=duplicate[1], start=duplicate[2], end=duplicate[3])
         self.add_document(db_duplicate)
Exemple #44
0
 def dump_request(self, request):
     YLogger.debug(self, str(request))
Exemple #45
0
 def reload_sets(client_context):
     YLogger.debug(client_context, "Hot reloading Sets")
     client_context.brain.load_sets()
     return 'HOTRELOAD OK'
Exemple #46
0
 def add_substitute(self, name, value):
     if name in self._substitutes:
         YLogger.warning(self, "Substitute [%s], already exists", name)
     self._substitutes[name] = value
Exemple #47
0
 def add_rdf(self, name, subject, predicate, objct, replace_existing=True):
     collection = self.collection()
     YLogger.info(self, "Adding RDF [%s] [%s] [%s] [%s]", name, subject, predicate, objct)
     anrdf = RDF(name=name, subject=subject, predicate=predicate, object=objct)
     collection.insert_one(anrdf.to_document())
     return True
Exemple #48
0
 def set_attrib(self, attrib_name, attrib_value):
     if attrib_name != 'timeout':
         raise ParserException("Invalid attribute name %s for this node",
                               attrib_name)
     YLogger.warning(self, "System node timeout attrib currently ignored")
     self._timeout = attrib_value
Exemple #49
0
 def load_service(self, configuration):
     # First instantiate the service object
     YLogger.debug(self, "Loading service: [%s]", configuration.name)
     self._services[configuration.name] = ClassLoader.instantiate_class(
         configuration.service_class)(configuration)
     self._services[configuration.name].initialise(self._client)
Exemple #50
0
 def load(self, rdf_collection, rdf_name):
     collection = self.collection()
     rdfs = collection.find({MongoRDFsStore.NAME: rdf_name})
     for rdf in rdfs:
         YLogger.info(self, "Loading RDF [%s]", rdf[MongoRDFsStore.NAME])
         rdf_collection.add_entity(rdf[MongoRDFsStore.SUBJECT], rdf[MongoRDFsStore.PREDICATE], rdf[MongoRDFsStore.OBJECT], rdf_name)
Exemple #51
0
 def execute_oob_command(self, client_context):
     YLogger.info(client_context,
                  "CameraOutOfBandProcessor: Setting camera to=%s",
                  self._command)
     return "CAMERA"
Exemple #52
0
 def empty_named(self, name):
     YLogger.info(self, "Empting rdf [%s]", name)
     collection = self.collection()
     collection.remove({MongoRDFsStore.NAME: name})
Exemple #53
0
 def unlink_accounts(self, primary_userid):
     YLogger.info(self, "Unlinking accounts [%s] in Mongo", primary_userid)
     collection = self.collection()
     result = collection.delete_many(
         {MongoLinkedAccountStore.PRIMARY_USERID: primary_userid})
     return bool(result.deleted_count > 0)
Exemple #54
0
 def resolve_to_string(self, client_context):
     result = self.resolve_children_to_string(client_context)
     resolved = TextUtils.strip_all_whitespace(result)
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Exemple #55
0
    def _load_file_contents(self, nlu_collection, filename):
        YLogger.debug(self, "Loading NLU_Servers [%s]", filename)
        server_index = 0
        nlu_index = 0
        try:
            with open(filename, 'r+', encoding="utf-8") as yml_file:
                yaml_data = yaml.load(yml_file, Loader=yaml.SafeLoader)
                if yaml_data is not None:
                    servers_section = self._get_section(yaml_data, 'servers')
                    if servers_section is not None:
                        servers = self._get_keys(servers_section)
                        for server in servers:
                            server_info = self._get_section(servers_section, server)
                            url = self._get_yaml_option(server_info, "url")
                            if url is not None:
                                apikey = self._get_yaml_option(server_info, "apikey")
                                nlu_collection.add_server(server, url, apikey, filename, server_index)
                            else:
                                error_info = "url parameter not found in servers"
                                nlu_collection.set_servers_error(filename, server_index, error_info)
                            server_index += 1

                    if nlu_collection.set_matchlist is True:
                        nlu_section = self._get_section(yaml_data, 'nlu')
                        if nlu_section is not None:
                            if type(nlu_section) is not list:
                                nlu_section = [nlu_section]
                            for server_info in nlu_section:
                                name = self._get_yaml_option(server_info, "name")
                                if name is not None:
                                    if nlu_collection.server_info(name) is None:
                                        error_info = "server[%s] not found" % name
                                        nlu_collection.set_nlus_error(filename, nlu_index, error_info)
                                        nlu_index += 1
                                        continue
                                url = self._get_yaml_option(server_info, "url")
                                if url is not None:
                                    if name is not None:
                                        error_info = "exist both parameters name[%s] and url[%s]" % (name, url)
                                        nlu_collection.set_nlus_error(filename, nlu_index, error_info)
                                    else:
                                        apikey = self._get_yaml_option(server_info, "apikey")
                                        nlu_collection.add_nlu_by_url(url, apikey, filename, nlu_index)
                                else:
                                    if name is not None:
                                        nlu_collection.add_nlu_by_name(name, filename, nlu_index)
                                    else:
                                        error_info = "url parameter not found in nlu"
                                        nlu_collection.set_nlus_error(filename, nlu_index, error_info)
                                nlu_index += 1
                        else:
                            error_info = "nlu section not found"
                            nlu_collection.set_nlus_error(filename, 0, error_info)

                        timeout_val = self._get_section(yaml_data, 'timeout')
                        if timeout_val is not None:
                            timeout = 0
                            if type(timeout_val) is int:
                                timeout = timeout_val
                            elif type(timeout_val) is str:
                                try:
                                    timeout = int(timeout)
                                except Exception:
                                    pass
                            if timeout > 0:
                                nlu_collection.timeout = timeout
                            else:
                                nlu_collection.set_timeout_error(filename, timeout_val)

        except Exception as excep:
            YLogger.exception(self, "Failed to load NLU_Servers [%s]", excep, filename)
            error_info = "illegal yaml format"
            nlu_collection.set_servers_error(filename, 0, error_info)
Exemple #56
0
 def resolve_to_string(self, client_context):
     conversation = client_context.bot.get_conversation(client_context)
     question = conversation.previous_nth_question(self.index)
     resolved = question.combine_sentences()
     YLogger.debug(client_context, "[%s] resolved to [%s]", self.to_string(), resolved)
     return resolved
Exemple #57
0
    def load_configuration(self,
                           configuration_file,
                           bot_root,
                           subs: Substitutions = None):
        bot = configuration_file.get_section(self.section_name)
        if bot is not None:

            self._default_response = configuration_file.get_option(
                bot,
                "default_response",
                BotConfiguration.DEFAULT_RESPONSE,
                subs=subs)
            self._default_response_srai = configuration_file.get_option(
                bot,
                "default_response_srai",
                BotConfiguration.DEFAULT_RESPONSE_SRAI,
                subs=subs)
            self._empty_string = configuration_file.get_option(
                bot,
                "empty_string",
                BotConfiguration.DEFAULT_EMPTY_STRING,
                subs=subs)
            self._exit_response = configuration_file.get_option(
                bot,
                "exit_response",
                BotConfiguration.DEFAULT_EXIT_RESPONSE,
                subs=subs)
            self._exit_response_srai = configuration_file.get_option(
                bot,
                "exit_response_srai",
                BotConfiguration.DEFAULT_EXIT_RESPONSE_SRAI,
                subs=subs)
            self._initial_question = configuration_file.get_option(
                bot,
                "initial_question",
                BotConfiguration.DEFAULT_INITIAL_QUESTION,
                subs=subs)
            self._initial_question_srai = configuration_file.get_option(
                bot,
                "initial_question_srai",
                BotConfiguration.DEFAULT_INITIAL_QUESTION_SRAI,
                subs=subs)
            self._override_properties = configuration_file.get_option(
                bot,
                "override_properties",
                BotConfiguration.DEFAULT_OVERRIDE_PREDICATES,
                subs=subs)
            self._max_question_recursion = configuration_file.get_int_option(
                bot,
                "max_question_recursion",
                BotConfiguration.DEFAULT_MAX_QUESTION_RECURSION,
                subs=subs)
            self._max_question_timeout = configuration_file.get_int_option(
                bot,
                "max_question_timeout",
                BotConfiguration.DEFAULT_MAX_QUESTION_TIMEOUT,
                subs=subs)
            self._max_search_depth = configuration_file.get_int_option(
                bot,
                "max_search_depth",
                BotConfiguration.DEFAULT_MAX_SEARCH_DEPTH,
                subs=subs)
            self._max_search_timeout = configuration_file.get_int_option(
                bot,
                "max_search_timeout",
                BotConfiguration.DEFAULT_MAX_SEARCH_TIMEOUT,
                subs=subs)
            self._tab_parse_output = configuration_file.get_bool_option(
                bot,
                "tab_parse_output",
                BotConfiguration.DEFAULT_TAB_PARSE_OUTPUT,
                subs=subs)

            self._spelling.load_config_section(configuration_file,
                                               bot,
                                               bot_root,
                                               subs=subs)

            self._conversations.load_config_section(configuration_file,
                                                    bot,
                                                    bot_root,
                                                    subs=subs)

            self._splitter.load_config_section(configuration_file,
                                               bot,
                                               bot_root,
                                               subs=subs)

            self._joiner.load_config_section(configuration_file,
                                             bot,
                                             bot_root,
                                             subs=subs)

            self._from_translator.load_config_section(configuration_file,
                                                      bot,
                                                      bot_root,
                                                      subs=subs)

            self._to_translator.load_config_section(configuration_file,
                                                    bot,
                                                    bot_root,
                                                    subs=subs)

            self._sentiment.load_config_section(configuration_file,
                                                bot,
                                                bot_root,
                                                subs=subs)

        else:
            YLogger.warning(
                self, "Config section [%s] missing, using default values",
                self.section_name)

        self.load_configurations(configuration_file, bot, bot_root, subs)
Exemple #58
0
 def link_accounts(self, primary_userid, linked_userid):
     YLogger.info(self, "Linking accounts [%s] [%s] in Mongo",
                  primary_userid, linked_userid)
     linked = LinkedAccount(primary_userid, linked_userid)
     return self.add_document(linked)
Exemple #59
0
 def receive_message():
     try:
         return KIK_CLIENT.receive_message(request)
     except Exception as e:
         YLogger.exception(None, "KIK Error", e)
Exemple #60
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")