fragment-api 1.0.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.
- fragment_api/__init__.py +48 -0
- fragment_api/_version.py +1 -0
- fragment_api/client.py +340 -0
- fragment_api/errors.py +54 -0
- fragment_api/models.py +272 -0
- fragment_api/py.typed +0 -0
- fragment_api-1.0.0.dist-info/METADATA +166 -0
- fragment_api-1.0.0.dist-info/RECORD +11 -0
- fragment_api-1.0.0.dist-info/WHEEL +5 -0
- fragment_api-1.0.0.dist-info/licenses/LICENSE +21 -0
- fragment_api-1.0.0.dist-info/top_level.txt +1 -0
fragment_api/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""fragment-api — Python client for the Fragment API (https://fragment-api.uz).
|
|
2
|
+
|
|
3
|
+
from fragment_api import FragmentAPI, FragmentError
|
|
4
|
+
|
|
5
|
+
api = FragmentAPI("API_KEY")
|
|
6
|
+
try:
|
|
7
|
+
order = api.stars.buy("durov", 50)
|
|
8
|
+
print(order.cost)
|
|
9
|
+
except FragmentError as e:
|
|
10
|
+
print(e.code, e.message)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from ._version import __version__
|
|
14
|
+
from .client import DEFAULT_BASE_URL, AsyncFragmentAPI, FragmentAPI
|
|
15
|
+
from .errors import FragmentError, OrderUncertainError
|
|
16
|
+
from .models import (
|
|
17
|
+
OrderStatus,
|
|
18
|
+
PremiumOrder,
|
|
19
|
+
PremiumPackage,
|
|
20
|
+
PremiumPricing,
|
|
21
|
+
Price,
|
|
22
|
+
StarsCapacity,
|
|
23
|
+
StarsOrder,
|
|
24
|
+
StarsPricing,
|
|
25
|
+
UserInfo,
|
|
26
|
+
WalletBalance,
|
|
27
|
+
WalletCalculation,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"__version__",
|
|
32
|
+
"DEFAULT_BASE_URL",
|
|
33
|
+
"FragmentAPI",
|
|
34
|
+
"AsyncFragmentAPI",
|
|
35
|
+
"FragmentError",
|
|
36
|
+
"OrderUncertainError",
|
|
37
|
+
"UserInfo",
|
|
38
|
+
"Price",
|
|
39
|
+
"StarsPricing",
|
|
40
|
+
"PremiumPackage",
|
|
41
|
+
"PremiumPricing",
|
|
42
|
+
"StarsOrder",
|
|
43
|
+
"PremiumOrder",
|
|
44
|
+
"WalletBalance",
|
|
45
|
+
"StarsCapacity",
|
|
46
|
+
"WalletCalculation",
|
|
47
|
+
"OrderStatus",
|
|
48
|
+
]
|
fragment_api/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
fragment_api/client.py
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"""Clients for https://fragment-api.uz. Methods follow the API's endpoints::
|
|
2
|
+
|
|
3
|
+
api.get_info(username) POST /getInfo -> UserInfo
|
|
4
|
+
api.stars.pricing(amount) POST /stars/pricing -> StarsPricing
|
|
5
|
+
api.stars.buy(username, amount) POST /stars/buy -> StarsOrder
|
|
6
|
+
api.premium.pricing() POST /premium/pricing -> PremiumPricing
|
|
7
|
+
api.premium.buy(username, duration) POST /premium/buy -> PremiumOrder
|
|
8
|
+
api.order.status(order_id) POST /order/status -> OrderStatus
|
|
9
|
+
api.wallet.balance() POST /wallet/balance -> WalletBalance
|
|
10
|
+
api.wallet.calculate() POST /wallet/calculate -> WalletCalculation
|
|
11
|
+
|
|
12
|
+
Any failure raises :class:`~fragment_api.errors.FragmentError` with the API's ``code``.
|
|
13
|
+
|
|
14
|
+
Read-only calls are retried up to 2 times on network errors, 429 and 502/503/504.
|
|
15
|
+
Buy calls are never retried, so the library cannot send an order twice; when a buy was sent
|
|
16
|
+
but its result is unknown, :class:`~fragment_api.errors.OrderUncertainError` is raised.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import asyncio
|
|
22
|
+
import os
|
|
23
|
+
import random
|
|
24
|
+
import time
|
|
25
|
+
from typing import Any, Callable, Dict, Optional, TypeVar
|
|
26
|
+
|
|
27
|
+
import httpx
|
|
28
|
+
|
|
29
|
+
from ._version import __version__
|
|
30
|
+
from .errors import FragmentError, OrderUncertainError
|
|
31
|
+
from .models import (
|
|
32
|
+
OrderStatus,
|
|
33
|
+
PremiumOrder,
|
|
34
|
+
PremiumPricing,
|
|
35
|
+
StarsOrder,
|
|
36
|
+
StarsPricing,
|
|
37
|
+
UserInfo,
|
|
38
|
+
WalletBalance,
|
|
39
|
+
WalletCalculation,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = ["FragmentAPI", "AsyncFragmentAPI", "DEFAULT_BASE_URL"]
|
|
43
|
+
|
|
44
|
+
DEFAULT_BASE_URL = "https://fragment-api.uz/api/v1"
|
|
45
|
+
API_KEY_ENV = "FRAGMENT_API_KEY"
|
|
46
|
+
DEFAULT_TIMEOUT = 30.0
|
|
47
|
+
# A buy can wait for the wallet queue, the blockchain confirmation and the forward to Fragment.
|
|
48
|
+
ORDER_TIMEOUT = 180.0
|
|
49
|
+
READ_RETRIES = 2
|
|
50
|
+
_RETRY_STATUSES = frozenset({429, 502, 503, 504})
|
|
51
|
+
# The server says this when the payment is already broadcast: "...So'rovni qayta yubormang."
|
|
52
|
+
_PENDING_MARKER = "qayta yubormang"
|
|
53
|
+
|
|
54
|
+
_MSG_NETWORK = "Serverga ulanib bo'lmadi. Internetni tekshirib, birozdan keyin qayta urinib ko'ring."
|
|
55
|
+
_MSG_NO_RESPONSE = "Server javob bermadi. Birozdan keyin qayta urinib ko'ring."
|
|
56
|
+
_MSG_NO_RESPONSE_ORDER = (
|
|
57
|
+
"Buyurtma yuborildi, lekin javob kelmadi. U bajarilgan bo'lishi mumkin — "
|
|
58
|
+
"qayta yubormang, avval dashboarddagi Tranzaksiyalar bo'limida tekshiring."
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
T = TypeVar("T")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _retry_after(http: httpx.Response) -> Optional[float]:
|
|
65
|
+
try:
|
|
66
|
+
return max(0.0, float(http.headers["Retry-After"]))
|
|
67
|
+
except (KeyError, ValueError):
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _delay(attempt: int, http: Optional[httpx.Response]) -> float:
|
|
72
|
+
if http is not None and http.status_code == 429:
|
|
73
|
+
return min(10.0, _retry_after(http) or 1.0)
|
|
74
|
+
return 0.5 * 2.0 ** attempt + random.uniform(0, 0.25)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _json_or_raise(http: httpx.Response, order: bool) -> Dict[str, Any]:
|
|
78
|
+
"""Return the API's JSON on success, raise FragmentError otherwise."""
|
|
79
|
+
try:
|
|
80
|
+
data = http.json()
|
|
81
|
+
except ValueError:
|
|
82
|
+
data = None
|
|
83
|
+
if not isinstance(data, dict) or "ok" not in data:
|
|
84
|
+
# Not the API's JSON: a proxy answered (e.g. nginx 504 while the order was still running).
|
|
85
|
+
if order:
|
|
86
|
+
raise OrderUncertainError(_MSG_NO_RESPONSE_ORDER, "NO_RESPONSE", http.status_code)
|
|
87
|
+
raise FragmentError(_MSG_NO_RESPONSE, "NO_RESPONSE", http.status_code)
|
|
88
|
+
if data.get("ok") is True:
|
|
89
|
+
return data
|
|
90
|
+
message = str(data.get("message") or f"So'rov bajarilmadi (HTTP {http.status_code}).")
|
|
91
|
+
code = str(data.get("code") or "UNKNOWN_ERROR")
|
|
92
|
+
# On a buy, CRITICAL_SERVER_ERROR can come after the payment was sent (timeout during the transfer,
|
|
93
|
+
# failure to record it), and "qayta yubormang" means the payment is waiting for confirmation.
|
|
94
|
+
uncertain = order and (code in ("PAYMENT_PENDING", "CRITICAL_SERVER_ERROR") or _PENDING_MARKER in message.lower())
|
|
95
|
+
order_id = data.get("order_id") if isinstance(data.get("order_id"), int) else None
|
|
96
|
+
raise (OrderUncertainError if uncertain else FragmentError)(message, code, http.status_code, _retry_after(http), order_id)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _transport_error(exc: httpx.HTTPError, order: bool) -> FragmentError:
|
|
100
|
+
if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
|
|
101
|
+
return FragmentError(_MSG_NETWORK, "NETWORK_ERROR") # never reached the server
|
|
102
|
+
if order:
|
|
103
|
+
return OrderUncertainError(_MSG_NO_RESPONSE_ORDER, "NO_RESPONSE")
|
|
104
|
+
return FragmentError(_MSG_NO_RESPONSE, "NO_RESPONSE")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class _Base:
|
|
108
|
+
def __init__(self, api_key: Optional[str], base_url: str, timeout: float) -> None:
|
|
109
|
+
key = (api_key if api_key is not None else os.environ.get(API_KEY_ENV, "")).strip()
|
|
110
|
+
if not key:
|
|
111
|
+
raise ValueError(
|
|
112
|
+
f"API kalit kerak: FragmentAPI('KALIT') yoki {API_KEY_ENV} muhit o'zgaruvchisi. "
|
|
113
|
+
"Kalit: https://fragment-api.uz/dashboard → loyiha sozlamalari."
|
|
114
|
+
)
|
|
115
|
+
self.api_key = key
|
|
116
|
+
self.base_url = base_url.rstrip("/")
|
|
117
|
+
self.timeout = timeout
|
|
118
|
+
self._headers = {
|
|
119
|
+
"X-API-Key": key,
|
|
120
|
+
"Accept": "application/json",
|
|
121
|
+
"User-Agent": f"fragment-api-python/{__version__}",
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
def __repr__(self) -> str:
|
|
125
|
+
return f"{type(self).__name__}(base_url={self.base_url!r}, api_key='…{self.api_key[-4:]}')"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ================================================================ sync
|
|
129
|
+
|
|
130
|
+
class _Group:
|
|
131
|
+
def __init__(self, api: "FragmentAPI") -> None:
|
|
132
|
+
self._api = api
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class Stars(_Group):
|
|
136
|
+
"""``api.stars`` — Telegram Stars."""
|
|
137
|
+
|
|
138
|
+
def pricing(self, amount: int) -> StarsPricing:
|
|
139
|
+
"""Price of ``amount`` stars, commission included (``POST /stars/pricing``)."""
|
|
140
|
+
return self._api._post("/stars/pricing", {"amount": amount}, StarsPricing._from)
|
|
141
|
+
|
|
142
|
+
def buy(self, username: str, amount: int) -> StarsOrder:
|
|
143
|
+
"""Send ``amount`` stars (minimum 50) to ``username`` (``POST /stars/buy``)."""
|
|
144
|
+
return self._api._post("/stars/buy", {"username": username, "amount": amount}, StarsOrder._from, order=True)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Premium(_Group):
|
|
148
|
+
"""``api.premium`` — Telegram Premium."""
|
|
149
|
+
|
|
150
|
+
def pricing(self) -> PremiumPricing:
|
|
151
|
+
"""Premium packages for 3, 6 and 12 months (``POST /premium/pricing``)."""
|
|
152
|
+
return self._api._post("/premium/pricing", {}, PremiumPricing._from)
|
|
153
|
+
|
|
154
|
+
def buy(self, username: str, duration: int) -> PremiumOrder:
|
|
155
|
+
"""Gift Premium to ``username`` for ``duration`` months: 3, 6 or 12 (``POST /premium/buy``)."""
|
|
156
|
+
return self._api._post("/premium/buy", {"username": username, "duration": duration}, PremiumOrder._from, order=True)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class Order(_Group):
|
|
160
|
+
"""``api.order`` — order status."""
|
|
161
|
+
|
|
162
|
+
def status(self, order_id: int) -> OrderStatus:
|
|
163
|
+
"""Status of an order by the ``order_id`` from a buy response (``POST /order/status``)."""
|
|
164
|
+
return self._api._post("/order/status", {"order_id": order_id}, OrderStatus._from)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
class Wallet(_Group):
|
|
168
|
+
"""``api.wallet`` — the project's TON wallet."""
|
|
169
|
+
|
|
170
|
+
def balance(self) -> WalletBalance:
|
|
171
|
+
"""Wallet balance in TON (and USDT) (``POST /wallet/balance``)."""
|
|
172
|
+
return self._api._post("/wallet/balance", {}, WalletBalance._from)
|
|
173
|
+
|
|
174
|
+
def calculate(self) -> WalletCalculation:
|
|
175
|
+
"""How many stars and which Premium packages the wallet can pay for (``POST /wallet/calculate``)."""
|
|
176
|
+
return self._api._post("/wallet/calculate", {}, WalletCalculation._from)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class FragmentAPI(_Base):
|
|
180
|
+
"""Fragment API client.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
api_key: the project's API key. If omitted, ``FRAGMENT_API_KEY`` is used.
|
|
184
|
+
timeout: seconds to wait for read-only calls (buys always wait up to 180 s).
|
|
185
|
+
|
|
186
|
+
Example::
|
|
187
|
+
|
|
188
|
+
api = FragmentAPI("API_KEY")
|
|
189
|
+
order = api.stars.buy("durov", 50)
|
|
190
|
+
print(order.cost)
|
|
191
|
+
"""
|
|
192
|
+
|
|
193
|
+
stars: Stars
|
|
194
|
+
premium: Premium
|
|
195
|
+
order: Order
|
|
196
|
+
wallet: Wallet
|
|
197
|
+
|
|
198
|
+
def __init__(self, api_key: Optional[str] = None, *, timeout: float = DEFAULT_TIMEOUT, base_url: str = DEFAULT_BASE_URL) -> None:
|
|
199
|
+
super().__init__(api_key, base_url, timeout)
|
|
200
|
+
self._http = httpx.Client()
|
|
201
|
+
self.stars = Stars(self)
|
|
202
|
+
self.premium = Premium(self)
|
|
203
|
+
self.order = Order(self)
|
|
204
|
+
self.wallet = Wallet(self)
|
|
205
|
+
|
|
206
|
+
def get_info(self, username: str) -> UserInfo:
|
|
207
|
+
"""Telegram user info by username (``POST /getInfo``). Limit: 2 requests/second (Gold: 5)."""
|
|
208
|
+
return self._post("/getInfo", {"username": username}, UserInfo._from)
|
|
209
|
+
|
|
210
|
+
def close(self) -> None:
|
|
211
|
+
"""Close the HTTP connections."""
|
|
212
|
+
self._http.close()
|
|
213
|
+
|
|
214
|
+
def __enter__(self) -> "FragmentAPI":
|
|
215
|
+
return self
|
|
216
|
+
|
|
217
|
+
def __exit__(self, *exc: Any) -> None:
|
|
218
|
+
self.close()
|
|
219
|
+
|
|
220
|
+
def _post(self, path: str, body: Dict[str, Any], parse: Callable[[Dict[str, Any]], T], order: bool = False) -> T:
|
|
221
|
+
tries = 1 if order else 1 + READ_RETRIES
|
|
222
|
+
for attempt in range(tries):
|
|
223
|
+
last = attempt == tries - 1
|
|
224
|
+
try:
|
|
225
|
+
http = self._http.post(
|
|
226
|
+
self.base_url + path, json=body, headers=self._headers,
|
|
227
|
+
timeout=max(self.timeout, ORDER_TIMEOUT) if order else self.timeout,
|
|
228
|
+
)
|
|
229
|
+
except httpx.HTTPError as exc:
|
|
230
|
+
if last:
|
|
231
|
+
raise _transport_error(exc, order) from exc
|
|
232
|
+
time.sleep(_delay(attempt, None))
|
|
233
|
+
continue
|
|
234
|
+
if not last and http.status_code in _RETRY_STATUSES:
|
|
235
|
+
time.sleep(_delay(attempt, http))
|
|
236
|
+
continue
|
|
237
|
+
return parse(_json_or_raise(http, order))
|
|
238
|
+
raise AssertionError("unreachable") # pragma: no cover
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# ================================================================ async
|
|
242
|
+
|
|
243
|
+
class _AsyncGroup:
|
|
244
|
+
def __init__(self, api: "AsyncFragmentAPI") -> None:
|
|
245
|
+
self._api = api
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
class AsyncStars(_AsyncGroup):
|
|
249
|
+
"""``api.stars`` — Telegram Stars."""
|
|
250
|
+
|
|
251
|
+
async def pricing(self, amount: int) -> StarsPricing:
|
|
252
|
+
"""Price of ``amount`` stars, commission included (``POST /stars/pricing``)."""
|
|
253
|
+
return await self._api._post("/stars/pricing", {"amount": amount}, StarsPricing._from)
|
|
254
|
+
|
|
255
|
+
async def buy(self, username: str, amount: int) -> StarsOrder:
|
|
256
|
+
"""Send ``amount`` stars (minimum 50) to ``username`` (``POST /stars/buy``)."""
|
|
257
|
+
return await self._api._post("/stars/buy", {"username": username, "amount": amount}, StarsOrder._from, order=True)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
class AsyncPremium(_AsyncGroup):
|
|
261
|
+
"""``api.premium`` — Telegram Premium."""
|
|
262
|
+
|
|
263
|
+
async def pricing(self) -> PremiumPricing:
|
|
264
|
+
"""Premium packages for 3, 6 and 12 months (``POST /premium/pricing``)."""
|
|
265
|
+
return await self._api._post("/premium/pricing", {}, PremiumPricing._from)
|
|
266
|
+
|
|
267
|
+
async def buy(self, username: str, duration: int) -> PremiumOrder:
|
|
268
|
+
"""Gift Premium to ``username`` for ``duration`` months: 3, 6 or 12 (``POST /premium/buy``)."""
|
|
269
|
+
return await self._api._post("/premium/buy", {"username": username, "duration": duration}, PremiumOrder._from, order=True)
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
class AsyncOrder(_AsyncGroup):
|
|
273
|
+
"""``api.order`` — order status."""
|
|
274
|
+
|
|
275
|
+
async def status(self, order_id: int) -> OrderStatus:
|
|
276
|
+
"""Status of an order by the ``order_id`` from a buy response (``POST /order/status``)."""
|
|
277
|
+
return await self._api._post("/order/status", {"order_id": order_id}, OrderStatus._from)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class AsyncWallet(_AsyncGroup):
|
|
281
|
+
"""``api.wallet`` — the project's TON wallet."""
|
|
282
|
+
|
|
283
|
+
async def balance(self) -> WalletBalance:
|
|
284
|
+
"""Wallet balance in TON (and USDT) (``POST /wallet/balance``)."""
|
|
285
|
+
return await self._api._post("/wallet/balance", {}, WalletBalance._from)
|
|
286
|
+
|
|
287
|
+
async def calculate(self) -> WalletCalculation:
|
|
288
|
+
"""How many stars and which Premium packages the wallet can pay for (``POST /wallet/calculate``)."""
|
|
289
|
+
return await self._api._post("/wallet/calculate", {}, WalletCalculation._from)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
class AsyncFragmentAPI(_Base):
|
|
293
|
+
"""Async Fragment API client (aiogram, FastAPI). Same methods as :class:`FragmentAPI`, with ``await``."""
|
|
294
|
+
|
|
295
|
+
stars: AsyncStars
|
|
296
|
+
premium: AsyncPremium
|
|
297
|
+
order: AsyncOrder
|
|
298
|
+
wallet: AsyncWallet
|
|
299
|
+
|
|
300
|
+
def __init__(self, api_key: Optional[str] = None, *, timeout: float = DEFAULT_TIMEOUT, base_url: str = DEFAULT_BASE_URL) -> None:
|
|
301
|
+
super().__init__(api_key, base_url, timeout)
|
|
302
|
+
self._http = httpx.AsyncClient()
|
|
303
|
+
self.stars = AsyncStars(self)
|
|
304
|
+
self.premium = AsyncPremium(self)
|
|
305
|
+
self.order = AsyncOrder(self)
|
|
306
|
+
self.wallet = AsyncWallet(self)
|
|
307
|
+
|
|
308
|
+
async def get_info(self, username: str) -> UserInfo:
|
|
309
|
+
"""Telegram user info by username (``POST /getInfo``). Limit: 2 requests/second (Gold: 5)."""
|
|
310
|
+
return await self._post("/getInfo", {"username": username}, UserInfo._from)
|
|
311
|
+
|
|
312
|
+
async def close(self) -> None:
|
|
313
|
+
"""Close the HTTP connections."""
|
|
314
|
+
await self._http.aclose()
|
|
315
|
+
|
|
316
|
+
async def __aenter__(self) -> "AsyncFragmentAPI":
|
|
317
|
+
return self
|
|
318
|
+
|
|
319
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
320
|
+
await self.close()
|
|
321
|
+
|
|
322
|
+
async def _post(self, path: str, body: Dict[str, Any], parse: Callable[[Dict[str, Any]], T], order: bool = False) -> T:
|
|
323
|
+
tries = 1 if order else 1 + READ_RETRIES
|
|
324
|
+
for attempt in range(tries):
|
|
325
|
+
last = attempt == tries - 1
|
|
326
|
+
try:
|
|
327
|
+
http = await self._http.post(
|
|
328
|
+
self.base_url + path, json=body, headers=self._headers,
|
|
329
|
+
timeout=max(self.timeout, ORDER_TIMEOUT) if order else self.timeout,
|
|
330
|
+
)
|
|
331
|
+
except httpx.HTTPError as exc:
|
|
332
|
+
if last:
|
|
333
|
+
raise _transport_error(exc, order) from exc
|
|
334
|
+
await asyncio.sleep(_delay(attempt, None))
|
|
335
|
+
continue
|
|
336
|
+
if not last and http.status_code in _RETRY_STATUSES:
|
|
337
|
+
await asyncio.sleep(_delay(attempt, http))
|
|
338
|
+
continue
|
|
339
|
+
return parse(_json_or_raise(http, order))
|
|
340
|
+
raise AssertionError("unreachable") # pragma: no cover
|
fragment_api/errors.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Errors. One exception for everything, carrying the API's own error code.
|
|
2
|
+
|
|
3
|
+
try:
|
|
4
|
+
order = api.stars.buy("durov", 50)
|
|
5
|
+
except FragmentError as e:
|
|
6
|
+
print(e.code, e.message) # INSUFFICIENT_FUNDS Hamyonda to'lov uchun yetarli mablag' yo'q.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Optional
|
|
12
|
+
|
|
13
|
+
__all__ = ["FragmentError", "OrderUncertainError"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FragmentError(Exception):
|
|
17
|
+
"""An error from the API or the connection.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
code: the API error code (``INSUFFICIENT_FUNDS``, ``RATE_LIMIT``, ...), or
|
|
21
|
+
``NETWORK_ERROR`` / ``NO_RESPONSE`` when the server could not be reached.
|
|
22
|
+
message: human-readable text from the server (in the project owner's language, else English).
|
|
23
|
+
status_code: HTTP status, if the server answered.
|
|
24
|
+
retry_after: seconds to wait, for ``RATE_LIMIT``.
|
|
25
|
+
order_id: set when a buy reached the payment step (e.g. ``PAYMENT_PENDING``) —
|
|
26
|
+
check it with ``api.order.status(order_id)``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
message: str,
|
|
32
|
+
code: str,
|
|
33
|
+
status_code: Optional[int] = None,
|
|
34
|
+
retry_after: Optional[float] = None,
|
|
35
|
+
order_id: Optional[int] = None,
|
|
36
|
+
) -> None:
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
self.message = message
|
|
39
|
+
self.code = code
|
|
40
|
+
self.status_code = status_code
|
|
41
|
+
self.retry_after = retry_after
|
|
42
|
+
self.order_id = order_id
|
|
43
|
+
|
|
44
|
+
def __str__(self) -> str:
|
|
45
|
+
return f"{self.code}: {self.message}"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class OrderUncertainError(FragmentError):
|
|
49
|
+
"""A buy request was sent, but its result is unknown: the order may already be paid.
|
|
50
|
+
|
|
51
|
+
Raised only by ``stars.buy`` / ``premium.buy`` when no answer came back (``NO_RESPONSE``),
|
|
52
|
+
when the server says the payment is waiting for confirmation, or on ``CRITICAL_SERVER_ERROR``.
|
|
53
|
+
Do not send the same order again. Check it in the dashboard (Tranzaksiyalar) first.
|
|
54
|
+
"""
|
fragment_api/models.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
"""Results of the API calls.
|
|
2
|
+
|
|
3
|
+
Field names are the same as in the API's ``result`` JSON. Money is :class:`~decimal.Decimal`
|
|
4
|
+
(exact, no float rounding), counts are ``int``. ``raw`` keeps the full JSON answer.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from decimal import Decimal, InvalidOperation
|
|
12
|
+
from typing import Any, Dict, List, Optional
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"UserInfo",
|
|
16
|
+
"Price",
|
|
17
|
+
"StarsPricing",
|
|
18
|
+
"PremiumPackage",
|
|
19
|
+
"PremiumPricing",
|
|
20
|
+
"StarsOrder",
|
|
21
|
+
"PremiumOrder",
|
|
22
|
+
"WalletBalance",
|
|
23
|
+
"StarsCapacity",
|
|
24
|
+
"WalletCalculation",
|
|
25
|
+
"OrderStatus",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _money(value: Any) -> Optional[Decimal]:
|
|
30
|
+
if value is None or value == "":
|
|
31
|
+
return None
|
|
32
|
+
try:
|
|
33
|
+
return Decimal(str(value))
|
|
34
|
+
except (InvalidOperation, ValueError):
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _money0(value: Any) -> Decimal:
|
|
39
|
+
parsed = _money(value)
|
|
40
|
+
return parsed if parsed is not None else Decimal("0")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _int(value: Any) -> int:
|
|
44
|
+
try:
|
|
45
|
+
return int(value)
|
|
46
|
+
except (TypeError, ValueError):
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _dict(value: Any) -> Dict[str, Any]:
|
|
51
|
+
return value if isinstance(value, dict) else {}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _opt_int(value: Any) -> Optional[int]:
|
|
55
|
+
try:
|
|
56
|
+
return int(value) if value is not None else None
|
|
57
|
+
except (TypeError, ValueError):
|
|
58
|
+
return None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _time(value: Any) -> Optional[datetime]:
|
|
62
|
+
if not isinstance(value, str) or not value:
|
|
63
|
+
return None
|
|
64
|
+
try:
|
|
65
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
66
|
+
except ValueError:
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True)
|
|
71
|
+
class UserInfo:
|
|
72
|
+
"""``/getInfo``: a Telegram user."""
|
|
73
|
+
|
|
74
|
+
username: str
|
|
75
|
+
name: Optional[str]
|
|
76
|
+
photo: Optional[str]
|
|
77
|
+
is_premium: bool
|
|
78
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
79
|
+
|
|
80
|
+
@classmethod
|
|
81
|
+
def _from(cls, data: Dict[str, Any]) -> "UserInfo":
|
|
82
|
+
r = _dict(data.get("result"))
|
|
83
|
+
return cls(str(r.get("username") or ""), r.get("name"), r.get("photo"), bool(r.get("is_premium")), data)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class Price:
|
|
88
|
+
"""A price in TON and USD; ``selected`` is in the project's payment currency."""
|
|
89
|
+
|
|
90
|
+
ton: Decimal
|
|
91
|
+
usd: Decimal
|
|
92
|
+
selected: Decimal
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True)
|
|
96
|
+
class StarsPricing:
|
|
97
|
+
"""``/stars/pricing``: price of ``amount`` stars, commission included."""
|
|
98
|
+
|
|
99
|
+
amount: int
|
|
100
|
+
price: Price
|
|
101
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
102
|
+
|
|
103
|
+
@classmethod
|
|
104
|
+
def _from(cls, data: Dict[str, Any]) -> "StarsPricing":
|
|
105
|
+
r = _dict(data.get("result"))
|
|
106
|
+
p = _dict(r.get("price"))
|
|
107
|
+
return cls(_int(r.get("amount")), Price(_money0(p.get("ton")), _money0(p.get("usd")), _money0(p.get("selected"))), data)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@dataclass(frozen=True)
|
|
111
|
+
class PremiumPackage:
|
|
112
|
+
"""One Premium package: ``months`` and its price, commission included."""
|
|
113
|
+
|
|
114
|
+
months: int
|
|
115
|
+
ton: Decimal
|
|
116
|
+
usd: Decimal
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _packages(value: Any) -> List[PremiumPackage]:
|
|
120
|
+
items = value if isinstance(value, list) else []
|
|
121
|
+
return [PremiumPackage(_int(i.get("months")), _money0(i.get("ton")), _money0(i.get("usd"))) for i in items if isinstance(i, dict)]
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True)
|
|
125
|
+
class PremiumPricing:
|
|
126
|
+
"""``/premium/pricing``: available Premium packages (3, 6, 12 months)."""
|
|
127
|
+
|
|
128
|
+
packages: List[PremiumPackage]
|
|
129
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
130
|
+
|
|
131
|
+
@classmethod
|
|
132
|
+
def _from(cls, data: Dict[str, Any]) -> "PremiumPricing":
|
|
133
|
+
return cls(_packages(_dict(data.get("result")).get("packages")), data)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class StarsOrder:
|
|
138
|
+
"""``/stars/buy``: a completed stars order. ``cost`` is in ``payment_method`` (TON or USDT)."""
|
|
139
|
+
|
|
140
|
+
username: str
|
|
141
|
+
amount: int
|
|
142
|
+
payment_method: str
|
|
143
|
+
cost: Decimal
|
|
144
|
+
order_id: Optional[int] = None
|
|
145
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
146
|
+
|
|
147
|
+
@classmethod
|
|
148
|
+
def _from(cls, data: Dict[str, Any]) -> "StarsOrder":
|
|
149
|
+
r = _dict(data.get("result"))
|
|
150
|
+
return cls(
|
|
151
|
+
str(r.get("username") or ""), _int(r.get("amount")), str(r.get("payment_method") or ""), _money0(r.get("cost")),
|
|
152
|
+
_opt_int(r.get("order_id")), data,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class PremiumOrder:
|
|
158
|
+
"""``/premium/buy``: a completed Premium order. ``duration`` is in months."""
|
|
159
|
+
|
|
160
|
+
username: str
|
|
161
|
+
duration: int
|
|
162
|
+
payment_method: str
|
|
163
|
+
cost: Decimal
|
|
164
|
+
order_id: Optional[int] = None
|
|
165
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
166
|
+
|
|
167
|
+
@classmethod
|
|
168
|
+
def _from(cls, data: Dict[str, Any]) -> "PremiumOrder":
|
|
169
|
+
r = _dict(data.get("result"))
|
|
170
|
+
return cls(
|
|
171
|
+
str(r.get("username") or ""), _int(r.get("duration")), str(r.get("payment_method") or ""), _money0(r.get("cost")),
|
|
172
|
+
_opt_int(r.get("order_id")), data,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@dataclass(frozen=True)
|
|
177
|
+
class WalletBalance:
|
|
178
|
+
"""``/wallet/balance``: the project wallet. ``balance_usdt`` is ``None`` for TON projects."""
|
|
179
|
+
|
|
180
|
+
project: str
|
|
181
|
+
address: str
|
|
182
|
+
balance_ton: Decimal
|
|
183
|
+
balance_usdt: Optional[Decimal]
|
|
184
|
+
wallet_version: str
|
|
185
|
+
network: str
|
|
186
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
187
|
+
|
|
188
|
+
@classmethod
|
|
189
|
+
def _from(cls, data: Dict[str, Any]) -> "WalletBalance":
|
|
190
|
+
r = _dict(data.get("result"))
|
|
191
|
+
return cls(
|
|
192
|
+
str(r.get("project") or ""),
|
|
193
|
+
str(r.get("address") or ""),
|
|
194
|
+
_money0(r.get("balance_ton")),
|
|
195
|
+
_money(r.get("balance_usdt")),
|
|
196
|
+
str(r.get("wallet_version") or ""),
|
|
197
|
+
str(r.get("network") or ""),
|
|
198
|
+
data,
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@dataclass(frozen=True)
|
|
203
|
+
class StarsCapacity:
|
|
204
|
+
"""How many stars the wallet can buy now (``max_amount``) and what they cost (``amount``)."""
|
|
205
|
+
|
|
206
|
+
max_amount: int
|
|
207
|
+
asset: str
|
|
208
|
+
amount: Decimal
|
|
209
|
+
ton: Decimal
|
|
210
|
+
usdt: Optional[Decimal]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
@dataclass(frozen=True)
|
|
214
|
+
class WalletCalculation:
|
|
215
|
+
"""``/wallet/calculate``: what the project wallet can pay for right now."""
|
|
216
|
+
|
|
217
|
+
balance_ton: Decimal
|
|
218
|
+
balance_usdt: Optional[Decimal]
|
|
219
|
+
stars: StarsCapacity
|
|
220
|
+
premium: PremiumPricing
|
|
221
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
222
|
+
|
|
223
|
+
@classmethod
|
|
224
|
+
def _from(cls, data: Dict[str, Any]) -> "WalletCalculation":
|
|
225
|
+
r = _dict(data.get("result"))
|
|
226
|
+
s = _dict(r.get("stars"))
|
|
227
|
+
return cls(
|
|
228
|
+
_money0(r.get("balance_ton")),
|
|
229
|
+
_money(r.get("balance_usdt")),
|
|
230
|
+
StarsCapacity(_int(s.get("max_amount")), str(s.get("asset") or ""), _money0(s.get("amount")), _money0(s.get("ton")), _money(s.get("usdt"))),
|
|
231
|
+
PremiumPricing(_packages(_dict(r.get("premium")).get("packages"))),
|
|
232
|
+
data,
|
|
233
|
+
)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
@dataclass(frozen=True)
|
|
237
|
+
class OrderStatus:
|
|
238
|
+
"""``/order/status``: an order's current state.
|
|
239
|
+
|
|
240
|
+
``status``: ``completed`` | ``processing`` (paid, being sent to Fragment) | ``pending`` (payment
|
|
241
|
+
confirmation awaited — do not resend) | ``failed`` (not done, no funds deducted) | ``refunded``.
|
|
242
|
+
"""
|
|
243
|
+
|
|
244
|
+
order_id: int
|
|
245
|
+
type: str
|
|
246
|
+
username: str
|
|
247
|
+
status: str
|
|
248
|
+
payment_method: str
|
|
249
|
+
cost: Decimal
|
|
250
|
+
completed_at: Optional[datetime]
|
|
251
|
+
amount: Optional[int] = None
|
|
252
|
+
duration: Optional[int] = None
|
|
253
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
|
|
254
|
+
|
|
255
|
+
@classmethod
|
|
256
|
+
def _from_item(cls, r: Dict[str, Any]) -> "OrderStatus":
|
|
257
|
+
return cls(
|
|
258
|
+
order_id=_int(r.get("order_id")),
|
|
259
|
+
type=str(r.get("type") or ""),
|
|
260
|
+
username=str(r.get("username") or ""),
|
|
261
|
+
status=str(r.get("status") or ""),
|
|
262
|
+
payment_method=str(r.get("payment_method") or ""),
|
|
263
|
+
cost=_money0(r.get("cost")),
|
|
264
|
+
completed_at=_time(r.get("completed_at")),
|
|
265
|
+
amount=_opt_int(r.get("amount")),
|
|
266
|
+
duration=_opt_int(r.get("duration")),
|
|
267
|
+
raw=r,
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
@classmethod
|
|
271
|
+
def _from(cls, data: Dict[str, Any]) -> "OrderStatus":
|
|
272
|
+
return cls._from_item(_dict(data.get("result")))
|
fragment_api/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fragment-api
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Python client for the Fragment API (fragment-api.uz): buy Telegram Stars and Premium from your bot.
|
|
5
|
+
Author: Fragment API
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://fragment-api.uz
|
|
8
|
+
Project-URL: Documentation, https://fragment-api.uz/docs
|
|
9
|
+
Keywords: telegram,stars,premium,fragment,ton,usdt,api,sdk
|
|
10
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Framework :: AsyncIO
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.9
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: httpx<1,>=0.26
|
|
21
|
+
Provides-Extra: test
|
|
22
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# fragment-api
|
|
26
|
+
|
|
27
|
+
[Fragment API](https://fragment-api.uz) uchun Python kutubxona: botingizdan Telegram Stars va Premium soting.
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from fragment_api import FragmentAPI
|
|
31
|
+
|
|
32
|
+
api = FragmentAPI("API_KALIT")
|
|
33
|
+
order = api.stars.buy("durov", 50)
|
|
34
|
+
print(order.cost) # 0.76125
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## O'rnatish
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install fragment-api
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Python 3.9 yoki undan yangi versiya kerak.
|
|
44
|
+
|
|
45
|
+
API kalitni [dashboard](https://fragment-api.uz/dashboard) → loyiha sozlamalaridan oling. Kalitni kodga yozish o'rniga `FRAGMENT_API_KEY` muhit o'zgaruvchisiga qo'ysangiz, `FragmentAPI()` kifoya.
|
|
46
|
+
|
|
47
|
+
## Metodlar
|
|
48
|
+
|
|
49
|
+
Metodlar API endpointlari bo'yicha guruhlangan: `/stars/buy` → `api.stars.buy()`.
|
|
50
|
+
|
|
51
|
+
| Metod | Endpoint | Qaytaradi |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `api.get_info(username)` | `/getInfo` | `UserInfo` |
|
|
54
|
+
| `api.stars.pricing(amount)` | `/stars/pricing` | `StarsPricing` |
|
|
55
|
+
| `api.stars.buy(username, amount)` | `/stars/buy` | `StarsOrder` |
|
|
56
|
+
| `api.premium.pricing()` | `/premium/pricing` | `PremiumPricing` |
|
|
57
|
+
| `api.premium.buy(username, duration)` | `/premium/buy` | `PremiumOrder` |
|
|
58
|
+
| `api.order.status(order_id)` | `/order/status` | `OrderStatus` |
|
|
59
|
+
| `api.wallet.balance()` | `/wallet/balance` | `WalletBalance` |
|
|
60
|
+
| `api.wallet.calculate()` | `/wallet/calculate` | `WalletCalculation` |
|
|
61
|
+
|
|
62
|
+
Natija maydonlarining nomlari API javobidagi bilan bir xil. Pul summalari `Decimal` turida keladi: aniq son, bemalol hisoblash mumkin.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
user = api.get_info("durov")
|
|
66
|
+
user.name, user.is_premium # 'Pavel Durov', True
|
|
67
|
+
|
|
68
|
+
price = api.stars.pricing(50)
|
|
69
|
+
price.price.selected # Decimal('0.76125'), loyihangiz valyutasida
|
|
70
|
+
|
|
71
|
+
order = api.stars.buy("durov", 50)
|
|
72
|
+
order.amount, order.cost, order.payment_method # 50, Decimal('0.76125'), 'USDT'
|
|
73
|
+
|
|
74
|
+
for p in api.premium.pricing().packages:
|
|
75
|
+
print(p.months, p.usd) # 3 12.17 ...
|
|
76
|
+
|
|
77
|
+
order = api.premium.buy("durov", duration=3)
|
|
78
|
+
order.duration, order.cost # 3, Decimal('5.075')
|
|
79
|
+
|
|
80
|
+
wallet = api.wallet.balance()
|
|
81
|
+
wallet.balance_ton, wallet.balance_usdt # Decimal('1.2400'), Decimal('12.500000')
|
|
82
|
+
|
|
83
|
+
api.wallet.calculate().stars.max_amount # 16 — hamyon hozir nechta stars'ga yetadi
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Xatolar
|
|
87
|
+
|
|
88
|
+
Har qanday xatoda `FragmentError` chiqadi. Uning ichida API'dagi xato kodi (`e.code`) va tushuntirish (`e.message`) bo'ladi:
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from fragment_api import FragmentAPI, FragmentError
|
|
92
|
+
|
|
93
|
+
try:
|
|
94
|
+
order = api.stars.buy("durov", 50)
|
|
95
|
+
except FragmentError as e:
|
|
96
|
+
if e.code == "INSUFFICIENT_FUNDS":
|
|
97
|
+
print("Hamyonni to'ldiring")
|
|
98
|
+
else:
|
|
99
|
+
print(e.code, e.message)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
| `e.code` | Ma'nosi |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `VALIDATION_ERROR` | API kalit yoki maydon noto'g'ri, hamyon ulanmagan |
|
|
105
|
+
| `IP_NOT_ALLOWED` | server IP'si loyihaning IP ro'yxatida yo'q |
|
|
106
|
+
| `INVALID_AMOUNT_MIN` / `INVALID_AMOUNT_MAX` | stars miqdori 50 dan kam yoki 10 000 000 dan ko'p |
|
|
107
|
+
| `INSUFFICIENT_FUNDS` | hamyonda to'lov uchun mablag' yetmaydi |
|
|
108
|
+
| `INSUFFICIENT_GAS` | hamyonda gaz (blokcheyn to'lovi) uchun TON yetmaydi |
|
|
109
|
+
| `RATE_LIMIT` | so'rovlar juda ko'p, `e.retry_after` soniya kuting |
|
|
110
|
+
| `USERNAME_NOT_FOUND` | username topilmadi yoki foydalanuvchiga tegishli emas (kanal yoki bot) — qayta urinish foyda bermaydi |
|
|
111
|
+
| `FRAGMENT_ERROR` / `FRAGMENT_TIMEOUT` | Fragment vaqtincha ishlamayapti |
|
|
112
|
+
| `BLOCKCHAIN_FAIL` | TON tarmog'ida vaqtincha muammo |
|
|
113
|
+
| `PAYMENT_REJECTED` | to'lov blokcheynga kiritilmadi, pul yechilmagan — qayta yuborish mumkin |
|
|
114
|
+
| `PAYMENT_PENDING` | to'lov yuborildi, natija ~90 s ichida aniqlanmadi — `OrderUncertainError`, qayta yubormang |
|
|
115
|
+
| `CRITICAL_SERVER_ERROR` | serverda kutilmagan xato |
|
|
116
|
+
| `NETWORK_ERROR` | serverga ulanib bo'lmadi (internet) |
|
|
117
|
+
| `NO_RESPONSE` | so'rov ketdi, lekin javob kelmadi |
|
|
118
|
+
|
|
119
|
+
### Muhim: xaridni ikki marta yubormang
|
|
120
|
+
|
|
121
|
+
Xarid so'rovi ketgandan keyin javob kelmasa yoki server "to'lov yuborildi, tasdiq kutilmoqda" yoki `CRITICAL_SERVER_ERROR` desa, pul allaqachon ketgan bo'lishi mumkin. Bunday holatlarda `FragmentError`'ning maxsus turi — `OrderUncertainError` chiqadi:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
from fragment_api import FragmentError, OrderUncertainError
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
order = api.stars.buy("durov", 50)
|
|
128
|
+
except OrderUncertainError:
|
|
129
|
+
print("Buyurtma tekshirilmoqda") # QAYTA YUBORMANG — dashboarddagi Tranzaksiyalarni tekshiring
|
|
130
|
+
except FragmentError as e:
|
|
131
|
+
print(e.message) # server buyurtma bajarilmaganini aytdi
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Bunday xatoda server buyurtma raqamini ham beradi (`e.order_id`). U orqali natijani keyinroq tekshirish mumkin:
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
try:
|
|
138
|
+
order = api.stars.buy("durov", 50)
|
|
139
|
+
except OrderUncertainError as e:
|
|
140
|
+
st = api.order.status(e.order_id) if e.order_id else None
|
|
141
|
+
# st.status: completed | processing | pending | failed | refunded
|
|
142
|
+
# failed — pul yechilmagan, qayta yuborish mumkin; pending — kuting
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Javob umuman kelmagan bo'lsa (`NO_RESPONSE`), `order_id` bo'lmaydi — natijani dashboarddagi Tranzaksiyalar bo'limidan tekshiring.
|
|
146
|
+
|
|
147
|
+
Muvaffaqiyatli xaridda ham raqam bor: `order.order_id`.
|
|
148
|
+
|
|
149
|
+
Kutubxona xaridlarni hech qachon o'zi qayta yubormaydi. Narx, balans va `get_info` so'rovlari esa internet xatosi yoki limitda o'zi 2 martagacha qayta urinadi.
|
|
150
|
+
|
|
151
|
+
## Async (aiogram, FastAPI)
|
|
152
|
+
|
|
153
|
+
Metodlar xuddi shunday, faqat `await` bilan:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from fragment_api import AsyncFragmentAPI
|
|
157
|
+
|
|
158
|
+
api = AsyncFragmentAPI("API_KALIT")
|
|
159
|
+
order = await api.stars.buy("durov", 50)
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Bitta klientni butun dastur davomida ishlating. To'liq bot misoli: [`examples/aiogram_bot.py`](examples/aiogram_bot.py).
|
|
163
|
+
|
|
164
|
+
## Litsenziya
|
|
165
|
+
|
|
166
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
fragment_api/__init__.py,sha256=Jbb4D88XAW1xVSAv9ggr1Sm8UVMsC6NKxBZnST9HgAw,1062
|
|
2
|
+
fragment_api/_version.py,sha256=J-j-u0itpEFT6irdmWmixQqYMadNl1X91TxUmoiLHMI,22
|
|
3
|
+
fragment_api/client.py,sha256=fdFrtC8OsKXy5WJb8mO7XIGLSfqfNfA7qWDX6gSH2qg,14025
|
|
4
|
+
fragment_api/errors.py,sha256=yrifCTmnKk4WRPBV77CbXDpP3NesK5q5viIDzUWYkgY,1942
|
|
5
|
+
fragment_api/models.py,sha256=CvG-ol61cxm-Xv-bsPeRcbI0ZAP1xra_XZqUw-9DHpU,8074
|
|
6
|
+
fragment_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
fragment_api-1.0.0.dist-info/licenses/LICENSE,sha256=Q_cRJ8bbc-wXRLqdmaQGwNEEoQZpCINmA_VFN5tsiS0,1069
|
|
8
|
+
fragment_api-1.0.0.dist-info/METADATA,sha256=r843BK3Lvxpy85mWvHzCoUSfPAZc08iqeRumqkxTvy4,6348
|
|
9
|
+
fragment_api-1.0.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
fragment_api-1.0.0.dist-info/top_level.txt,sha256=TDMQZMt5L9X5nNzYsf-7jrbS6Wti1_SkTlEcdL8yrEY,13
|
|
11
|
+
fragment_api-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fragment API
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
fragment_api
|