Metadata-Version: 2.4
Name: apifragment
Version: 1.1.1
Summary: Python SDK for the Fragment API: buy Telegram Stars, gift Telegram Premium and top up Telegram Ads (TON Ads)
Author: ApiFragment
License-Expression: MIT
Project-URL: Homepage, https://apifragment.online
Project-URL: Documentation, https://apifragment.online/en/docs
Project-URL: Repository, https://github.com/newaurumcoder/apifragment-python
Project-URL: Changelog, https://github.com/newaurumcoder/apifragment-python/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/newaurumcoder/apifragment-python/issues
Keywords: telegram,telegram-stars,telegram-premium,telegram-ads,fragment,fragment-api,stars,premium,ton,usdt,api,sdk,asyncio
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Framework :: AsyncIO
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.23
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Dynamic: license-file

# apifragment — Python SDK for the Fragment API

[![PyPI](https://img.shields.io/pypi/v/apifragment)](https://pypi.org/project/apifragment/)
[![Python](https://img.shields.io/pypi/pyversions/apifragment)](https://pypi.org/project/apifragment/)
[![Tests](https://github.com/newaurumcoder/apifragment-python/actions/workflows/tests.yml/badge.svg)](https://github.com/newaurumcoder/apifragment-python/actions/workflows/tests.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/newaurumcoder/apifragment-python/blob/main/LICENSE)

English | [Русский](https://github.com/newaurumcoder/apifragment-python/blob/main/README.ru.md)

Official Python client for [ApiFragment](https://apifragment.online): buy Telegram Stars, gift Telegram Premium and top up Telegram Ads (TON Ads) through Fragment. Sync and asyncio, typed responses, one exception class per server error code, safe retries that never buy twice.

```bash
pip install apifragment
```

Python 3.8+, one dependency (`httpx`). Get your token from [@apiregisterbot](https://t.me/apiregisterbot).

## Quick start

```python
from apifragment import ApiFragment, TaskFailedError, PaymentOutcomeUnknownError

api = ApiFragment("YOUR_TOKEN")

# KYC mode: link your Fragment account once
api.login("word1 word2 ... word24", wallet_version="v4r2")

order = api.stars("durov", 100, idempotency_key="order-42")   # queued, not delivered yet
try:
    task = api.wait(order.task_id)                            # polls until completed / failed
    print("delivered")
except PaymentOutcomeUnknownError as e:
    print("money may have moved, do NOT re-order:", e.code, e.hint)
except TaskFailedError as e:
    print(e.code, e.message, e.hint, "retry is safe:", e.retryable)
```

Other products:

```python
api.premium("durov", months=3)                        # 3, 6 or 12
api.ads("mychannel", amount_ton=10)                   # Telegram Ads top-up, not a TON transfer
api.stars("durov", 500, payment_method="usdt_ton")    # pay in USDT on TON (KYC Stars / Premium)
api.stars("durov", 100, hide=False)                   # show your Fragment account as the sender
```

NoKYC mode (no Fragment account):

```python
api.nokyc_stars("durov", 100, "word1 ... word24")      # your wallet pays per order
api.nokyc_premium("durov", 3, from_balance=True)       # pay from the cabinet balance, no seed
api.nokyc_stars("durov", 100, "word1 ... word24", hide=False, payment_method="usdt_ton")
```

`payment_method="usdt_ton"` in NoKYC works only while the service has NoKYC USDT enabled; otherwise the order is refused with code `306` before anything is charged. Telegram Ads top-ups (`ads`, `nokyc_ads`) are paid in TON only.

Async — the same methods, awaitable:

```python
from apifragment import AsyncApiFragment

async with AsyncApiFragment("YOUR_TOKEN") as api:
    order = await api.stars("durov", 100)
    task = await api.wait(order.task_id)
```

Many orders at once (`GET /tasks`, 100 ids per request):

```python
results = api.wait_many([o.task_id for o in orders])  # {task_id: Task}, never raises on failures
# wait()/wait_many() ride out network errors, 429 and 5xx while polling; wait_many(on_status=...) reports changes
```

## Money safety, built in

- **Every order has an `idempotency_key`.** If you don't pass one, the SDK generates it. On a network error, `429` or a retryable `5xx` the SDK re-sends the order with the **same** key, and the server deduplicates it: a retry can never buy twice. Pass your own order id as the key so that your own retries are safe too.
- **Double-click window.** Besides the key, the server treats a second order with the same recipient, product, amount and payment method as a duplicate, even with a different key, when it comes within 15 seconds (default) while the first one is still in progress. Such an order comes back with `order.is_duplicate == True` and the `task_id` of the first one: nothing new is bought. To send two identical orders to one recipient on purpose, wait until the first one finishes or space them more than 15 seconds apart.
- **`wait()` never re-orders.** A task in `paycheck` is being verified on-chain and can take tens of minutes. When `wait()` times out it raises `TaskTimeoutError`; the order is still running.
- **`PaymentOutcomeUnknownError`** marks the codes where the transaction may already be on-chain (`TX_VERIFY_PENDING`, `NOKYC_REFUND_REQUIRED`, …). Never place such an order again blindly.
- **Local checks before sending.** Username format, Stars 50–1,000,000, months 3/6/12, whole TON 1–10,000, a 12/24-word seed, and so on. A bad value raises `InvalidRequestError` and nothing is sent: your seed never travels for nothing.
- **No sandbox.** Every order spends real funds on mainnet.

## Errors

```
ApiFragmentError
├── InvalidRequestError       rejected locally, nothing was sent (also a ValueError)
├── TransportError            no response (network, TLS) ─ RequestTimeoutError
├── TaskTimeoutError          wait() gave up, the task is still running (also a TimeoutError)
└── APIError                  .code .message .hint .retryable .retry_after .status_code .detail
    ├── BadRequestError 400   PaymentRequiredError 402   ForbiddenError 403 ─ AuthenticationError
    ├── NotFoundError 404     ConflictError 409          ValidationError 422
    ├── TooManyRequestsError 429                         ServerError 5xx
    └── one class per server code, e.g. LowBalanceError (402), UserNotFoundError (404),
        AlreadyPremiumError (777), QuoteGuardError (312), CookiesExpiredError (101), QueueFullError…
```

A failed task raises the class of its code mixed with `TaskFailedError`, so `except LowBalanceError` and `except TaskFailedError` both work, and `e.task` holds the full task. The classes are generated from the server's own error catalogue, so they always match [the error table](https://apifragment.online/docs/errors). Look a code up with `apifragment.CODE_TO_CLASS["402"]`.

## Webhooks

```python
from apifragment import parse_webhook, WebhookVerificationError

secret = api.get_webhook().webhook_secret

# in your handler (raw bytes, before any JSON parsing):
try:
    event = parse_webhook(request.body, request.headers, secret)
except WebhookVerificationError:
    return 401
if event.is_task:
    print(event.task.task_id, event.task.status)
```

There is one final event per task. Deliveries are retried, so deduplicate by `event.delivery_id`. Reply `2xx` within 10 seconds. Polling stays the primary channel. Ready handlers: [Flask](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/webhook_flask.py), [FastAPI](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/webhook_fastapi.py).

## Examples

Runnable scripts live in [examples/](https://github.com/newaurumcoder/apifragment-python/tree/main/examples); each one is covered by a test.

| Example | What it shows |
|---|---|
| [buy_stars.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/buy_stars.py) | Buy Telegram Stars, wait for delivery, handle every outcome |
| [premium_gift.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/premium_gift.py) | Gift Telegram Premium for 3, 6 or 12 months |
| [nokyc_stars.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/nokyc_stars.py) | NoKYC mode: your wallet pays per order |
| [async_bulk.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/async_bulk.py) | Asyncio: many orders, one polling loop |
| [price_and_balance.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/price_and_balance.py) | Wallet balance and a price quote |
| [history_export.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/history_export.py) | Order history to CSV, totals for 30 days |
| [telegram_bot_aiogram.py](https://github.com/newaurumcoder/apifragment-python/blob/main/examples/telegram_bot_aiogram.py) | aiogram 3 bot that sells Stars |

## Configuration

```python
ApiFragment(token, base_url="https://apifragment.online", timeout=30, max_retries=3,
            max_retry_wait=30, language="en", http_client=None)
```

`max_retry_wait` is the longest pause the SDK sleeps through on its own. A longer `retry_after` (for example `QUEUE_FULL`, 30 s) is raised to you instead. `language="ru"` gives Russian messages and hints.

## Methods

| Method | Endpoint |
|---|---|
| `login(wallet_seed, wallet_version)` | `POST /cookies/login` |
| `stars`, `premium`, `ads` → `Order` | `POST /stars`, `/premium`, `/ton` |
| `nokyc_stars`, `nokyc_premium`, `nokyc_ads` → `Order` | `POST /nokyc/...` |
| `task(id)` → `Task`, `tasks(ids)`, `wait(id)`, `wait_many(ids)` | `GET /task/{id}`, `/tasks` |
| `receipt(id)` → PNG bytes or `None` | `GET /task/{id}/receipt` |
| `balance()` → `Balance`, `price(product, quantity)` → `Price` | `GET /balance`, `/price` |
| `resolve_user(username)` | `GET /resolve_user/{username}` |
| `history(...)` → `[HistoryItem]`, `iter_history()` (all pages via `before`), `stats(days)` → `Stats` | `GET /history`, `/stats` |
| `get_webhook()` → `Webhook`, `set_webhook(url)`, `test_webhook(url)` | `/webhook`, `/webhook/test` |

Every model keeps the full JSON in `.raw` and also supports `obj["field"]`.

The SDK is a thin HTTP wrapper: all purchasing logic runs on the ApiFragment server.

## Versions

The SDK follows semantic versioning: a minor release adds methods or fields, a major release may change existing ones. Every release is listed in the [changelog](https://github.com/newaurumcoder/apifragment-python/blob/main/CHANGELOG.md). Check the installed version with `apifragment.__version__`.

## Links

- API reference: [apifragment.online/docs](https://apifragment.online/en/docs)
- Error codes: [apifragment.online/docs/errors](https://apifragment.online/en/docs/errors)
- Webhooks and order statuses: [apifragment.online/docs/webhooks](https://apifragment.online/en/docs/webhooks)
- Pricing: [apifragment.online/pricing](https://apifragment.online/en/pricing)
- News: [@Apifragment](https://t.me/Apifragment)

## Development

```bash
pip install -e ".[dev]"
pytest tests
```

`apifragment/_codes.py` is generated from the server's error catalogue. Do not edit it by hand.
