|
1 | | -from websockets.sync.client import connect |
2 | 1 | import requests |
| 2 | +import time |
| 3 | + |
| 4 | +from .utils import to_refined |
3 | 5 |
|
4 | 6 |
|
5 | 7 | class PricesTFError(Exception): |
@@ -75,6 +77,55 @@ def get_price(self, sku: str) -> dict: |
75 | 77 | def get_prices(self, page: int, limit: int = 100, order: str = "DESC") -> dict: |
76 | 78 | return self.__get("/prices", {"page": page, "limit": limit, "order": order}) |
77 | 79 |
|
| 80 | + def format_price(self, data: dict) -> dict: |
| 81 | + return { |
| 82 | + "buy": { |
| 83 | + "keys": data["buyKeys"], |
| 84 | + "metal": to_refined(data["buyHalfScrap"] / 2), |
| 85 | + }, |
| 86 | + "sell": { |
| 87 | + "keys": data["sellKeys"], |
| 88 | + "metal": to_refined(data["sellHalfScrap"] / 2), |
| 89 | + }, |
| 90 | + } |
| 91 | + |
| 92 | + def get_prices_till_page( |
| 93 | + self, page_limit: int, print_rate_limit: bool = False |
| 94 | + ) -> dict: |
| 95 | + prices = {} |
| 96 | + current_page = 1 |
| 97 | + # set higher than current page first time |
| 98 | + max_page = page_limit if page_limit != -1 else 2 |
| 99 | + |
| 100 | + while current_page < max_page: |
| 101 | + try: |
| 102 | + response = self.prices_tf.get_prices(current_page) |
| 103 | + except RateLimited: |
| 104 | + timeout = 60 |
| 105 | + |
| 106 | + if print_rate_limit: |
| 107 | + print(f"rate limited from prices.tf, waiting {timeout} seconds") |
| 108 | + |
| 109 | + time.sleep(timeout) |
| 110 | + continue |
| 111 | + |
| 112 | + if "items" not in response: |
| 113 | + raise PricesTFError("could not find any items in response") |
| 114 | + |
| 115 | + for item in response["items"]: |
| 116 | + prices[item["sku"]] = self.format_price(item) |
| 117 | + |
| 118 | + current_page = response["meta"]["currentPage"] + 1 |
| 119 | + total_pages = response["meta"]["totalPages"] |
| 120 | + |
| 121 | + if page_limit == -1: |
| 122 | + max_page = total_pages |
| 123 | + |
| 124 | + return prices |
| 125 | + |
| 126 | + def get_all_prices(self, print_rate_limit: bool = False) -> dict: |
| 127 | + return self.get_prices_till_page(-1, print_rate_limit) |
| 128 | + |
78 | 129 | def update_price(self, sku: str) -> tuple[dict, int]: |
79 | 130 | return self.__post(f"/prices/{sku}/refresh") |
80 | 131 |
|
|
0 commit comments