Exemple #1
0
    def list_from_tibiadata(cls, content):
        """Parses the content of a house list from TibiaData.com into a list of houses

        Parameters
        ----------
        content: :class:`str`
            The raw JSON response from TibiaData

        Returns
        -------
        :class:`list` of :class:`ListedHouse`

        Raises
        ------
        InvalidContent`
            Content is not the house list from TibiaData.com
        """
        json_data = parse_json(content)
        try:
            house_data = json_data["houses"]
            houses = []
            house_type = HouseType.HOUSE if house_data["type"] == "houses" else HouseType.GUILDHALL
            for house_json in house_data["houses"]:
                house = ListedHouse(house_json["name"], house_data["world"], house_json["houseid"],
                                    size=house_json["size"], rent=house_json["rent"], town=house_data["town"],
                                    type=house_type)
                house._parse_status(house_json["status"])
                houses.append(house)
            return houses
        except KeyError:
            raise InvalidContent("content is not a house list json response from TibiaData.com")
Exemple #2
0
    def from_tibiadata(cls, content, vocation=None):
        """Builds a highscores object from a TibiaData highscores response.

        Notes
        -----
        Since TibiaData.com's response doesn't contain any indication of the vocation filter applied,
        :py:attr:`vocation` can't be determined from the response, so the attribute must be assigned manually.

        If the attribute is known, it can be passed for it to be assigned in this method.

        Parameters
        ----------
        content: :class:`str`
            The JSON content of the response.
        vocation: :class:`VocationFilter`, optional
            The vocation filter to assign to the results. Note that this won't affect the parsing.

        Returns
        -------
        :class:`Highscores`
            The highscores contained in the page, or None if the content is for the highscores of a nonexistent world.

        Raises
        ------
        InvalidContent
            If content is not a JSON string of the highscores response."""
        json_content = parse_json(content)
        try:
            highscores_json = json_content["highscores"]
            if "error" in highscores_json["data"]:
                return None
            world = highscores_json["world"]
            category = highscores_json["type"]
            highscores = cls(world, category)
            for entry in highscores_json["data"]:
                value_key = "level"
                if highscores.category in [Category.ACHIEVEMENTS, Category.LOYALTY_POINTS, Category.EXPERIENCE]:
                    value_key = "points"
                if highscores.category == Category.EXPERIENCE:
                    highscores.entries.append(ExpHighscoresEntry(entry["name"], entry["rank"], entry["voc"],
                                                                 entry[value_key], entry["level"]))
                elif highscores.category == Category.LOYALTY_POINTS:
                    highscores.entries.append(LoyaltyHighscoresEntry(entry["name"], entry["rank"], entry["voc"],
                                                                     entry[value_key], entry["title"]))
                else:
                    highscores.entries.append(HighscoresEntry(entry["name"], entry["rank"], entry["voc"],
                                                              entry[value_key]))
            highscores.results_count = len(highscores.entries)
        except KeyError:
            raise InvalidContent("content is not a TibiaData highscores response.")
        highscores.vocation = vocation or VocationFilter.ALL
        return highscores
Exemple #3
0
    def from_tibiadata(cls, content):
        """Parses a TibiaData.com response into a :class:`World`

        Parameters
        ----------
        content: :class:`str`
            The raw JSON content from TibiaData

        Returns
        -------
        :class:`World`
            The World described in the page, or ``None``.

        Raises
        ------
        InvalidContent
            If the provided content is not a TibiaData world response.
        """
        json_data = parse_json(content)
        try:
            world_data = json_data["world"]
            world_info = world_data["world_information"]
            world = cls(world_info["name"])
            if "location" not in world_info:
                return None
            world.online_count = world_info["players_online"]
            world.status = "Online" if world.online_count > 0 else "Offline"
            world.record_count = world_info["online_record"]["players"]
            world.record_date = parse_tibiadata_datetime(
                world_info["online_record"]["date"])
            world.creation_date = world_info["creation_date"]
            world.location = try_enum(WorldLocation, world_info["location"])
            world.pvp_type = try_enum(PvpType, world_info["pvp_type"])
            world.transfer_type = try_enum(TransferType,
                                           world_info.get("transfer_type"),
                                           TransferType.REGULAR)
            world.premium_only = "premium_type" in world_info
            world.world_quest_titles = world_info.get("world_quest_titles", [])
            world._parse_battleye_status(world_info.get("battleye_status", ""))
            world.experimental = world_info.get("Game World Type:",
                                                "Regular") != "Regular"
            for player in world_data.get("players_online", []):
                world.online_players.append(
                    OnlineCharacter(player["name"], world.name,
                                    player["level"], player["vocation"]))
            return world
        except KeyError:
            raise InvalidContent(
                "content is not a world json response from TibiaData")
Exemple #4
0
    def from_tibiadata(cls, content):
        """Parses the content of the World Overview section from TibiaData.com into an object of this class.

        Notes
        -----
        Due to TibiaData limitations, :py:attr:`record_count` and :py:attr:`record_date` are unavailable
        object.

        Additionally, the listed worlds in :py:attr:`worlds` lack some information when obtained from TibiaData.
        The following attributes are unavailable:

        - :py:attr:`ListedWorld.status` is always ``Online``.
        - :py:attr:`ListedWorld.battleye_protected` is always ``False``
        - :py:attr:`ListedWorld.battleye_date` is always ``None``.


        Parameters
        ----------
        content: :class:`str`
            The JSON response of the worlds section in TibiaData.com

        Returns
        -------
        :class:`WorldOverview`
            An instance of this class containing only the available worlds.

        Raises
        ------
        InvalidContent
            If the provided content is the json content of the world section in TibiaData.com
        """
        json_data = parse_json(content)
        try:
            worlds_json = json_data["worlds"]["allworlds"]
            world_overview = cls()
            for world_json in worlds_json:
                world = ListedWorld(world_json["name"], world_json["location"],
                                    world_json["worldtype"])
                world._parse_additional_info(world_json["additional"])
                world.online_count = world_json["online"]
                world_overview.worlds.append(world)
            return world_overview
        except KeyError:
            raise InvalidContent(
                "content is not a worlds json response from TibiaData.com.")
Exemple #5
0
    def list_from_tibiadata(cls, content):
        """Builds a character object from a TibiaData character response.

        Parameters
        ----------
        content: :class:`str`
            A string containing the JSON response from TibiaData.

        Returns
        -------
        :class:`list` of :class:`ListedGuild`
            The list of guilds contained.

        Raises
        ------
        InvalidContent
            If content is not a JSON response of TibiaData's guild list.
        """
        json_content = parse_json(content)
        try:
            guilds_obj = json_content["guilds"]
            guilds = []
            for guild in guilds_obj["active"]:
                guilds.append(
                    cls(guild["name"],
                        guilds_obj["world"],
                        logo_url=guild["guildlogo"],
                        description=guild["desc"],
                        active=True))
            for guild in guilds_obj["formation"]:
                guilds.append(
                    cls(guild["name"],
                        guilds_obj["world"],
                        logo_url=guild["guildlogo"],
                        description=guild["desc"],
                        active=False))
        except KeyError:
            raise InvalidContent(
                "content doest not belong to a guilds response.")
        return guilds
Exemple #6
0
    def from_tibiadata(cls, content):
        """
        Parses a TibiaData response into a House object.

        Parameters
        ----------
        content: :class:`str`
            The JSON content of the TibiaData response.

        Returns
        -------
        :class:`House`
            The house contained in the response, if found.

        Raises
        ------
        InvalidContent
            If the content is not a house JSON response from TibiaData
        """
        json_content = parse_json(content)
        try:
            house_json = json_content["house"]
            if not house_json["name"]:
                return None
            house = cls(house_json["name"], house_json["world"])

            house.type = try_enum(HouseType, house_json["type"])
            house.id = house_json["houseid"]
            house.beds = house_json["beds"]
            house.size = house_json["size"]
            house.size = house_json["size"]
            house.rent = house_json["rent"]
            house.image_url = house_json["img"]

            # Parsing the original status string is easier than dealing with TibiaData fields
            house._parse_status(house_json["status"]["original"])
        except KeyError:
            raise InvalidContent("content is not a TibiaData house response.")
        return house
Exemple #7
0
    def from_tibiadata(cls, content):
        """Builds a character object from a TibiaData character response.

        Parameters
        ----------
        content: :class:`str`
            The JSON content of the response.

        Returns
        -------
        :class:`Character`
            The character contained in the page, or None if the character doesn't exist

        Raises
        ------
        InvalidContent
            If content is not a JSON string of the Character response."""
        json_content = parse_json(content)
        char = cls()
        try:
            character = json_content["characters"]
            if "error" in character:
                return None
            character_data = character["data"]
            char.name = character_data["name"]
            char.world = character_data["world"]
            char.level = character_data["level"]
            char.achievement_points = character_data["achievement_points"]
            char.sex = try_enum(Sex, character_data["sex"])
            char.vocation = try_enum(Vocation, character_data["vocation"])
            char.residence = character_data["residence"]
            char.account_status = try_enum(AccountStatus,
                                           character_data["account_status"])
        except KeyError:
            raise InvalidContent(
                "content does not match a character json from TibiaData.")
        char.former_names = character_data.get("former_names", [])
        if "deleted" in character_data:
            char.deletion_date = parse_tibiadata_datetime(
                character_data["deleted"])
        char.married_to = character_data.get("married_to")
        char.former_world = character_data.get("former_world")
        char.position = character_data.get("Position:")
        if "guild" in character_data:
            char.guild_membership = GuildMembership(
                character_data["guild"]["name"],
                character_data["guild"]["rank"])
        if "house" in character_data:
            house = character_data["house"]
            paid_until_date = parse_tibiadata_date(house["paid"])
            char.houses.append(
                CharacterHouse(house["houseid"], house["name"], char.world,
                               house["town"], char.name, paid_until_date))
        char.comment = character_data.get("comment")
        if len(character_data["last_login"]) > 0:
            char.last_login = parse_tibiadata_datetime(
                character_data["last_login"][0])
        for achievement in character["achievements"]:
            char.achievements.append(
                Achievement(achievement["name"], achievement["stars"]))

        char._parse_deaths_tibiadata(character.get("deaths", []))

        for other_char in character["other_characters"]:
            char.other_characters.append(
                OtherCharacter(other_char["name"], other_char["world"],
                               other_char["status"] == "online",
                               other_char["status"] == "deleted"))

        if character["account_information"]:
            acc_info = character["account_information"]
            created = parse_tibiadata_datetime(acc_info.get("created"))
            loyalty_title = None if acc_info[
                "loyalty_title"] == "(no title)" else acc_info["loyalty_title"]
            position = acc_info.get("position")

            char.account_information = AccountInformation(
                created, loyalty_title, position)

        return char
Exemple #8
0
    def from_tibiadata(cls, content):
        """Builds a guild object from a TibiaData character response.

        Parameters
        ----------
        content: :class:`str`
            The json string from the TibiaData response.

        Returns
        -------
        :class:`Guild`
            The guild contained in the description or ``None``.

        Raises
        ------
        InvalidContent
            If content is not a JSON response of a guild's page.
        """
        json_content = parse_json(content)
        guild = cls()
        try:
            guild_obj = json_content["guild"]
            if "error" in guild_obj:
                return None
            guild_data = guild_obj["data"]
            guild.name = guild_data["name"]
            guild.world = guild_data["world"]
            guild.logo_url = guild_data["guildlogo"]
            guild.description = guild_data["description"]
            guild.founded = parse_tibiadata_date(guild_data["founded"])
            guild.open_applications = guild_data["application"]
        except KeyError:
            raise InvalidContent(
                "content does not match a guild json from TibiaData.")
        guild.homepage = guild_data.get("homepage")
        guild.active = not guild_data.get("formation", False)
        if isinstance(guild_data["disbanded"], dict):
            guild.disband_date = parse_tibiadata_date(
                guild_data["disbanded"]["date"])
            guild.disband_condition = disband_tibadata_regex.search(
                guild_data["disbanded"]["notification"]).group(1)
        for rank in guild_obj["members"]:
            rank_name = rank["rank_title"]
            for member in rank["characters"]:
                guild.members.append(
                    GuildMember(member["name"],
                                rank_name,
                                member["nick"] or None,
                                member["level"],
                                member["vocation"],
                                joined=parse_tibiadata_date(member["joined"]),
                                online=member["status"] == "online"))
        for invited in guild_obj["invited"]:
            guild.invites.append(
                GuildInvite(invited["name"],
                            parse_tibiadata_date(invited["invited"])))
        if isinstance(guild_data["guildhall"], dict):
            gh = guild_data["guildhall"]
            guild.guildhall = GuildHouse(gh["name"], gh["world"],
                                         guild.members[0].name,
                                         parse_tibiadata_date(gh["paid"]))
        return guild