Ejemplo n.º 1
0
    def _fetch(self, url: str, data: dict = None) -> tuple[dict, bool]:
        """
        Get the JSON Response from the Root Hypixel API URL,
        and Also add the ability to include the GET request parameters
        with the API KEY Parameter by default.

        Parameters:
            url (str): The URL to be accessed from the Root Domain.
            data (dict):
                The GET Request's Key-Value Pair. Example: {"uuid": "abc"} is converted to `?uuid=abc`

        Returns:
            JSON Response, Request Success (tuple):
                The JSON Response from the Fetch Done to the API and the SUCCESS Value from the Response.
        """
        if not data:
            data = {}

        if "key" not in data:
            data["key"] = random.choice(self.api_key)

        url = form_url(HYPIXEL_API, url, data)

        with requests.get(url, timeout=TIMEOUT) as response:

            if response.status_code == 429:
                raise RateLimitError("Out of Requests!")

            try:
                json = response.json()
                return json, json["success"]
            except Exception as exception:
                raise HypixelAPIError(
                    f"Invalid Content type Received instead of JSON. {exception}"
                )
Ejemplo n.º 2
0
    async def _fetch(self, url: str, data: dict = None) -> t.Tuple[dict, bool]:
        """
        Get the JSON Response from the Root Hypixel API URL, and also add the ability to include the GET request
        parameters with the API KEY Parameter by default.

        Parameters
        ----------
        url: `str`
            The URL to be accessed from the Root Domain.
        data: `t.Optional[dict]`
            The GET Request's Key-Value Pair. Example: {"uuid": "abc"} is converted to `?uuid=abc`. Defaults to None.

        Returns
        -------
        `t.Tuple[dict, bool]`
            The JSON Response from the Fetch Done to the API and the SUCCESS Value from the Response.
        """
        if not data:
            data = {}

        headers = {"API-Key": random.choice(self.api_key)}

        url = form_url(HYPIXEL_API, url, data)

        async with self.session.get(url, timeout=TIMEOUT,
                                    headers=headers) as response:
            if response.status == 429:
                raise RateLimitError("Out of Requests!")

            try:
                json = await response.json()
            except Exception as exception:
                raise HypixelAPIError(f"{exception}")
            else:
                if not json["success"]:
                    reason = "The Key given is invalid, or something else has problem."
                    if json["cause"] is not None:
                        reason += f" Reason given: {json['cause']}"

                    raise HypixelAPIError(reason=reason)

                return json
Ejemplo n.º 3
0
    def _fetch(self,
               url: str,
               data: dict = None,
               key: bool = True) -> t.Tuple[dict, bool]:
        """
        Get the JSON Response from the Root Hypixel API URL, and also add the ability to include the GET request
        parameters with the API KEY Parameter by default.

        Parameters
        ----------
        url: `str`
            The URL to be accessed from the Root Domain.
        data: `t.Optional[dict]`
            The GET Request's Key-Value Pair. Example: {"uuid": "abc"} is converted to `?uuid=abc`. Defaults to None.
        key: bool
            If key is needed for the endpoint.

        Returns
        -------
        `t.Tuple[dict, bool]`
            The JSON Response from the Fetch Done to the API and the SUCCESS Value from the Response.
        """
        if (self.requests_remaining != -1 and  # noqa: W504
            (self.requests_remaining == 0
             and self._ratelimit_reset > datetime.now()) or  # noqa: W504
                self.retry_after and (self.retry_after > datetime.now())):
            raise RateLimitError(f"Retry after {self.retry_after}")

        if not data:
            data = {}

        headers = {}

        if key:
            headers["API-Key"] = random.choice(self.api_key)

        url = form_url(HYPIXEL_API, url, data)

        with requests.get(url, timeout=TIMEOUT, headers=headers) as response:
            if response.status_code == 429:
                self.requests_remaining = 0
                self.retry_after = datetime.now() + timedelta(
                    seconds=int(response.headers["Retry-After"]))
                raise RateLimitError(
                    f"Out of Requests! {datetime.now() + timedelta(seconds=int(response.headers['Retry-After']))}"
                )

            if response.status_code == 400:
                raise HypixelAPIError(reason="Invalid key specified!")

            if key:
                if "RateLimit-Limit" in response.headers:
                    if self.total_requests == 0:
                        self.total_requests = int(
                            response.headers["RateLimit-Limit"])

                    self.requests_remaining = int(
                        response.headers["RateLimit-Remaining"])
                    self._ratelimit_reset = datetime.now() + timedelta(
                        seconds=int(response.headers["RateLimit-Reset"]))

            try:
                json = response.json()
            except Exception as exception:
                raise HypixelAPIError(f"{exception}")
            else:
                if not json["success"]:
                    reason = "Something in the API has problem."
                    if json["cause"] is not None:
                        reason += f" Reason given: {json['cause']}"

                    raise HypixelAPIError(reason=reason)

                return json