Beispiel #1
0
    async def test_adds_event_on_subscribe(self):
        async def foo():
            pass

        messenger = Messenger()
        messenger.subscribe('bar', foo)
        assert 'bar' in messenger._events.keys()
Beispiel #2
0
    async def test_subscribe_with_sync_method_raises_typeerror(self):
        def foo():
            pass

        messenger = Messenger()
        with pytest.raises(TypeError):
            messenger.subscribe('bar', foo)
Beispiel #3
0
def main():

    if not os.path.exists('Logs'):
        os.makedirs('Logs')
    #sets up the logging for discord.py
    disc_log = logging.getLogger('discord')
    disc_log.setLevel(logging.DEBUG)
    disc_log_name = Path(
        f'Logs/{datetime.now().strftime("%Y-%m-%d-%H.%M.%S")}_discord.log')
    handler = logging.FileHandler(filename=disc_log_name,
                                  encoding='utf-8',
                                  mode='w')
    handler.setFormatter(
        logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
    disc_log.addHandler(handler)

    #creates the logger for the Bot Itself
    setup_logger()
    bot_log = logging.getLogger('bot')
    bot_log_name = Path(
        f'Logs/{datetime.now().strftime("%Y-%m-%d-%H.%M.%S")}_bot.log')
    bot_file_handle = logging.FileHandler(filename=bot_log_name,
                                          encoding='utf-8',
                                          mode='w')
    bot_file_handle.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    bot_log.addHandler(bot_file_handle)

    try:
        bot_log.info(f'Attempting to load BotSecrets.json from {os.getcwd()}')
        with open("BotSecrets.json") as f:
            BotSecrets.get_instance().load_secrets(f.read())
    except FileNotFoundError as e:
        bot_log.error(f'{e}: The bot could not find your BotSecrets Json File')
        sys.exit(0)
    except KeyError as e:
        bot_log.error(f'{e} is not a valid key in BotSecrets')
        sys.exit(0)
    except Exception as e:
        bot_log.error(e)

    token = os.environ.get('BotToken', None)

    if token is not None:
        BotSecrets.get_instance().bot_token = token

    prefix = BotSecrets.get_instance().bot_prefix

    #Initialize the messenger here and inject it into the base bot class,
    #this is so it can be reused later on
    #if we decide to add something not related to the bot
    # E.G a website frontend
    messenger = Messenger(name='primary_bot_messenger')

    bot_log.info('Bot Starting Up')
    ClemBot(
        command_prefix=prefix,  # noqa: E126
        messenger=messenger,
        max_messages=5000).run(BotSecrets.get_instance().bot_token)
Beispiel #4
0
def main():
    bot_log = logging.getLogger()

    # check if this is a prod or a dev instance
    if bool(os.environ.get('PROD')):
        bot_log.info('Production env var found, loading production environment')
        bot_secrets.secrets.load_production_secrets()
    else:
        try:
            bot_log.info(f'Attempting to load BotSecrets.json from {os.getcwd()}')
            with open("BotSecrets.json") as f:
                bot_secrets.secrets.load_development_secrets(f.read())
        except FileNotFoundError as e:
            bot_log.fatal(f'{e}: The bot could not find your BotSecrets Json File')
            sys.exit(0)
        except KeyError as e:
            bot_log.fatal(f'{e} is not a valid key in BotSecrets')
            sys.exit(0)
        except Exception as e:
            bot_log.fatal(e)
            sys.exit(0)

    # get the default prefix for the bot instance
    prefix = bot_secrets.secrets.bot_prefix

    # Initialize the messenger here and inject it into the base bot class,
    # this is so it can be reused later on
    # if we decide to add something not related to the bot
    # E.G a website frontend
    messenger = Messenger(name='primary_bot_messenger')

    # create the custom prefix handler class
    custom_prefix = CustomPrefix(default=prefix)

    # enable privileged member gateway intents
    intents = discord.Intents.default()
    intents.members = True

    # Create the scheduler for injection into the bot instance
    scheduler = Scheduler()

    # set allowed mentions
    mentions = discord.AllowedMentions(everyone=False, roles=False)

    bot_log.info('Bot Starting Up')
    ClemBot(
        messenger=messenger,
        scheduler=scheduler,
        command_prefix=custom_prefix.get_prefix,  # noqa: E126
        activity=discord.Game(name='https://clembot.io'),
        help_command=None,
        case_insensitive=True,
        max_messages=50000,
        allowed_mentions=mentions,
        intents=intents
    ).run(bot_secrets.secrets.bot_token)
Beispiel #5
0
    async def test_adds_two_listeners(self):
        async def foo():
            pass

        async def bar():
            pass

        messenger = Messenger()
        messenger.subscribe('baz', foo)
        messenger.subscribe('baz', bar)

        assert len(messenger._events['baz']) == 2
Beispiel #6
0
    async def test_publish_event_invokes_listener(self):
        messenger = Messenger()

        class Foo:
            def __init__(self):
                self.mock = mock.Mock()

            async def async_mock(self, *args, **kwargs):
                self.mock(*args, **kwargs)

        foo = Foo()
        messenger.subscribe('bar', foo.async_mock)
        await messenger.publish('bar')

        foo.mock.assert_called_once_with()
Beispiel #7
0
    async def test_delete_dead_ref(self):
        messenger = Messenger()

        class Foo:
            def __init__(self):
                self.async_mock1 = mock.Mock()

            async def async_1(self, *args, **kwargs):
                self.async_mock1(*args, **kwargs)

        foo = Foo()
        messenger.subscribe('bar', foo.async_1)
        del foo
        await messenger.publish('bar')

        assert len(messenger._events['bar']) == 0
Beispiel #8
0
    async def test_publish_event_invokes_listener_twice(self):
        messenger = Messenger()

        class Foo:
            def __init__(self):
                self.async_mock1 = mock.Mock()

            async def async_1(self, *args, **kwargs):
                self.async_mock1(*args, **kwargs)

        foo = Foo()
        messenger.subscribe('bar', foo.async_1)
        await messenger.publish('bar')
        await messenger.publish('bar')

        assert foo.async_mock1.call_count == 2
Beispiel #9
0
    async def test_publish_event_invokes_two_listeners(self):
        messenger = Messenger()

        class Foo:
            def __init__(self):
                self.async_mock1 = mock.Mock()
                self.async_mock2 = mock.Mock()

            async def async_1(self, *args, **kwargs):
                self.async_mock1(*args, **kwargs)

            async def async_2(self, *args, **kwargs):
                self.async_mock2(*args, **kwargs)

        foo = Foo()
        messenger.subscribe('bar', foo.async_1)
        messenger.subscribe('bar', foo.async_2)
        await messenger.publish('bar')

        foo.async_mock1.assert_called_once_with()
        foo.async_mock2.assert_called_once_with()
Beispiel #10
0
 async def test_subscribe_with_none_raises_typeerror(self):
     messenger = Messenger()
     with pytest.raises(TypeError):
         messenger.subscribe('bar', None)
Beispiel #11
0
def main():

    if not os.path.exists('Logs'):
        os.makedirs('Logs')
    #sets up the logging for discord.py
    disc_log = logging.getLogger('discord')
    disc_log.setLevel(logging.DEBUG)
    disc_log_name = Path(
        f'Logs/{datetime.now().strftime("%Y-%m-%d-%H.%M.%S")}_discord.log')
    handler = logging.FileHandler(filename=disc_log_name,
                                  encoding='utf-8',
                                  mode='w')
    handler.setFormatter(
        logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
    disc_log.addHandler(handler)

    #creates the logger for the Bot Itself
    setup_logger()
    bot_log = logging.getLogger('bot')
    bot_log_name = Path(
        f'Logs/{datetime.now().strftime("%Y-%m-%d-%H.%M.%S")}_bot.log')
    bot_file_handle = logging.FileHandler(filename=bot_log_name,
                                          encoding='utf-8',
                                          mode='w')
    bot_file_handle.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    bot_log.addHandler(bot_file_handle)

    #check if this is a prod or a dev instance
    if bool(os.environ.get('PROD')):
        bot_log.info('Production env var found, loading production enviroment')
        BotSecrets.get_instance().load_production_secrets()
    else:
        try:
            bot_log.info(
                f'Attempting to load BotSecrets.json from {os.getcwd()}')
            with open("BotSecrets.json") as f:
                BotSecrets.get_instance().load_development_secrets(f.read())
        except FileNotFoundError as e:
            bot_log.error(
                f'{e}: The bot could not find your BotSecrets Json File')
            sys.exit(0)
        except KeyError as e:
            bot_log.error(f'{e} is not a valid key in BotSecrets')
            sys.exit(0)
        except Exception as e:
            bot_log.error(e)

    #get the default prefix for the bot instance
    prefix = BotSecrets.get_instance().bot_prefix

    #Initialize the messenger here and inject it into the base bot class,
    #this is so it can be reused later on
    #if we decide to add something not related to the bot
    # E.G a website frontend
    messenger = Messenger(name='primary_bot_messenger')

    #create the custom prefix handler class, and register its methods
    #as event callbacks
    custom_prefix = CustomPrefix(default=prefix)
    messenger.subscribe(Events.on_set_custom_prefix, custom_prefix.set_prefix)

    #enable privileged member gateway intents
    intents = discord.Intents.default()
    intents.members = True

    #Create the scheduler for injection into the bot instance
    scheduler = Scheduler()

    #set allowed mentions
    mentions = discord.AllowedMentions(everyone=False, roles=False)

    bot_log.info('Bot Starting Up')
    ClemBot(
        messenger=messenger,
        scheduler=scheduler,
        command_prefix=custom_prefix.get_prefix,  # noqa: E126
        help_command=None,
        case_insensitive=True,
        max_messages=50000,
        allowed_mentions=mentions,
        intents=intents).run(BotSecrets.get_instance().bot_token)