Exemplo n.º 1
0
    def test_when_supports_color(self):
        stack = contextlib.ExitStack()
        stack.enter_context(mock.patch.object(logging, "root", handlers=[]))
        logging_dict_config = stack.enter_context(
            mock.patch.object(logging.config, "dictConfig"))
        logging_basic_config = stack.enter_context(
            mock.patch.object(logging, "basicConfig"))
        colorlog_basic_config = stack.enter_context(
            mock.patch.object(colorlog, "basicConfig"))
        supports_color = stack.enter_context(
            mock.patch.object(ux, "supports_color", return_value=True))

        with stack:
            ux.init_logging("LOGGING_LEVEL", True, False)

        logging_dict_config.assert_not_called()
        logging_basic_config.assert_not_called()
        colorlog_basic_config.assert_called_once_with(
            level="LOGGING_LEVEL",
            format=
            "%(log_color)s%(bold)s%(levelname)-1.1s%(thin)s %(asctime)23.23s %(bold)s%(name)s: "
            "%(thin)s%(message)s%(reset)s",
            stream=sys.stderr,
        )
        supports_color.assert_called_once_with(True, False)
Exemplo n.º 2
0
    def test_when_flavour_is_a_dict_and_doesnt_define_handlers(self):
        stack = contextlib.ExitStack()
        stack.enter_context(mock.patch.object(logging, "root", handlers=[]))
        stack.enter_context(
            mock.patch.object(ux, "supports_color", return_value=False))
        logging_dict_config = stack.enter_context(
            mock.patch.object(logging.config, "dictConfig"))
        logging_basic_config = stack.enter_context(
            mock.patch.object(logging, "basicConfig"))
        colorlog_basic_config = stack.enter_context(
            mock.patch.object(colorlog, "basicConfig"))

        with stack:
            ux.init_logging({"hikari": {"level": "INFO"}}, True, False)

        logging_dict_config.assert_called_once_with(
            {"hikari": {
                "level": "INFO"
            }})
        logging_basic_config.assert_called_once_with(
            level=None,
            format="%(levelname)-1.1s %(asctime)23.23s %(name)s: %(message)s",
            stream=sys.stderr,
        )
        colorlog_basic_config.assert_not_called()
Exemplo n.º 3
0
    def test_when_flavour_is_a_dict_and_defines_handlers(self):
        stack = contextlib.ExitStack()
        stack.enter_context(mock.patch.object(logging, "root", handlers=[]))
        logging_dict_config = stack.enter_context(
            mock.patch.object(logging.config, "dictConfig"))
        logging_basic_config = stack.enter_context(
            mock.patch.object(logging, "basicConfig"))
        colorlog_basic_config = stack.enter_context(
            mock.patch.object(colorlog, "basicConfig"))

        with stack:
            ux.init_logging(
                {
                    "hikari": {
                        "level": "INFO"
                    },
                    "handlers": {
                        "some_handler": {}
                    }
                }, True, False)

        logging_dict_config.assert_called_once_with({
            "hikari": {
                "level": "INFO"
            },
            "handlers": {
                "some_handler": {}
            }
        })
        logging_basic_config.assert_not_called()
        colorlog_basic_config.assert_not_called()
Exemplo n.º 4
0
    def __init__(
        self,
        token: typing.Union[str, rest_api.TokenStrategy],
        token_type: typing.Union[applications.TokenType, str, None] = None,
        public_key: typing.Union[bytes, str, None] = None,
        *,
        allow_color: bool = True,
        banner: typing.Optional[str] = "hikari",
        executor: typing.Optional[concurrent.futures.Executor] = None,
        force_color: bool = False,
        http_settings: typing.Optional[config_impl.HTTPSettings] = None,
        logs: typing.Union[None, int, str, typing.Dict[str, typing.Any]] = "INFO",
        max_rate_limit: float = 300.0,
        max_retries: int = 3,
        proxy_settings: typing.Optional[config_impl.ProxySettings] = None,
        rest_url: typing.Optional[str] = None,
    ) -> None:
        if isinstance(public_key, str):
            public_key = bytes.fromhex(public_key)

        if isinstance(token, str):
            token = token.strip()

        # Beautification and logging
        ux.init_logging(logs, allow_color, force_color)
        self.print_banner(banner, allow_color, force_color)

        # Settings and state
        self._close_event: typing.Optional[asyncio.Event] = None
        self._executor = executor
        self._http_settings = http_settings if http_settings is not None else config_impl.HTTPSettings()
        self._is_closing = False
        self._proxy_settings = proxy_settings if proxy_settings is not None else config_impl.ProxySettings()

        # Entity creation
        self._entity_factory = entity_factory_impl.EntityFactoryImpl(self)

        # RESTful API.
        self._rest = rest_impl.RESTClientImpl(
            cache=None,
            entity_factory=self._entity_factory,
            executor=self._executor,
            http_settings=self._http_settings,
            max_rate_limit=max_rate_limit,
            max_retries=max_retries,
            proxy_settings=self._proxy_settings,
            rest_url=rest_url,
            token=token,
            token_type=token_type,
        )

        # IntegrationServer
        self._server = interaction_server_impl.InteractionServer(
            entity_factory=self._entity_factory,
            public_key=public_key,
            rest_client=self._rest,
        )
Exemplo n.º 5
0
    def test_when_handlers_specify_not_to_set_up(self):
        stack = contextlib.ExitStack()
        stack.enter_context(mock.patch.object(logging, "root", handlers=[]))
        logging_dict_config = stack.enter_context(mock.patch.object(logging.config, "dictConfig"))
        logging_basic_config = stack.enter_context(mock.patch.object(logging, "basicConfig"))
        colorlog_basic_config = stack.enter_context(mock.patch.object(colorlog, "basicConfig"))

        with stack:
            ux.init_logging(None, True, False)

        logging_dict_config.assert_not_called()
        logging_basic_config.assert_not_called()
        colorlog_basic_config.assert_not_called()
Exemplo n.º 6
0
    credentials = get_credentials()

    if not credentials:
        return

    try:
        requiem = client.Requiem(credentials)
        requiem.run()

    except aiohttp.ClientConnectionError:
        _LOGGER.error(
            "requiem was unable to connect to discord! check your internet connection and try again!"
        )

    except hikari.errors.UnauthorizedError:
        _LOGGER.error(
            "requiem was unable to login because the provided token is invalid!"
        )

    except Exception as exc:
        _LOGGER.critical(
            "requiem has encountered a critical exception and crashed!",
            exc_info=exc)


if __name__ == "__main__":
    ux.init_logging("INFO", True, False)
    start_requiem_failsafe()
    _LOGGER.info("requiem has closed!")
    input()
Exemplo n.º 7
0
Arquivo: bot.py Projeto: Reliku/hikari
    def __init__(
        self,
        token: str,
        *,
        allow_color: bool = True,
        banner: typing.Optional[str] = "hikari",
        chunking_limit: int = 200,
        enable_cache: bool = True,
        max_messages: int = 300,
        executor: typing.Optional[concurrent.futures.Executor] = None,
        force_color: bool = False,
        http_settings: typing.Optional[config.HTTPSettings] = None,
        intents: intents_.Intents = intents_.Intents.ALL_UNPRIVILEGED,
        logs: typing.Union[None, LoggerLevelT,
                           typing.Dict[str, typing.Any]] = "INFO",
        max_rate_limit: float = 300,
        proxy_settings: typing.Optional[config.ProxySettings] = None,
        rest_url: typing.Optional[str] = None,
    ) -> None:
        # Beautification and logging
        ux.init_logging(logs, allow_color, force_color)
        self.print_banner(banner, allow_color, force_color)

        # Settings and state
        self._banner = banner
        self._closing_event = asyncio.Event()
        self._closed = False
        self._executor = executor
        self._http_settings = http_settings if http_settings is not None else config.HTTPSettings(
        )
        self._intents = intents
        self._proxy_settings = proxy_settings if proxy_settings is not None else config.ProxySettings(
        )
        self._token = token

        # Caching, chunking, and event subsystems.
        self._cache: cache.Cache
        self._chunker: chunker.GuildChunker
        self._events: event_dispatcher.EventDispatcher
        events_obj: event_manager_base.EventManagerBase

        if enable_cache:
            from hikari.impl import stateful_cache
            from hikari.impl import stateful_event_manager
            from hikari.impl import stateful_guild_chunker

            cache_obj = stateful_cache.StatefulCacheImpl(
                self, intents, max_messages)
            self._cache = cache_obj
            self._chunker = stateful_guild_chunker.StatefulGuildChunkerImpl(
                self, chunking_limit)

            events_obj = stateful_event_manager.StatefulEventManagerImpl(
                self, cache_obj, intents)
            self._raw_event_consumer = events_obj.consume_raw_event
            self._events = events_obj
        else:
            from hikari.impl import stateless_cache
            from hikari.impl import stateless_event_manager
            from hikari.impl import stateless_guild_chunker

            self._cache = stateless_cache.StatelessCacheImpl()
            self._chunker = stateless_guild_chunker.StatelessGuildChunkerImpl()

            events_obj = stateless_event_manager.StatelessEventManagerImpl(
                self, intents)
            self._raw_event_consumer = events_obj.consume_raw_event
            self._events = events_obj

        # Entity creation
        self._entity_factory = entity_factory_impl.EntityFactoryImpl(self)

        # Event creation
        self._event_factory = event_factory_impl.EventFactoryImpl(self)

        # Voice subsystem
        self._voice = voice_impl.VoiceComponentImpl(self, self._events)

        # RESTful API.
        self._rest = rest_impl.RESTClientImpl(
            connector_factory=rest_impl.BasicLazyCachedTCPConnectorFactory(
                self._http_settings),
            connector_owner=True,
            entity_factory=self._entity_factory,
            executor=self._executor,
            http_settings=self._http_settings,
            max_rate_limit=max_rate_limit,
            proxy_settings=self._proxy_settings,
            rest_url=rest_url,
            token=token,
        )

        # We populate these on startup instead, as we need to possibly make some
        # HTTP requests to determine what to put in this mapping.
        self._shards: typing.Dict[int, shard.GatewayShard] = {}
        self.shards: typing.Mapping[
            int,
            gateway_shard.GatewayShard] = types.MappingProxyType(self._shards)
Exemplo n.º 8
0
    def __init__(
        self,
        token: str,
        *,
        allow_color: bool = True,
        banner: typing.Optional[str] = "hikari",
        executor: typing.Optional[concurrent.futures.Executor] = None,
        force_color: bool = False,
        cache_settings: typing.Optional[config.CacheSettings] = None,
        http_settings: typing.Optional[config.HTTPSettings] = None,
        intents: intents_.Intents = intents_.Intents.ALL_UNPRIVILEGED,
        logs: typing.Union[None, int, str, typing.Dict[str, typing.Any]] = "INFO",
        max_rate_limit: float = 300,
        proxy_settings: typing.Optional[config.ProxySettings] = None,
        rest_url: typing.Optional[str] = None,
    ) -> None:
        # Beautification and logging
        ux.init_logging(logs, allow_color, force_color)
        self.print_banner(banner, allow_color, force_color)

        # Settings and state
        self._closing_event = asyncio.Event()
        self._closed = False
        self._is_alive = False
        self._executor = executor
        self._http_settings = http_settings if http_settings is not None else config.HTTPSettings()
        self._intents = intents
        self._proxy_settings = proxy_settings if proxy_settings is not None else config.ProxySettings()
        self._token = token

        # Caching
        cache_settings = cache_settings if cache_settings is not None else config.CacheSettings()
        self._cache = cache_impl.CacheImpl(self, cache_settings)

        # Event handling
        self._events = event_manager_impl.EventManagerImpl(self, cache=self._cache)

        # Entity creation
        self._entity_factory = entity_factory_impl.EntityFactoryImpl(self)

        # Event creation
        self._event_factory = event_factory_impl.EventFactoryImpl(self)

        # Voice subsystem
        self._voice = voice_impl.VoiceComponentImpl(self)

        # RESTful API.
        self._rest = rest_impl.RESTClientImpl(
            connector_factory=rest_impl.BasicLazyCachedTCPConnectorFactory(self._http_settings),
            connector_owner=True,
            entity_factory=self._entity_factory,
            executor=self._executor,
            http_settings=self._http_settings,
            max_rate_limit=max_rate_limit,
            proxy_settings=self._proxy_settings,
            rest_url=rest_url,
            token=token,
        )

        # We populate these on startup instead, as we need to possibly make some
        # HTTP requests to determine what to put in this mapping.
        self._shards: typing.Dict[int, gateway_shard.GatewayShard] = {}
        self.shards: typing.Mapping[int, gateway_shard.GatewayShard] = types.MappingProxyType(self._shards)