Unified async Python SDK for Telegram Gifts marketplaces (Tonnel, Portals, Fragment)
Project description
tg-gifts-sdk
Unified async Python SDK for Telegram Gifts marketplaces (Tonnel, Portals, Fragment).
Status (v0.1.0)
Read-only. This SDK provides a unified async surface for querying gift listings, floor stats, and account balance across Telegram Gifts marketplaces.
| Marketplace | Listings | Floor stats | Balance | Writes |
|---|---|---|---|---|
| Tonnel | ✅ | ✅ | ✅ | — (out of scope) |
| Portals | scaffolded | scaffolded | — | — |
| Fragment | scaffolded | scaffolded | — | — |
Tonnel is fully implemented and tested. Portals and Fragment are interface stubs that raise NotImplementedYetError with documented hints — contributions welcome (see CONTRIBUTING.md).
Write operations (buyGift, listGift) are deliberately out of scope to keep the public SDK conservative; downstream users can reverse-engineer the marketplace signing protocol themselves.
Install
pip install tg-gifts-sdk
Quick start
import asyncio
from tg_gifts_sdk import TonnelClient, find_deals
async def main():
auth = "user=...&hash=..." # see "Capturing auth_data" below
async with TonnelClient(auth_data=auth) as client:
listings = await client.fetch_listings(gift_name="Plush Pepe", limit=30)
stats = await client.fetch_floor_stats()
balance = await client.fetch_balance()
print(f"Balance: {balance.balance_ton} TON ({balance.memo=})")
print(f"Found {len(listings)} Plush Pepe listings")
deals = find_deals(listings, stats, min_discount=0.15)
for d in deals:
print(f" {d.listing.gift_name} #{d.listing.gift_num}: "
f"{d.listing.price} TON (fair ~{d.fair_value_ton:.1f}, "
f"{d.discount_pct*100:.1f}% discount)")
asyncio.run(main())
Capturing auth_data (Tonnel)
auth_data is the URL-encoded Telegram WebApp initData string that Tonnel uses to authenticate. To capture it:
- Open https://marketplace.tonnel.network in your browser (you must be logged in).
- Open DevTools → Console.
- Run:
localStorage.getItem("web-initData") - Copy the result. The string starts with
user=and ends with&hash=....
auth_data expires every 24-72 hours. Re-capture it when API calls start returning 401/403.
API surface
Clients
TonnelClient(auth_data: str, timeout: float = 30.0)— fully implementedfetch_listings(gift_name=, model=, backdrop=, symbol=, sort=, limit=, page=, asset="TON") -> list[Listing]fetch_floor_stats() -> list[FloorStats]fetch_balance() -> BalanceInfo
PortalsClient— stub (raisesNotImplementedYetError)FragmentClient— stub (raisesNotImplementedYetError)UnifiedClient(tonnel_auth=, portals_auth=, fragment_auth=)— aggregates across venues
Models (pydantic v2)
Listing— gift for sale (price, asset, traits, seller, raw)Gift— gift identifier with traitsFloorStats— per-collection floor + per-trait floor breakdownTrait— single trait variant (model / backdrop / symbol) with rarity + floorBalanceInfo— operator's balance + deposit memo
Scoring (the public differentiator)
score_listing(listing, floor_stats) -> FairValueQuote | None— trait-aware fair valuefind_deals(listings, floor_stats, min_discount=0.10) -> list[FairValueQuote]— filtered + sorted
The scorer takes MAX(model_premium, backdrop_premium, symbol_premium) instead of the sum — a conservative choice that minimises false positives when joint-distribution data on trait co-occurrence is unavailable. Calibrated against weeks of paper-mode trading on Tonnel.
Design choices
Read-only scope. This SDK does not implement gift purchases or sales. The marketplace signing protocol (wtf field on Tonnel) is left out deliberately — public availability of a buy/sell SDK would accelerate bot-on-bot competition. If you need writes, reverse-engineer the protocol yourself; the surface here covers everything needed for monitoring and price discovery.
curl_cffi + Firefox 133 impersonation. Tonnel's CloudFlare rules reject plain httpx/aiohttp requests via TLS fingerprinting. curl_cffi ships TLS impersonation profiles matching real browsers; Firefox 133 is the profile that currently passes Tonnel's checks. If a future migration breaks this, update the impersonate= argument in tg_gifts_sdk._http.post_json.
No retry on 4xx. A 401/403 from Tonnel almost always means expired auth_data. Retrying is wasteful and noisy; the caller should refresh auth and try again. Retry-on-5xx is configurable per-call via the timeout parameter (the underlying curl_cffi call enforces it).
Stubs over fakes. Portals and Fragment are not yet implemented. Rather than ship fake implementations that look fine on paper but fail in production, they raise NotImplementedYetError with explicit hints about what's needed. UnifiedClient silently skips unimplemented venues by default (configurable via raise_on_unimplemented=True).
Contributing
Contributions to fill in Portals and Fragment are most welcome. See CONTRIBUTING.md for setup and how to share captured cURL from marketplace API calls.
License
Apache 2.0 — see LICENSE.
Краткое описание на русском
tg-gifts-sdk — асинхронный Python SDK для маркетплейсов Telegram Gifts. v0.1.0 покрывает Tonnel полностью (читающие операции: листинги, флор-статы, баланс); Portals и Fragment — заглушки с документированными подсказками для контрибьюторов. Записывающие операции (покупка/листинг) намеренно вне scope, чтобы не разгонять bot-войны.
Установка: pip install tg-gifts-sdk
Trait-aware скорер (find_deals) — публичный differentiator: ищет листинги, недооценённые по сравнению с trait-aware fair value, а не просто по collection floor.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file tg_gifts_sdk-0.1.1.tar.gz.
File metadata
- Download URL: tg_gifts_sdk-0.1.1.tar.gz
- Upload date:
- Size: 29.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
103d13f4fb072d72a3de00a706a258d1fbed99f20492abf93d963fa0877008a5
|
|
| MD5 |
3ce708eaa1f1236726caa52bd1e8ab23
|
|
| BLAKE2b-256 |
73fc8fbb538b5a60bf27af4a845d4f9fb3e02df49fdd32a1eb2ecadc30fada0a
|
File details
Details for the file tg_gifts_sdk-0.1.1-py3-none-any.whl.
File metadata
- Download URL: tg_gifts_sdk-0.1.1-py3-none-any.whl
- Upload date:
- Size: 24.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.13
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
12ddc2830f9f3b8a3f0d54ba89b24f12e40363ab32346d675a92f67b8339ec15
|
|
| MD5 |
ac7c10a9b6e217cd475dd40202970537
|
|
| BLAKE2b-256 |
dc3a1b6a2a1cea5dada1ef3f611e99c2d9d640ad859a6660df8454285584f852
|