refactor: update README configuration parameters and add error handling section refactor: streamline tonapi imports and add WalletVersion to __all__ chore: update project metadata in pyproject.toml
Fragment API
Async Python client for the Fragment API. Buy Stars and Premium, top up TON and Ads balances, run giveaways, manage anonymous numbers, and search Fragment listings.
Disclaimer: This project is not affiliated with, endorsed by, or in any way officially connected with Fragment or Telegram.
Installation
pip install pyfragment
To install the latest unreleased changes from the dev branch:
pip install git+https://github.com/bohd4nx/pyfragment.git@dev
Requires Python 3.10+.
Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
seed |
str |
— | 12-, 18-, or 24-word TON wallet mnemonic |
api_key |
str |
— | Tonapi key from tonconsole.com |
cookies |
dict | str |
— | Fragment session cookies |
wallet_version |
str |
"V5R1" |
"V4R2" or "V5R1" (also accepts WalletVersion literal) |
timeout |
float |
30.0 |
HTTP request timeout in seconds |
Logging
pyfragment uses standard Python logging under the pyfragment namespace and is silent by default.
To enable logs, configure your app's logging and set the level:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("pyfragment").setLevel(logging.DEBUG) # DEBUG for detailed request logs
Credentials
Fragment cookies — log in to fragment.com and connect your TON wallet. You can get cookies in two ways:
-
Automatically (recommended) — install the optional browser extra and use
get_cookies_from_browser(), which reads them directly from your browser's on-disk store. No extension needed:pip install "pyfragment[browser]"from pyfragment import get_cookies_from_browser result = get_cookies_from_browser("chrome") # or "firefox", "edge", "brave", ... # result.cookies — dict[str, str] to pass to FragmentClient # result.expires — ISO 8601 expiry of stel_ssid, or None for session cookies -
Manually — install Cookie Editor and export these four keys:
stel_ssid,stel_dt,stel_token,stel_ton_token. Pass them as adictor JSON string.
Refresh when you get authentication errors.
Tonapi key — generate at tonconsole.com.
Seed phrase — 24-word mnemonic from your TON wallet (Tonkeeper → Settings → Backup). Never share it.
Usage
import asyncio
from pyfragment import FragmentClient
async def main() -> None:
async with FragmentClient(
seed="word1 word2 ... word24",
api_key="YOUR_TONAPI_KEY",
cookies={
"stel_ssid": "...",
"stel_dt": "...",
"stel_token": "...",
"stel_ton_token": "...",
},
) as client:
wallet = await client.get_wallet()
print(f"Wallet: {wallet.address} | TON: {wallet.ton_balance} | USDT: {wallet.usdt_balance}")
recipient = "https://t.me/username" # also supports: @username, username
stars = await client.purchase_stars(recipient, amount=500, payment_method="usdt_ton")
print(f"Stars sent: {stars.amount} to {stars.username} | tx: {stars.transaction_id}")
premium = await client.purchase_premium(recipient, months=6, payment_method="ton")
print(f"Premium sent: {premium.amount} months to {premium.username} | tx: {premium.transaction_id}")
asyncio.run(main())
Full runnable examples:
Error Handling
All exceptions inherit from FragmentError. Catch specific ones or the base class:
from pyfragment import (
ConfigurationError, # invalid arguments (amount, months, payment_method, etc.)
UserNotFoundError, # recipient not found on Fragment
WalletError, # insufficient TON/USDT balance
TransactionError, # broadcast failed, duplicate seqno, invalid payload
FragmentAPIError, # Fragment API returned an error response
FragmentPageError, # page fetch or hash extraction failed
AnonymousNumberError, # number not owned, wrong state, login code issues
CookieError, # missing or malformed session cookies
ParseError, # failed to decode Fragment payload
VerificationError, # on-chain verification step failed
OperationError, # generic operation-level failure
UnexpectedError, # unexpected API response structure
)
Payload debug/decode helper (thanks):
Changelog
See CHANGELOG.md for release history.
Made with ❤️ by @bohd4nx
Star ⭐ this repo if you found it useful!