Пример #1
0
 def receive_message():
     try:
         return WEB_CLIENT.receive_message(request)
     except Exception as e:
         outputLog(None, "Error receiving webchat message", e)
         YLogger.exception(None, "Web client error", e)
         return "500"
Пример #2
0
    def receive_message():
        try:
            return ALEXA_CLIENT.receive_message(request)

        except Exception as e:
            outputLog(None, "Alexa failed receiving message", e)
            YLogger.exception(None, "Alexa Error", e)
Пример #3
0
    def extract_list_info(self, tag):
        items = []

        for child in tag.children:

            if child.name is None:
                pass

            elif child.name == 'item':

                for childs_child in child.children:

                    if isinstance(childs_child, Tag):
                        items.append(self.extract_item_info(childs_child))

                    elif isinstance(childs_child, NavigableString):
                        childs_child_text = childs_child.strip()
                        if childs_child_text:
                            items.append({'type': 'text', 'text': childs_child_text})

            else:
                outputLog(self, "Unknown list tag %s" % child.name)

        data = {'type': 'list', 'items': items}
        self.extract_class_attr(tag, data)
        self.extract_id_attr(tag, data)
        return data
Пример #4
0
    def _upload_users(self, yaml_data, verbose=False):
        if 'users' in yaml_data:
            for user_name in yaml_data['users'].keys():

                auth_user = AuthoriseUser(name=user_name)
                result = self.storage_engine.session.add(auth_user)

                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()
                        user_role = UserRole(user=user_name, role=role_name)
                        if verbose is True:
                            outputLog(self, user_role)
                        self.storage_engine.session.add(user_role)

                if 'groups' in yaml_obj:
                    groups_list = yaml_obj['groups']
                    splits = groups_list.split(",")
                    for group_name in splits:
                        group_name = group_name.strip()
                        user_group = UserGroup(user=user_name,
                                               group=group_name)
                        if verbose is True:
                            outputLog(self, user_group)
                        self.storage_engine.session.add(user_group)
Пример #5
0
    def _handle_intent_request(self, client_context, request):

        if 'intent' not in request:
            raise Exception("Invalid request, intent missing!")

        intent = request['intent']

        if 'name' not in intent:
            raise Exception("Invalid intent, name missing!")

        intent_name = intent['name']

        outputLog(self, "Handling [%s] intent..." % intent_name)

        if intent_name == 'AMAZON.CancelIntent':
            return self._handle_cancel_request(client_context,
                                               self._should_leave(intent_name))

        elif intent_name == 'AMAZON.StopIntent':
            return self._handle_stop_request(client_context,
                                             self._should_leave(intent_name))

        elif intent_name == 'AMAZON.HelpIntent':
            return self._handle_help_request(client_context)

        else:
            value = self._extract_question(intent)

            question = self._add_intent(intent_name, value)

            return self._handle_reply_request(client_context, question)
Пример #6
0
    def poll_and_answer(self):

        running = True
        sleepy_time = self._configuration.client_configuration.polling_interval

        try:
            if self._configuration.client_configuration.follow_followers is True:
                YLogger.debug(self, "Following followers")
                self._follow_followers()

            if self._configuration.client_configuration.respond_to_directs:
                YLogger.debug(self, "Checking direct messages")
                self._check_directs()

            YLogger.debug(self, "Sleeping for %d at %s" %(sleepy_time, datetime.datetime.now().strftime("%H:%M:%S")))

        except KeyboardInterrupt:
            running = False

        except RateLimitError:

            outputLog(self, "Rate limit exceeded, check logs!")
            YLogger.error(self, "Rate limit exceeded, sleeping for %d seconds", self._rate_limit_sleep)

            sleepy_time = self._rate_limit_sleep

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

        time.sleep(sleepy_time)

        return running
Пример #7
0
 def load_storage(self):
     self._storage = StorageFactory()
     if self.configuration.client_configuration.storage is not None:
         YLogger.debug(None, "Loading Storage Factory")
         self._storage.load_engines_from_config(self.configuration.client_configuration.storage)
     else:
         outputLog(self, "No storage defined!")
Пример #8
0
    def receive_message():
        try:
            return GOOGLE_CLIENT.receive_message(request)

        except Exception as e:
            outputLog(None, "Failure receiving message", e)
            YLogger.exception(None, "Google Error", e)
Пример #9
0
    def extract_button_info(self, tag):
        text = None
        url = None
        postback = None
        for child in tag.children:

            if child.name is None:
                pass

            elif child.name == 'text':
                text = child.text

            elif child.name == 'url':
                url = child.text

            elif child.name == 'postback':
                postback = child.text

            else:
                outputLog(self, "Unknown button tag %s" % child.name)

        data = {"type": "button", "text": text, "url": url, "postback": postback}
        self.extract_class_attr(tag, data)
        self.extract_id_attr(tag, data)
        return data
Пример #10
0
    def extract_card_info(self, tag):
        image = None
        title = None
        subtitle = None
        buttons = []

        for child in tag.children:

            if child.name is None:
                pass

            elif child.name == 'image':
                image = child.text

            elif child.name == 'title':
                title = child.text

            elif child.name == 'subtitle':
                subtitle = child.text

            elif child.name == 'button':
                button = self.extract_button_info(child)
                buttons.append(button)

            else:
                outputLog(self, "Unknown card tag [%s]" % child.name)

        data = {"type": "card", "image": image, "title": title, "subtitle": subtitle, "buttons": buttons}
        self.extract_class_attr(tag, data)
        self.extract_id_attr(tag, data)
        return data
Пример #11
0
    def ping_service(ping_app: Flask, config: PingResponderConfig):

        if config.ssl_cert_file is not None and \
                config.ssl_key_file is not None:
            context = (config.ssl_cert_file, config.ssl_key_file)

            outputLog(None, "Healthcheck running in https mode")
            try:
                ping_app.run(host=config.host,
                             port=config.port,
                             debug=config.debug,
                             ssl_context=context)

            except Exception as error:
                print("Healthcheck failed to start:", error)

        else:
            outputLog(None, "Healthcheck running in http mode, careful now !")
            try:
                ping_app.run(host=config.host,
                             port=config.port,
                             debug=config.debug)

            except Exception as error:
                print("Healthcheck failed to start:", error)
Пример #12
0
    def init_ping_response(ping_responder):

        if ping_responder.config.host is None:
            YLogger.info(None, "No REST configuration for ping responder")
            outputLog(None,
                      "Healthcheck now running as part of REST Service...")
            return

        outputLog(None, "Healthcheck now running as separate REST Service...")

        ping_app = Flask(ping_responder.config.name)

        if ping_responder.config.url is not None:

            @ping_app.route(ping_responder.config.url, methods=['GET'])
            def ping():  # pylint: disable=unused-variable
                return jsonify(ping_responder.ping())

        if ping_responder.config.shutdown is not None:

            @ping_app.route(ping_responder.config.shutdown, methods=['GET'])
            def shutdown():  # pylint: disable=unused-variable
                ping_responder.stop_ping_service()
                return 'Server shutting down...'

        ping_responder.start_ping_service(ping_app)
Пример #13
0
    def __init__(self, argument_parser=None):
        self._host = None
        self._port = None
        self._queue = None
        self._max_buffer = None
        self._server_socket = None
        self._client_connection = None

        EventBotClient.__init__(self, "Socket", argument_parser)

        if self._host is not None and \
                self._port is not None and \
                self._queue is not None:
            outputLog(
                self, "TCP Socket Client server now listening on %s:%d" %
                (self._host, self._port))
            self._server_socket = self.create_socket_connection(
                self._host, self._port, self._queue, self._max_buffer)
            self._renderer = JSONRenderer(self)

        else:
            outputLog(
                self,
                "TCP Socket Client configuration not defined, unable to create socket!"
            )
Пример #14
0
    def write_yaml(self, filename, data):
        outputLog(self, "Writing new config file to [%s]" % filename)
        try:
            with open(filename, 'w') as outfile:
                yaml.dump(data, outfile, default_flow_style=False)

        except Exception as excep:
            outputLog(self, "Failed to write new config file [%s] - [%s]" % (filename, str(excep)))
Пример #15
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, 'alexa', argument_parser)

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

        self._load_intent_mappings()

        outputLog(self, "Alexa Client loaded")
Пример #16
0
    def connect(self):
        if self._telegram_token is not None:
            self.create_updater(self._telegram_token)
            self.register_handlers()
            return True

        outputLog(self, "No telegram token defined, unable to connect")
        return False
Пример #17
0
 def _process_config_line(self, line, verbose):
     line = line.strip()
     if line[0] != '#':
         processor = self._get_entity(line)
         self.storage_engine.session.add(processor)
         if verbose is True:
             outputLog(self, line)
         return True
     return False
Пример #18
0
 def process_line(self, name, fields, verbose=False):
     if fields and len(fields) == 2:
         result = self.add_to_lookup(fields[0].upper(), fields[1].upper())
         if verbose is True:
             outputLog(
                 self, "Key=[%s], Value={%s]" %
                 (fields[0].upper(), fields[1].upper()))
         return result
     return False
Пример #19
0
    def __init__(self, argument_parser=None):
        self._access_token = None
        FlaskRestBotClient.__init__(self, 'facebook', argument_parser)

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

        self._facebook_bot = self.create_facebook_bot()

        outputLog(self, "Facebook Client loaded")
Пример #20
0
    def unregister_with_healthchecker(self):

        if self.config.unregister is not None:
            try:
                url = "%s?name=%s" % (self.config.unregister, self._client.id)
                requests.get(url)
            except Exception as e:
                outputLog(self, e)
                YLogger.error(None, "Unable to unregister with healthchecker")
Пример #21
0
    def __init__(self, argument_parser=None):
        FlaskRestBotClient.__init__(self, 'twilio', argument_parser)

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

        self.get_license_keys()

        self._twilio_client = self.create_twilio_client()

        outputLog(self, "Twilio Client loaded")
Пример #22
0
    def to_aiml(self):
        if self.actiontype == 'web_url':
            aiml = "<link>"
            aiml += "<text>%s</text>" % self.label
            if self.payload is not None:
                aiml += "<url>%s</url>" % self.payload
            aiml += "</link>"
            return aiml

        outputLog(None, "Unknown Default Action type [%s]" % self.actiontype)
        return None
Пример #23
0
    def to_aiml(self):
        if self.actiontype == 'web_url':
            aiml = "<button>"
            aiml += "<text>%s</text>" % self.label
            if self.payload is not None:
                aiml += "<url>%s</url>" % self.payload
            aiml += "</button>"
            return aiml

        outputLog(self, "Unknown Button type [%s]" % self.actiontype)
        return None
Пример #24
0
 def display_debug_info(self):
     if self._errors is not None:
         outputLog(
             self,
             "Found a total of %d errors in your grammars, check your errors store"
             % len(self._errors))
     if self._duplicates is not None:
         outputLog(
             self,
             "Found a total of %d duplicates in your grammars, check your duplicates store"
             % len(self._duplicates))
Пример #25
0
    def _handle_launch_request(self, client_context):
        outputLog(self, "Handling launch...")
        if self.configuration.client_configuration.launch_srai is not None:
            reply = self._ask_question(
                client_context,
                self.configuration.client_configuration.launch_srai)

        else:
            reply = self.configuration.client_configuration.launch_text

        return self._create_response(reply)
Пример #26
0
    def initiate_logging(self, arguments):
        if arguments.logging is not None:
            try:
                with open(arguments.logging, 'r+', encoding="utf-8") as yml_data_file:
                    logging_config = yaml.load(yml_data_file, Loader=yaml.FullLoader)
                    logging.config.dictConfig(logging_config)
                    YLogger.info(self, "Now logging under configuration")

            except Exception as excep:
                YLogger.exception(self, "Failed to open logging configuration [%s]", excep, arguments.logging)

        else:
            outputLog(self, "Warning. No logging configuration file defined, using defaults...")
Пример #27
0
    def load_qandas(self, defaults_qandas):
        if self.arguments.args.qandas is not None:
            try:
                reader = CSVFileReader(self.arguments.args.qandas)
                reader.process_lines("qandas", self)
                return

            except Exception as excep:
                outputLog(
                    self,
                    "Using q&a defaults, as unable to load file [%s], reason[%s]"
                    % (self.arguments.args.qandas, str(excep)))

        self._qandas = defaults_qandas[:]
Пример #28
0
    def run(self, app=None):

        outputLog(
            self, "%s Client running on http://%s:%s" %
            (self.id, self.configuration.client_configuration.host,
             self.configuration.client_configuration.port))

        self.startup()

        if self.configuration.client_configuration.debug is True:
            outputLog(self, "%s Client running in debug mode" % self.id)

        if self.configuration.client_configuration.ssl_cert_file is not None and \
                self.configuration.client_configuration.ssl_key_file is not None:
            context = (self.configuration.client_configuration.ssl_cert_file,
                       self.configuration.client_configuration.ssl_key_file)

            outputLog(self, "%s Client running in https mode" % self.id)
            app.run(host=self.configuration.client_configuration.host,
                    port=self.configuration.client_configuration.port,
                    debug=self.configuration.client_configuration.debug,
                    ssl_context=context)
        else:
            outputLog(
                self,
                "%s Client running in http mode, careful now !" % self.id)
            app.run(host=self.configuration.client_configuration.host,
                    port=self.configuration.client_configuration.port,
                    debug=self.configuration.client_configuration.debug)

        self.shutdown()
Пример #29
0
    def run(args=None):
        parser = ConfigurationWriter.create_arguments()
        try:
            app = ConfigurationWriter()

            if args is None:
                app.execute(parser.parse_args())

            else:
                app.execute(args)

        except Exception as excep:
            outputLog(None, "Error: [%s]" % str(excep))
            parser.print_help()
Пример #30
0
    def _load_services_from_file(self, filename, verbose):

        with open(filename, "r+") as file:
            yaml_data = yaml.load(file, Loader=yaml.FullLoader)

            service_data = yaml_data['service']
            service = self._get_entity(service_data)
            self.storage_engine.session.add(service)

            if verbose is True:
                outputLog(
                    self, "[%s] = [%s]" %
                    (service_data['name'], service_data['service_class']))

        return True