Skip to content

Commit

Permalink
Added prey_wildcards parameter and filters to auction history.
Browse files Browse the repository at this point in the history
  • Loading branch information
Galarzaa90 committed Mar 30, 2021
1 parent ef36ad1 commit 1877bde
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 28 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ Changelog
Due to this library relying on external content, older versions are not guaranteed to work.
Try to always use the latest version.

.. v4.1.0
4.1.0 (2021-03-30)
==================
- Added ``prey_wildcards`` attribute to ``AuctionDetails``.
- Added ``filters`` parameter to ``CharacterBazaar.get_auctions_history_url`` and ``Client.fetch_auction_history``.

.. v4.0.0:
4.0.0 (2021-03-10)
Expand Down
17 changes: 12 additions & 5 deletions serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ async def home(request: web.Request):
@routes.get('/auctions')
async def get_current_auctions(request: web.Request):
page = int(request.query.get("page", 1))
filters = await filters_from_query(request)
response = await app["tibiapy"].fetch_current_auctions(page, filters)
return json_response(response)


async def filters_from_query(request):
filters = tibiapy.AuctionFilters()
filters.world = request.query.get("world")
filters.battleye = try_enum(tibiapy.BattlEyeTypeFilter, request.query.get("battleye"))
Expand All @@ -65,14 +71,15 @@ async def get_current_auctions(request: web.Request):
filters.max_skill_level = tibiapy.utils.parse_integer(request.query.get("max_skill_level"), None)
filters.order_by = try_enum(tibiapy.AuctionOrderBy, request.query.get("order_by"))
filters.order = try_enum(tibiapy.AuctionOrder, request.query.get("order"))
filters.item = request.query.get("item")
response = await app["tibiapy"].fetch_current_auctions(page, filters)
return json_response(response)
filters.search_string = request.query.get("item")
return filters


@routes.get('/auctions/history')
async def get_auction_history(request: web.Request):
response = await app["tibiapy"].fetch_auction_history()
page = int(request.query.get("page", 1))
filters = await filters_from_query(request)
response = await app["tibiapy"].fetch_auction_history(page, filters)
return json_response(response)


Expand Down Expand Up @@ -350,7 +357,7 @@ async def middleware_handler(request: web.Request):
raise
except Exception as e:
tb = traceback.format_exc()
print(tb)
log.exception("%s %s", request.method, request.path)
return json_error(500, e, tb)

return middleware_handler
Expand Down
2 changes: 1 addition & 1 deletion tibiapy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = '4.0.0'
__version__ = '4.1.0'
__author__ = 'Allan Galarza'

import logging
Expand Down
27 changes: 17 additions & 10 deletions tibiapy/bazaar.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@
from tibiapy import abc, InvalidContent, Sex, Vocation
from tibiapy.abc import BaseCharacter
from tibiapy.enums import AuctionOrder, AuctionOrderBy, AuctionSearchType, AuctionStatus, BattlEyeTypeFilter, \
BazaarType, BidType, \
PvpTypeFilter, \
SkillFilter, \
VocationAuctionFilter
BazaarType, BidType, PvpTypeFilter, SkillFilter, VocationAuctionFilter
from tibiapy.utils import convert_line_breaks, deprecated, get_tibia_url, parse_integer, parse_pagination, \
parse_tibia_datetime, \
parse_tibia_money, \
parse_tibiacom_content, \
try_enum
parse_tibia_datetime, parse_tibiacom_content, try_enum

__all__ = (
"AchievementEntry",
Expand Down Expand Up @@ -365,15 +359,23 @@ def get_current_auctions_url(cls, page=1, filters=None):
return get_tibia_url("charactertrade", "currentcharactertrades", currentpage=page, **filters.query_params)

@classmethod
def get_auctions_history_url(cls, page=1):
def get_auctions_history_url(cls, page=1, filters=None):
"""Gets the URL to the auction history in Tibia.com
Parameters
----------
page: :class:`int`
The page to show the URL for.
filters: :class:`AuctionFilters`
The filtering criteria to use.
Returns
-------
:class:`str`
The URL to the auction history section in Tibia.com
"""
return get_tibia_url("charactertrade", "pastcharactertrades", currentpage=page)
filters = filters or AuctionFilters()
return get_tibia_url("charactertrade", "pastcharactertrades", currentpage=page, **filters.query_params)

@classmethod
def from_content(cls, content):
Expand Down Expand Up @@ -876,6 +878,8 @@ class AuctionDetails(ListedAuction):
The amount of charm points the character has available to spend.
spent_charm_points: :class:`int`
The total charm points the character has spent.
prey_wildcards: :class:`int`
The number of Prey Wildcards the character has.
daly_reward_streak: :class:`int`
The current daily reward streak.
permanent_hunting_task_slots: :class:`int`
Expand Down Expand Up @@ -941,6 +945,7 @@ def __init__(self, **kwargs):
self.spent_charm_points: int = kwargs.get("spent_charm_points", 0)
self.daily_reward_streak: int = kwargs.get("daily_reward_streak", 0)
self.hunting_task_points: int = kwargs.get("hunting_task_points", 0)
self.prey_wildcards: int = kwargs.get("prey_wildcards", 0)
self.permanent_hunting_task_slots: int = kwargs.get("permanent_hunting_task_slots", 0)
self.permanent_prey_slots: int = kwargs.get("permanent_prey_slots", 0)
self.hirelings: int = kwargs.get("hirelings", 0)
Expand Down Expand Up @@ -983,6 +988,7 @@ def __init__(self, **kwargs):
"hunting_task_points",
"permanent_hunting_task_slots",
"permanent_prey_slots",
"prey_wildcards",
"hirelings",
"hireling_jobs",
"hireling_outfits",
Expand Down Expand Up @@ -1316,6 +1322,7 @@ def _parse_general_table(self, table):
self.hunting_task_points = parse_integer(hunting_data.get("hunting_task_points", ""))
self.permanent_hunting_task_slots = parse_integer(hunting_data.get("permanent_hunting_task_slots", ""))
self.permanent_prey_slots = parse_integer(hunting_data.get("permanent_prey_slots", ""))
self.prey_wildcards = parse_integer(hunting_data.get("prey_wildcards", ""))

hirelings_data = self._parse_data_table(content_containers[7])
self.hirelings = parse_integer(hirelings_data.get("hirelings", ""))
Expand Down
22 changes: 12 additions & 10 deletions tibiapy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,14 @@ async def _initialize_session(self, proxy_url=None):
self._session_ready.set()

@classmethod
def _handle_status(cls, status_code):
def _handle_status(cls, status_code, fetching_time=0):
"""Handles error status codes, raising exceptions if necessary."""
if status_code < 400:
return
if status_code == 403:
raise Forbidden("403 Forbidden: Might be getting rate-limited")
raise Forbidden("403 Forbidden: Might be getting rate-limited", fetching_time=fetching_time)
else:
raise NetworkError("Request error, status code: %d" % status_code)
raise NetworkError("Request error, status code: %d" % status_code, fetching_time=fetching_time)

async def _request(self, method, url, data=None, headers=None):
"""Base request, handling possible error statuses.
Expand Down Expand Up @@ -182,24 +182,24 @@ async def _request(self, method, url, data=None, headers=None):
If there's any connection errors during the request.
"""
await self._session_ready.wait()
init_time = time.perf_counter()
try:
init_time = time.perf_counter()
async with self.session.request(method, url, data=data, headers=headers) as resp:
diff_time = time.perf_counter()-init_time
if "maintenance.tibia.com" in str(resp.url):
log.info(f"%s | %s | %s %s | maintenance.tibia.com", url, resp.method, resp.status, resp.reason)
raise SiteMaintenanceError("Tibia.com is down for maintenance.")
log.info(f"%s | %s | %s %s | %dms", url, resp.method, resp.status, resp.reason, int(diff_time*1000))
self._handle_status(resp.status)
self._handle_status(resp.status, diff_time)
response = RawResponse(resp, diff_time)
response.content = await resp.text()
return response
except aiohttp.ClientError as e:
raise NetworkError("aiohttp.ClientError: %s" % e, e)
raise NetworkError("aiohttp.ClientError: %s" % e, e, time.perf_counter()-init_time)
except aiohttp_socks.SocksConnectionError as e:
raise NetworkError("aiohttp_socks.SocksConnectionError: %s" % e, e)
raise NetworkError("aiohttp_socks.SocksConnectionError: %s" % e, e, time.perf_counter()-init_time)
except UnicodeDecodeError as e:
raise NetworkError('UnicodeDecodeError: %s' % e, e)
raise NetworkError('UnicodeDecodeError: %s' % e, e, time.perf_counter()-init_time)

async def fetch_current_auctions(self, page=1, filters=None):
"""Fetches the current auctions in the bazaar
Expand Down Expand Up @@ -236,7 +236,7 @@ async def fetch_current_auctions(self, page=1, filters=None):
parsing_time = time.perf_counter() - start_time
return TibiaResponse(response, current_auctions, parsing_time)

async def fetch_auction_history(self, page=1):
async def fetch_auction_history(self, page=1, filters=None):
"""Fetches the auction history of the bazaar.
.. versionadded:: 3.3.0
Expand All @@ -245,6 +245,8 @@ async def fetch_auction_history(self, page=1):
----------
page: :class:`int`
The page to display.
filters: :class:`AuctionFilters`
The filtering criteria to use.
Returns
-------
Expand All @@ -263,7 +265,7 @@ async def fetch_auction_history(self, page=1):
"""
if page <= 0:
raise ValueError('page must be 1 or greater.')
response = await self._request("GET", CharacterBazaar.get_auctions_history_url(page))
response = await self._request("GET", CharacterBazaar.get_auctions_history_url(page, filters))
start_time = time.perf_counter()
auction_history = CharacterBazaar.from_content(response.content)
parsing_time = time.perf_counter() - start_time
Expand Down
8 changes: 6 additions & 2 deletions tibiapy/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,14 @@ class NetworkError(TibiapyException):
Attributes
----------
original: :class:`Exception`
The original exception that caused this exception."""
def __init__(self, message, original=None):
The original exception that caused this exception.
fetching_time: :class:`float`
The time between the request and the response.
"""
def __init__(self, message, original=None, fetching_time=0):
super().__init__(message)
self.original = original
self.fetching_time = fetching_time


class Forbidden(NetworkError):
Expand Down

0 comments on commit 1877bde

Please sign in to comment.