示例#1
0
    def parse_criteria(cls, criteria):
        result = ''
        for key in criteria:
            if type(criteria[key]) == dict:
                if key.upper() == 'NOT':
                    result += ' NOT (%s) ' % cls.parse_criteria(criteria[key])
                elif key.upper() in ['AND', 'OR']:
                    result += ' ('
                    #parse each value in criteria[key] and stick key in between them
                    innerResults = []
                    for innerKey in criteria[key]:
                        innerResults.append(cls.parse_criteria({innerKey: criteria[key][innerKey]}))
                    result += key.upper().join(innerResults)
                    result += ') '
                else:
                    Logger.get_logger(__name__).warn('I\'m sorry, I don\'t speak idiot. Couldn\'t parse operator declaration: %s', key)
            else:
                if type(criteria[key]) == str:
                    result += ' %s = "%s" ' % (key, criteria[key])
                else:
                    result += ' %s = %s ' % (key, criteria[key])

        if result == '':
            result = '1'

        return result
示例#2
0
    def start(self):
        Logger.setup_logger(filename=configuration.LOG_FILE)
        logger = Logger.get_logger()
        logger.info("Action Daemon started running.")

        db_conn, rabbit_conn = None, None

        try:
            # creating connection to Postgres and reading data
            db_conn = Connector().get_postgres_conn()
            actions_conn = PostgresModel(db_conn)
            actions = actions_conn.read()

            # creating connection to Rabbit and sending data
            rabbit_conn = Connector().get_rabbit_conn()
            rabbit = RabbitModel(rabbit_conn, actions)
            rabbit.send()

            logger.info("Action Daemon terminated normally.")
        except Exception as e:
            logger.error('Error: {}'.format(e))
        finally:
            if db_conn and rabbit_conn:
                db_conn.close()
                rabbit_conn.close()
示例#3
0
    def __init__(self):
        # logging
        self.logger = Logger.get_logger(__name__)

        # tvrobot core object
        # self.tvrobot = TvRobot()

        # static handlers
        handlers = [
            (r'/sms', SMSHandler),
            (r'/event', EventHandler),
        ]
        # tornado app settings
        settings = dict(
            debug = False,
            cookie_secret = config.TVROBOT['API']['cookie_secret']
        )
        # init app with settings and static handlers
        tornado.web.Application.__init__(self, handlers, **settings)

        self.logger.info('API initialized successfully')
示例#4
0
class Yueri(discord.Client):
    # Get list of Discord permissions
    Discord_Permissions = [
        prop for prop, value in vars(discord.Permissions).items()
        if isinstance(value, property)
    ]

    def __init__(self, config):
        super(Yueri, self).__init__()
        self.config = config
        self.log = Logger(config['Logging'])
        self._logger = self.log.get_logger('Client')
        self._logger.info('Starting up')

        self.prefix = config['Client']['prefix']
        self.db = Database(self)
        self.plugin_manager = PluginManager(self)
        self.influx = Influx(self)

    def check_permissions(self, user: Union[discord.Member, discord.User],
                          permitted_groups: list) -> bool:
        if not permitted_groups:
            return True

        permissions = self.config['Permissions']
        # Check against permission groups in config
        allowed_groups = list(
            filter(lambda g: g if g not in self.Discord_Permissions else None,
                   permitted_groups))
        for group in allowed_groups:
            # Check user IDs
            if 'users' in permissions[group].keys():
                if user.id in permissions[group]['users']:
                    return True
            # Check role IDs
            if 'roles' in permissions[group].keys():
                for role in user.roles:
                    if role.id in permissions[group]['roles']:
                        return True

        # Check user permissions
        allowed_permissions = list(
            filter(lambda p: p if p in self.Discord_Permissions else None,
                   permitted_groups))
        for permission in allowed_permissions:
            if getattr(user.guild_permissions, permission, False):
                return True

        return False

    #  _____                 _         _ _                 _       _
    # | ____|_   _____ _ __ | |_    __| (_)___ _ __   __ _| |_ ___| |__   ___ _ __ ___
    # |  _| \ \ / / _ \ '_ \| __|  / _` | / __| '_ \ / _` | __/ __| '_ \ / _ \ '__/ __|
    # | |___ \ V /  __/ | | | |_  | (_| | \__ \ |_) | (_| | || (__| | | |  __/ |  \__ \
    # |_____| \_/ \___|_| |_|\__|  \__,_|_|___/ .__/ \__,_|\__\___|_| |_|\___|_|  |___/
    #                                         |_|

    async def on_connect(self):
        self._logger.info('Established connection to Discord')

    async def on_ready(self):
        self._logger.info(
            f'Logged in as {self.user.name}#{self.user.discriminator} with user ID {self.user.id}'
        )
        for plugin in self.plugin_manager.events.get('on_ready', []):
            # Server check, if bot is not in any of the guilds, skip the event execution for this plugin
            servers = getattr(plugin, 'servers', ())
            if servers and not any(
                [self.get_guild(server_id) for server_id in servers]):
                continue
            await plugin.on_ready()

    async def on_socket_response(self, msg: dict):
        # Latency monitoring
        if msg.get('op') == DiscordWebSocket.HEARTBEAT_ACK:
            await self.influx.write({
                'measurement': 'latency',
                'fields': {
                    'ms': self.latency * 1000
                }
            })

    async def on_message(self, message: discord.Message):
        await self.influx.write({
            'measurement': 'events',
            'fields': {
                'event': 'on_message'
            },
            'tags': {
                'event': 'on_message'
            }
        })

        # Return if there are no plugins with `on_message` implemented
        if 'on_message' not in self.plugin_manager.events.keys() or \
                'on_message_global' not in self.plugin_manager.events.keys():
            return
        # Ignore direct messages and group channels
        if isinstance(message.channel,
                      (discord.DMChannel, discord.GroupChannel)):
            return
        # Ignore bot users
        if message.author.bot:
            return

        matched_plugins = list(
            self.plugin_manager.events.get('on_message_global')
        )  # wrap in list() to get a copy and not a reference
        # Parse the message
        trigger, args = None, None
        match = re.match(rf'{self.prefix}([^\s]+)\s?(.+)?', message.content)
        if match:
            # Match the trigger with plugins
            trigger, args = match.groups()
            plugins = self.plugin_manager.events['on_message'].get(
                trigger.lower())
            if plugins:
                matched_plugins += plugins

        if not matched_plugins:
            return

        await self.influx.write({
            'measurement': 'events',
            'fields': {
                'event': 'on_command'
            },
            'tags': {
                'event': 'on_command'
            },
        })

        # Execute the matched plugins
        for plugin in matched_plugins:
            # If plugin is server-restricted, do a check
            if plugin.servers and message.guild.id not in plugin.servers:
                continue
            if trigger and plugin.triggers:
                self._logger.info(
                    f"{message.author.name}#{message.author.discriminator} ({message.author.id}) "
                    f"on {message.guild.name} ({message.guild.id}) "
                    f"used command {plugin.name} with trigger {trigger} and arguments: {args}"
                )
            # Permission check
            if getattr(plugin, 'permissions', None):
                if not self.check_permissions(message.author,
                                              plugin.permissions):
                    continue
            # Execute plugin
            await plugin.on_message(message, trigger,
                                    args.split() if args else None)

    async def on_member_join(self, member: discord.Member):
        self._logger.info(
            f"{member.name}#{member.discriminator} ({member.id}) has joined {member.guild.name} ({member.guild.id})"
        )
        for plugin in self.plugin_manager.events.get('on_member_join', []):
            # If plugin is server-restricted, do a check
            servers = getattr(plugin, 'servers', ())
            if servers and member.guild.id not in servers:
                return
            await plugin.on_member_join(member)

    async def on_member_remove(self, member: discord.Member):
        self._logger.info(
            f"{member.name}#{member.discriminator} ({member.id}) has left {member.guild.name} ({member.guild.id})"
        )
示例#5
0
import pika
import psycopg2
from core.logger import Logger

from core.config import configuration

logger = Logger.get_logger()


class Connector:
    def get_postgres_conn(self):
        try:
            return psycopg2.connect(configuration.POSTGRES_LINK)
        except Exception as e:
            logger.error("Unable to connect to the Postgres: {}".format(e))

    def get_rabbit_conn(self):
        try:
            return pika.BlockingConnection(pika.ConnectionParameters(host=configuration.RABBIT_MQ_HOST))
        except Exception as e:
            logger.error("Unable to connect to the Rabbit: {}".format(e))
示例#6
0
 def __init__(self):
     self.logr = Logger.get_logger(__name__)
     self._conn = None
     self._conn = self.__get_conn()
示例#7
0
 def __init__(self, save_to=None):
   self.logger = Logger.get_logger(utils.get_fullname(self))
   self.save_to = save_to or getattr(settings, 'SAVE_DIR')
示例#8
0
 def __init__(self, url=None):
   BaseSourceFeed.__init__(self, url)
   self.logger = Logger.get_logger(utils.get_fullname(self))
   self.logger.debug('Created an instance')
示例#9
0
 def __init__(self):
     self.logr = Logger.get_logger(__name__)
     self._new = False
     for fieldidx in self.FIELDS:
         setattr(self, self.FIELDS[fieldidx], None)
示例#10
0
 def search(cls, criteria = {}):
     logr = Logger.get_logger(__name__)
     pass