shushu-open-api 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Synchronous client for the published Shushu Open Platform endpoints."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import http.client
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Any, Literal, TypedDict
|
|
13
|
+
from urllib.parse import urlencode, urlsplit
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class PlayerQueryPayload(TypedDict, total=False):
|
|
17
|
+
"""Supply exactly one of query, nick, uid and username."""
|
|
18
|
+
|
|
19
|
+
query: str
|
|
20
|
+
nick: str
|
|
21
|
+
uid: str
|
|
22
|
+
username: str
|
|
23
|
+
mode: Literal[0, 1, 2, 3]
|
|
24
|
+
days: int
|
|
25
|
+
room_id: str
|
|
26
|
+
detail_scope: Literal["squad", "both_camps"]
|
|
27
|
+
include_match_detail: bool
|
|
28
|
+
include_victory_unite: bool
|
|
29
|
+
timeout_sec: int
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class ShushuResponse:
|
|
34
|
+
"""A single HTTP response, with its original decoded JSON body."""
|
|
35
|
+
|
|
36
|
+
status: int
|
|
37
|
+
request_id: str | None
|
|
38
|
+
body: Any
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ShushuApiError(Exception):
|
|
42
|
+
"""An unsuccessful HTTP call. Network failures can have no HTTP status."""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
code: str,
|
|
47
|
+
message: str,
|
|
48
|
+
*,
|
|
49
|
+
status: int | None = None,
|
|
50
|
+
request_id: str | None = None,
|
|
51
|
+
retry_after: str | None = None,
|
|
52
|
+
body: Any = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
super().__init__(message)
|
|
55
|
+
self.code = code
|
|
56
|
+
self.status = status
|
|
57
|
+
self.request_id = request_id
|
|
58
|
+
self.retry_after = retry_after
|
|
59
|
+
self.body = body
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
_PLAYER_QUERIES = "/v1/df/player/queries"
|
|
63
|
+
_BUSINESS_ID = re.compile(r"[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _player_path(business_id: str) -> str:
|
|
67
|
+
if not isinstance(business_id, str) or not _BUSINESS_ID.fullmatch(business_id):
|
|
68
|
+
raise ValueError("business_id must be the lowercase UUID returned by the gateway")
|
|
69
|
+
return f"{_PLAYER_QUERIES}/{business_id}"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _require_string(value: object, name: str) -> None:
|
|
73
|
+
if not isinstance(value, str) or not value.strip():
|
|
74
|
+
raise ValueError(f"{name} must be a nonempty string")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ShushuClient:
|
|
78
|
+
"""Uses an API key for one request per method call. Timeout is in seconds."""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
api_key: str | None = None,
|
|
83
|
+
*,
|
|
84
|
+
base_url: str = "https://openapi.shushu.fan",
|
|
85
|
+
timeout: float = 30.0,
|
|
86
|
+
) -> None:
|
|
87
|
+
key = os.environ.get("SHUSHU_API_KEY") if api_key is None else api_key
|
|
88
|
+
if not isinstance(key, str) or not re.fullmatch(r"[!-~]+", key.strip()):
|
|
89
|
+
raise ValueError("Supply a valid api_key or set SHUSHU_API_KEY")
|
|
90
|
+
url = urlsplit(base_url)
|
|
91
|
+
if (
|
|
92
|
+
url.scheme not in ("https", "http") or not url.hostname
|
|
93
|
+
or url.username is not None or url.password is not None or url.query or url.fragment
|
|
94
|
+
):
|
|
95
|
+
raise ValueError("base_url must be an absolute HTTP(S) URL without credentials, query or fragment")
|
|
96
|
+
if not math.isfinite(timeout) or timeout <= 0:
|
|
97
|
+
raise ValueError("timeout must be a positive finite number of seconds")
|
|
98
|
+
self._api_key = key.strip()
|
|
99
|
+
self._connection = http.client.HTTPSConnection if url.scheme == "https" else http.client.HTTPConnection
|
|
100
|
+
self._host = url.hostname
|
|
101
|
+
self._port = url.port
|
|
102
|
+
self._prefix = url.path.rstrip("/")
|
|
103
|
+
self._timeout = timeout
|
|
104
|
+
|
|
105
|
+
def daily_passwords(self, *, idempotency_key: str | None = None) -> ShushuResponse:
|
|
106
|
+
return self._request("GET", "/v1/df/daily_pwd", idempotency_key=idempotency_key)
|
|
107
|
+
|
|
108
|
+
def weekly_bazaar(self, *, idempotency_key: str | None = None) -> ShushuResponse:
|
|
109
|
+
return self._request("GET", "/v1/df/bazaar/weekly", idempotency_key=idempotency_key)
|
|
110
|
+
|
|
111
|
+
def latest_price(
|
|
112
|
+
self, item_id: str, grade: Literal[1, 2, 3] | None = None,
|
|
113
|
+
*, idempotency_key: str | None = None,
|
|
114
|
+
) -> ShushuResponse:
|
|
115
|
+
_require_string(item_id, "item_id")
|
|
116
|
+
query = {"item_id": item_id}
|
|
117
|
+
if grade is not None:
|
|
118
|
+
if type(grade) is not int or grade not in (1, 2, 3):
|
|
119
|
+
raise ValueError("grade must be 1, 2 or 3")
|
|
120
|
+
query["grade"] = str(grade)
|
|
121
|
+
return self._request("GET", "/v1/df/market/latest", query=query, idempotency_key=idempotency_key)
|
|
122
|
+
|
|
123
|
+
def market_snapshot(self, *, idempotency_key: str | None = None) -> ShushuResponse:
|
|
124
|
+
return self._request("GET", "/v1/df/market/snapshot", idempotency_key=idempotency_key)
|
|
125
|
+
|
|
126
|
+
def parse_loadout(
|
|
127
|
+
self, code: str, refresh: bool | None = None, *, idempotency_key: str | None = None
|
|
128
|
+
) -> ShushuResponse:
|
|
129
|
+
_require_string(code, "code")
|
|
130
|
+
if refresh is not None and not isinstance(refresh, bool):
|
|
131
|
+
raise ValueError("refresh must be a boolean")
|
|
132
|
+
query = {} if refresh is None else {"refresh": str(refresh).lower()}
|
|
133
|
+
return self._request(
|
|
134
|
+
"POST", "/v1/df/gunmod/share-code/parse", query=query,
|
|
135
|
+
payload={"code": code}, idempotency_key=idempotency_key,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def submit_player_query(
|
|
139
|
+
self, payload: PlayerQueryPayload, idempotency_key: str | None = None
|
|
140
|
+
) -> ShushuResponse:
|
|
141
|
+
if not isinstance(payload, dict):
|
|
142
|
+
raise ValueError("payload must be a JSON object")
|
|
143
|
+
fields: Mapping[str, object] = payload
|
|
144
|
+
identities = fields.keys() & {"query", "nick", "uid", "username"}
|
|
145
|
+
if len(identities) != 1:
|
|
146
|
+
raise ValueError("provide exactly one of query, nick, uid or username")
|
|
147
|
+
identity = identities.pop()
|
|
148
|
+
_require_string(fields[identity], identity)
|
|
149
|
+
if "room_id" in fields:
|
|
150
|
+
_require_string(fields["room_id"], "room_id")
|
|
151
|
+
return self._request("POST", _PLAYER_QUERIES, payload=payload, idempotency_key=idempotency_key)
|
|
152
|
+
|
|
153
|
+
def player_query_status(self, business_id: str) -> ShushuResponse:
|
|
154
|
+
return self._request("GET", _player_path(business_id))
|
|
155
|
+
|
|
156
|
+
def player_query_result(self, business_id: str) -> ShushuResponse:
|
|
157
|
+
return self._request("GET", _player_path(business_id) + "/result")
|
|
158
|
+
|
|
159
|
+
def _request(
|
|
160
|
+
self,
|
|
161
|
+
method: str,
|
|
162
|
+
path: str,
|
|
163
|
+
*,
|
|
164
|
+
query: dict[str, str] | None = None,
|
|
165
|
+
payload: object | None = None,
|
|
166
|
+
idempotency_key: str | None = None,
|
|
167
|
+
) -> ShushuResponse:
|
|
168
|
+
target = self._prefix + path
|
|
169
|
+
if query:
|
|
170
|
+
target += "?" + urlencode(query)
|
|
171
|
+
headers = {"Authorization": "Bearer " + self._api_key, "Accept": "application/json"}
|
|
172
|
+
if idempotency_key is not None:
|
|
173
|
+
if not isinstance(idempotency_key, str) or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key):
|
|
174
|
+
raise ValueError("idempotency_key must match [A-Za-z0-9._:-]{1,128}")
|
|
175
|
+
headers["Idempotency-Key"] = idempotency_key
|
|
176
|
+
data = None
|
|
177
|
+
if payload is not None:
|
|
178
|
+
headers["Content-Type"] = "application/json"
|
|
179
|
+
data = json.dumps(payload, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode("utf-8")
|
|
180
|
+
|
|
181
|
+
# http.client issues one request and leaves redirects to the caller.
|
|
182
|
+
connection = self._connection(self._host, self._port, timeout=self._timeout)
|
|
183
|
+
status = request_id = retry_after = None
|
|
184
|
+
try:
|
|
185
|
+
connection.request(method, target, body=data, headers=headers)
|
|
186
|
+
with connection.getresponse() as response:
|
|
187
|
+
status = response.status
|
|
188
|
+
request_id = response.getheader("X-Request-Id")
|
|
189
|
+
retry_after = response.getheader("Retry-After")
|
|
190
|
+
raw = response.read()
|
|
191
|
+
except (OSError, http.client.HTTPException) as exc:
|
|
192
|
+
code = "request_timeout" if isinstance(exc, TimeoutError) else "network_error"
|
|
193
|
+
raise ShushuApiError(
|
|
194
|
+
code, str(exc), status=status, request_id=request_id, retry_after=retry_after
|
|
195
|
+
) from exc
|
|
196
|
+
finally:
|
|
197
|
+
connection.close()
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
body = json.loads(raw)
|
|
201
|
+
except ValueError as exc:
|
|
202
|
+
body = raw.decode("utf-8", errors="replace")
|
|
203
|
+
if 200 <= status < 300:
|
|
204
|
+
raise ShushuApiError(
|
|
205
|
+
"invalid_json_response", "Expected a JSON response", status=status,
|
|
206
|
+
request_id=request_id, retry_after=retry_after, body=body,
|
|
207
|
+
) from exc
|
|
208
|
+
if not 200 <= status < 300:
|
|
209
|
+
error = body.get("error") if isinstance(body, dict) else None
|
|
210
|
+
message = body.get("message") if isinstance(body, dict) else None
|
|
211
|
+
code = error if isinstance(error, str) and error else "http_error"
|
|
212
|
+
raise ShushuApiError(
|
|
213
|
+
code, message if isinstance(message, str) and message else f"HTTP {status} ({code})",
|
|
214
|
+
status=status, request_id=request_id, retry_after=retry_after, body=body,
|
|
215
|
+
)
|
|
216
|
+
return ShushuResponse(status=status, request_id=request_id, body=body)
|
shushu_open_api/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: shushu-open-api
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the Shushu Open Platform API
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
|
|
8
|
+
# 鼠鼠开放平台 Python SDK
|
|
9
|
+
|
|
10
|
+
在机器人、网站后端或小程序云函数中接入三角洲行动数据。SDK 支持查询每日地图密码、每周集市、物品价格和交易行快照,也支持解析改枪码,以及提交战绩查询、轮询状态和读取结果。
|
|
11
|
+
|
|
12
|
+
## 安装
|
|
13
|
+
|
|
14
|
+
支持 Python 3.10 及以上版本。
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
python -m pip install shushu-open-api
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 查询每日地图密码
|
|
21
|
+
|
|
22
|
+
在鼠鼠开放平台的「API Key 管理」创建密钥,并在运行服务的环境中设置 `SHUSHU_API_KEY`。客户端会读取该变量,向 `https://openapi.shushu.fan` 发起请求。
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from shushu_open_api import ShushuClient
|
|
26
|
+
|
|
27
|
+
client = ShushuClient()
|
|
28
|
+
reply = client.daily_passwords()
|
|
29
|
+
for entry in reply.body["passwords"]:
|
|
30
|
+
print(entry["n"], entry["s"])
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
成功响应的 `reply.request_id` 可用于在开放平台的「工具 → 请求诊断」查看本次调用。接口返回错误时,可以从 `ShushuApiError` 读取 `status`、`code` 和 `request_id`。
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
shushu_open_api/__init__.py,sha256=ItDa-makUlS6UQM6Mf2IxLkJo7hidrPKAWKHGsNg7oc,171
|
|
2
|
+
shushu_open_api/client.py,sha256=9OuZ-sAvPOUadRZosnH63A3i0vfvb5A4CcT0KwsyUK4,8822
|
|
3
|
+
shushu_open_api/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
|
|
4
|
+
shushu_open_api-0.1.0.dist-info/METADATA,sha256=zzeXq0-85itQfi_O4_M8x25MoWomT65WT0xpnpnKwy4,1215
|
|
5
|
+
shushu_open_api-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
shushu_open_api-0.1.0.dist-info/top_level.txt,sha256=tPXKkwalByG_z88YwPIbPivRkKYU9qOOD7E0J1TcT1w,16
|
|
7
|
+
shushu_open_api-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
shushu_open_api
|