Ejemplo n.º 1
0
 def send_response(self, user_id: int, response: dict) -> bool:
     print(response)
     if not (response):
         return False
     if 'attachments' in response:
         attachments = ','.join(response['attachments'])
     else:
         attachments = ''
     if 'text' in response:
         text = response['text']
     else:
         text = ''
     if not (text) and not (attachments):
         return False
     reply = False
     try:
         reply = self.vk_api.messages.send(user_id=user_id,
                                           message=text,
                                           attachment=attachments)
     except BaseException as e:
         msg = "Send : " + str(e)
         logger.log_error(msg)
         print(msg)
         return False
     return bool(reply)
Ejemplo n.º 2
0
 def get_dialog(self, offset=0) -> list:
     try:
         dialog = self.vk_api.messages.getDialogs(offset=offset)
     except BaseException as e:
         msg = 'Error: ' + self.id + " : " + str(e)
         logger.log_error(msg)
         print(msg)
         raise StopIteration
     return dialog
Ejemplo n.º 3
0
 def get_template(self, tmp_name: str) -> 'Template':
     """Возвращает объект шаблолна"""
     try:
         tmp = get_template(tmp_name)
     except TemplateDoesNotExist as e:
         msg = "Error: " + e
         log_error(msg)
         print(msg)
         return False
     return tmp
Ejemplo n.º 4
0
def exec_script(path_dir: 'str', message: 'request') -> 'response':
    """Передает запрос указанному скрипту"""
    path_to_script = path_dir.replace('/', '.').replace('\\', '.')
    global g
    code = "from " + path_to_script + ".index import get_answer; g = get_answer"
    exec(code, globals())
    if not (callable(g)):
        msg = 'get_answer is not callable'
        logger.log_error(msg)
        raise AttributeError(msg)
    return g(message, Tools(path_dir), logger)
Ejemplo n.º 5
0
 def read_file(self, file: str, encoding='utf8') -> str:
     """Читает файл, с выбранной кодировкой и возвращает содержимое"""
     try:
         f = open(path.join(self.path, file), 'r', encoding=encoding)
     except FileNotFoundError as e:
         msg = "Error: " + str(e)
         log_error(msg)
         print(msg)
         return False
     text = f.read()
     f.close()
     return text
Ejemplo n.º 6
0
 def render_template(self, tmp_name: str, values: dict) -> str:
     """Возвращает отрендеренный шаблон"""
     tmp = self.get_template(tmp_name)
     if not (tmp):
         return False
     try:
         return tmp.render(values)
     except TemplateSyntaxError as e:
         msg = "Error: " + str(e)
         log_error(msg)
         print(msg)
         return False
Ejemplo n.º 7
0
 def error_handle():
     """Обрабатывает ошибку"""
     if path.exists("scripts/error/index.py"):
         error_response = start_script("scripts/error")
         if not (error_response):
             return False
         if 'response' not in error_response:
             return False
         return error_response['response']
     else:
         msg = "Didn't find error.py file"
         logger.log_error(msg)
         raise FileNotFoundError(msg)
Ejemplo n.º 8
0
 def get_request(self, user_id: int) -> dict:
     try:
         history = self.vk_api.messages.getHistory(user_id=user_id)
     except BaseException as e:
         msg = "Error: " + self.id + " : " + str(e)
         logger.log_error(msg)
         print(msg)
         return False
     current_message = history[1]
     request = {}
     request['text'] = current_message['body']
     request['user_id'] = current_message['uid']
     if 'attachments' in current_message:
         request['attachments'] = current_message['attachments']
     else:
         request['attachments'] = []
     request['msg_id'] = current_message['mid']
     return request
Ejemplo n.º 9
0
def get_response(accaunt: str, user: str, text: str,
                 message: '*') -> 'response':
    """Возвращает ответ бота"""
    def error_handle():
        """Обрабатывает ошибку"""
        if path.exists("scripts/error/index.py"):
            error_response = start_script("scripts/error")
            if not (error_response):
                return False
            if 'response' not in error_response:
                return False
            return error_response['response']
        else:
            msg = "Didn't find error.py file"
            logger.log_error(msg)
            raise FileNotFoundError(msg)

    def start_script(path_to_dir) -> 'response':
        """Запускает указанный скрипт"""
        tools = middlewares_tools
        request = message
        response = exec_script(path_to_dir, request)
        changed_data = False
        for middleware in middlewares:
            if changed_data:
                middleware.set_new(accaunt, user, text, request)
            middleware.set_response(response)
            try:
                middleware.process_response(tools, logger)
            except AttributeError:
                continue
            accaunt = middleware.accaunt_id
            user = middleware.user_id
            text = middleware.text
            request = middleware.request
            response = middleware.response
            changed_data = True
        return response

    middlewares = []
    middlewares_tools = Tools('middlewares')
    for middleware in BOT_MIDDLEWARES:
        middleware_path = path.join('middlewares', middleware + '.py')
        if not path.exists(middleware_path):
            msg = middleware + " middleware do not found"
            logger.log_error(msg)
            raise FileNotFoundError(msg)
        code = "from middlewares." + middleware + " import " + middleware + " as cmw; mw = cmw"
        exec(code, globals())
        current_middleware = mw(accaunt, user, text, message)
        middlewares.insert(0, current_middleware)
        try:
            current_middleware.process_request(middlewares_tools, logger)
        except AttributeError:
            continue
        if current_middleware.response != None:
            return current_middleware.response
        accaunt = current_middleware.accaunt_id
        user = current_middleware.user_id
        text = current_middleware.text
        message = current_middleware.request
    if not (text):
        return error_handle()
    if path.exists(path.join("globals", text)):
        global_response = start_script(path.join("globals", text))
        if not (global_response):
            return False
        if 'response' not in global_response:
            return False
        return global_response['response']
    users = Step.objects.filter(user_id=user)
    if not (len(users)):
        new_step = Step(user_id=user, step='')
        new_step.save()
        current_user = new_step
        if path.exists('responses/index.py'):
            return start_script('responses')
    else:
        current_user = users[0]
    text = text.replace('.', '').replace("/", '').replace('\\', '')
    text = modify_text(text)
    current_mode = current_user.step
    mode = path.join(current_mode, text)
    answer = False
    path_to_script = path.join("responses", mode)
    if path.exists(path.join(path_to_script, 'index.py')):
        answer = start_script(path_to_script)
    elif path.exists(path.join(path_to_script, "link.txt")):
        #получаем имя ссылки
        link_file = open(path.join(path_to_script, "link.txt"),
                         'r',
                         encoding='utf8')
        link = link_file.read()
        link_file.close()
        if path.exists(path.join("scripts", link)):
            answer = start_script(path.join("scripts", link))
        else:
            msg = "Didn't find a message file"
            logger.log_error(msg)
            raise FileNotFoundError(msg)
    else:
        return error_handle()
    #если ответ отсутствует, возвращаем False
    if not (answer):
        return False

    if answer['end']:
        #удаляем информацию о пользователе, если диалог закончился
        Step.objects.filter(user_id=user)[0].delete()
    elif answer['save']:
        #изменяем шаг пользователя, на следующий
        user_step = Step.objects.filter(user_id=user)[0]
        user_step.step = mode
        user_step.save()
    return answer['response']
Ejemplo n.º 10
0
def main():
    schema = open('schema.ini', 'r', encoding='utf8')
    mode = ''
    main_path = 'responses'
    path_count = -1
    for line in schema:
        line = line.strip()
        if not (line) or line[0] == '#': continue
        #если это определение типа, то сохраняем его
        if line[0] != '-':
            mode = line.lower()
            continue
        command = line[1:]
        #проверка типа
        if mode == 'globals' or mode == 'scripts':
            # инициализируем каталог
            create_path(mode)
            create_file(path.join(mode, '__init__.py'))
            path_name = path.join(mode, command)
            path_name = create_path(path_name)
            init_work_path(path_name)
        elif mode == 'templates':
            create_path('tmp')
            create_file(path.join('tmp', command))
        elif mode == 'responses':
            create_path(mode)
            create_file(path.join(mode, '__init__.py'))
            #уровень вложенности
            current_path_count = 0
            while command[0] == '-':
                command = command[1:]
                current_path_count += 1
            #если вложенность отсутсвует - сбрасываем ее
            while current_path_count <= path_count:
                main_path = path.dirname(main_path)
                path_count -= 1
            path_count = current_path_count
            #проверяем наличие указателя на ссылку
            link_name = ''
            if match('.+\/link\/.+', command):
                link_name = path.basename(command)
                command = path.dirname(path.dirname(command))
            #добавляем необходимые файлы в каталог команды
            current_main_path = path.join(main_path, command)
            path_name = create_path(current_main_path)
            if link_name:
                create_file(path.join(path_name, 'link.txt'), link_name)
            else:
                init_work_path(path_name)
            main_path = path_name
        else:
            raise TypeError(mode + ' is a unknown mode')
    schema.close()
    create_path('log')
    create_path('scripts')
    create_path(path.join('scripts', 'error'))
    init_work_path(path.join('scripts', 'error'))

    #обновляем поля базы данных
    for type in OBJECTS_TYPES:
        if not (check_name(type)):
            msg = type + " is incorrect type name"
            log_error(msg)
            raise ValueError(msg)

        current_type = Types.objects.filter(name=type)
        if len(current_type) == 0:
            new_type = Types(name=type)
            new_type.save()
            type_id = new_type.id
        else:
            type_id = current_type[0].id
        for type_value in OBJECTS_TYPES[type]['values']:
            if not (check_name(type_value)):
                msg = type_value + " is incorrect value name"
                log_error(msg)
                raise ValueError(msg)
            current_value = Fields.objects.filter(name=type_value)
            if len(current_value) == 0:
                new_value = Fields(type_id=type_id, name=type_value)
                new_value.save()
        for added_field in Fields.objects.filter(type_id=type_id):
            if not (added_field.name in OBJECTS_TYPES[type]['values']):
                added_field.delete()
    for added_type in Types.objects.all():
        if added_type.name not in OBJECTS_TYPES:
            added_type.delete()

    if len(middlewares) != 0:
        create_path('middlewares')
        create_file(path.join('middlewares', '__init__.py'))
    for middleware in middlewares:
        mw_import = "from core.middleware import Middleware\n\n"
        mw_class = "class " + middleware + "(Middleware):\n\t"
        def_request = "def process_request(self, Tools, Logger): pass\n\t"
        def_response = "def process_response(self, Tools, Logger): pass\n\t"
        code = mw_import + mw_class + def_request + def_response
        create_file(path.join('middlewares', middleware + '.py'), code)