# Path: mbot/event.py
# class Event:
# 
#     DEFAULT_PATTERN = r":\s?(\S*['-]*|\w*.+|'[^']+')"
# 
#     def __init__(self, bot, backend, body):
# 
#         self.bot = bot
#         self.backend = backend
#         self.body = body
# 
#     def __repr__(self):
#         return "%s" % self.body
# 
#     @property
#     def user(self):
#         """Return user if is present in body"""
#         return self.get("user", None)
# 
#     def get_template_context(self):
#         """Returns template context"""
#         return {
#             'bot': self.bot,
#             'backend': self.backend,
#             'state': self.bot.state,
#             'msg': self
#         }
# 
#     @property
#     def text(self):
#         """Return text if is present in body"""
#         txt = self.get("text", None)
#         if txt:
#             template = Template(txt)
#             try:
#                 return template.render(self.get_template_context())
#             except Exception as e:
#                 LOG.error("Error rendering template %s with %s" % (
#                     self.text, e))
#         return txt
# 
#     def reply(self, *args, **kwargs):
#         """Simple reply on message
#         """
#         return self.backend.reply(self, *args, **kwargs)
# 
#     def clean(self, value):
#         return re.sub(r"”|“", '"', value)
# 
#     def reply_snippet(self, name, content=None, file=None, format="bash",
#                       ext="sh"):
# 
#         kwargs = {
#             'content': content,
#             'filetype': format,
#             'channels': self.body['channel'],
#             'filename': '.'.join([slugify(name), ext]),
#             'initial_comment': name,
#             'title': slugify(name)
#         }
# 
#         if file:
#             kwargs['file'] = file
# 
#         return self.reply(name,
#                           attachments=[kwargs])
# 
#     def get(self, key, default=None):
#         return self.body.get(key, default)
# 
#     def extract_parameters(self, parameters=None, pattern=None, default=None):
#         """Extract parameters from message
# 
#         TODO: valid required parameters with typo
#         """
#         params = {}
# 
#         for key in parameters or self.parameters:
#             if isinstance(key, (tuple, list)) and len(key) > 1:
#                 _default = key[1]
#                 key = key[0]
#             else:
#                 _default = default
#             param, new_text = self._extract_from_text(key, self.text, pattern)
#             params[key] = self.clean(param) if param else _default
#             _default = default
# 
#         LOG.debug("Parsed parameters: %s from %s" % (params, self.text))
# 
#         return params
# 
#     def _extract_from_text(self, key, text=None, reg=None):
#         """Find `key` in `query`, return its value and a new query w/out the key
# 
#         Case-insensitive, always returns lowercase values.
#         """
# 
#         text = text or self.get("text", None)
# 
#         # match both `key: value` and `key: "value with spaces"`
#         regex = key.lower() + (reg or self.DEFAULT_PATTERN)
#         text = text.lower()
#         match = search(regex, text)
# 
#         if match is None:
#             return None, text
# 
#         value = match.group(1).strip('"')
#         new_text = text[:match.start()] + text[match.end():]
# 
#         return value, new_text
# 
# Path: mbot/utils/packages.py
# def install_package(package, upgrade=True,
#                     target=None):
#     """Install a package on PyPi. Accepts pip compatible package strings.
#     Return boolean if install successful.
#     """
#     # Not using 'import pip; pip.main([])' because it breaks the logger
#     with INSTALL_LOCK:
#         if check_package_exists(package, target):
#             return True
# 
#         _LOGGER.info('Attempting install of %s', package)
#         args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
#         if upgrade:
#             args.append('--upgrade')
#         if target:
#             args += ['--target', os.path.abspath(target)]
# 
#         try:
#             return subprocess.call(args) == 0
#         except subprocess.SubprocessError:
#             _LOGGER.exception('Unable to install pacakge %s', package)
#             return False


import logging
import types
from copy import deepcopy
from mbot.event import Event
from mbot.utils.packages import install_package
                return m

    def disable_middleware(self, name):

        for i, m in enumerate(self.middlewares):
            if m.__name__ == name:
                self._middlewares.pop(i)
                return True

    def enable_middleware(self, name):

        self.load_middlewares([name])

        return True

    def process_events(self, events):
        """Returns new events
        """

        _events = []

        for event in events:

            # skip event types
            msg_type = event.get("type", None)

            if msg_type and self.bot.process_types:
                if msg_type not in self.process_types:
                    continue


# Path: mbot/event.py
# class Event:
# 
#     DEFAULT_PATTERN = r":\s?(\S*['-]*|\w*.+|'[^']+')"
# 
#     def __init__(self, bot, backend, body):
# 
#         self.bot = bot
#         self.backend = backend
#         self.body = body
# 
#     def __repr__(self):
#         return "%s" % self.body
# 
#     @property
#     def user(self):
#         """Return user if is present in body"""
#         return self.get("user", None)
# 
#     def get_template_context(self):
#         """Returns template context"""
#         return {
#             'bot': self.bot,
#             'backend': self.backend,
#             'state': self.bot.state,
#             'msg': self
#         }
# 
#     @property
#     def text(self):
#         """Return text if is present in body"""
#         txt = self.get("text", None)
#         if txt:
#             template = Template(txt)
#             try:
#                 return template.render(self.get_template_context())
#             except Exception as e:
#                 LOG.error("Error rendering template %s with %s" % (
#                     self.text, e))
#         return txt
# 
#     def reply(self, *args, **kwargs):
#         """Simple reply on message
#         """
#         return self.backend.reply(self, *args, **kwargs)
# 
#     def clean(self, value):
#         return re.sub(r"”|“", '"', value)
# 
#     def reply_snippet(self, name, content=None, file=None, format="bash",
#                       ext="sh"):
# 
#         kwargs = {
#             'content': content,
#             'filetype': format,
#             'channels': self.body['channel'],
#             'filename': '.'.join([slugify(name), ext]),
#             'initial_comment': name,
#             'title': slugify(name)
#         }
# 
#         if file:
#             kwargs['file'] = file
# 
#         return self.reply(name,
#                           attachments=[kwargs])
# 
#     def get(self, key, default=None):
#         return self.body.get(key, default)
# 
#     def extract_parameters(self, parameters=None, pattern=None, default=None):
#         """Extract parameters from message
# 
#         TODO: valid required parameters with typo
#         """
#         params = {}
# 
#         for key in parameters or self.parameters:
#             if isinstance(key, (tuple, list)) and len(key) > 1:
#                 _default = key[1]
#                 key = key[0]
#             else:
#                 _default = default
#             param, new_text = self._extract_from_text(key, self.text, pattern)
#             params[key] = self.clean(param) if param else _default
#             _default = default
# 
#         LOG.debug("Parsed parameters: %s from %s" % (params, self.text))
# 
#         return params
# 
#     def _extract_from_text(self, key, text=None, reg=None):
#         """Find `key` in `query`, return its value and a new query w/out the key
# 
#         Case-insensitive, always returns lowercase values.
#         """
# 
#         text = text or self.get("text", None)
# 
#         # match both `key: value` and `key: "value with spaces"`
#         regex = key.lower() + (reg or self.DEFAULT_PATTERN)
#         text = text.lower()
#         match = search(regex, text)
# 
#         if match is None:
#             return None, text
# 
#         value = match.group(1).strip('"')
#         new_text = text[:match.start()] + text[match.end():]
# 
#         return value, new_text
# 
# Path: mbot/utils/packages.py
# def install_package(package, upgrade=True,
#                     target=None):
#     """Install a package on PyPi. Accepts pip compatible package strings.
#     Return boolean if install successful.
#     """
#     # Not using 'import pip; pip.main([])' because it breaks the logger
#     with INSTALL_LOCK:
#         if check_package_exists(package, target):
#             return True
# 
#         _LOGGER.info('Attempting install of %s', package)
#         args = [sys.executable, '-m', 'pip', 'install', '--quiet', package]
#         if upgrade:
#             args.append('--upgrade')
#         if target:
#             args += ['--target', os.path.abspath(target)]
# 
#         try:
#             return subprocess.call(args) == 0
#         except subprocess.SubprocessError:
#             _LOGGER.exception('Unable to install pacakge %s', package)
#             return False


# Path: mbot/backends/base.py
import logging
import types
from copy import deepcopy
from mbot.event import Event
from mbot.utils.packages import install_package

                return m

    def disable_middleware(self, name):

        for i, m in enumerate(self.middlewares):
            if m.__name__ == name:
                self._middlewares.pop(i)
                return True

    def enable_middleware(self, name):

        self.load_middlewares([name])

        return True

    def process_events(self, events):
        """Returns new events
        """

        _events = []

        for event in events:

            # skip event types
            msg_type = event.get("type", None)

            if msg_type and self.bot.process_types:
                if msg_type not in self.process_types:
                    continue


            _events.append(Event(self.bot, self, event))