refactor: rename error classes for consistency and clarity; update related code and tests

This commit is contained in:
bohd4nx
2026-03-15 22:03:32 +02:00
parent 9a090e3dbc
commit 7f269d9a87
17 changed files with 347 additions and 186 deletions
+106 -121
View File
@@ -1,19 +1,20 @@
<div align="center">
<img src="fragment.svg" alt="Fragment Logo" width="120" height="120" style="border-radius: 24px;">
<h1 style="margin-top: 24px;">💎 Fragment API by @bohd4nx</h1>
<h1 style="margin-top: 24px;">💎 Fragment API</h1>
<p style="font-size: 18px; margin-bottom: 24px;">
<b>Automate TON topups, Telegram Premium purchases, and Stars transactions via Fragment.com</b>
<b>Python library for the Fragment.com API — gift Telegram Stars, Premium, and top up TON Ads balance.</b>
</p>
[![Python](https://img.shields.io/badge/Python-3.10+-3776AB?style=flat&logo=python&logoColor=white)](https://python.org)
[![tonutils](https://img.shields.io/badge/tonutils-2.0.0-0098EA?style=flat&logo=ton&logoColor=white)](https://github.com/nessshon/tonutils)
[![PyPI version](https://img.shields.io/pypi/v/fragmentapi?style=flat&color=blue)](https://pypi.org/project/fragmentapi/)
[![PyPI downloads](https://img.shields.io/pypi/dm/fragmentapi?style=flat&color=brightgreen)](https://pypi.org/project/fragmentapi/)
[![Python](https://img.shields.io/badge/Python-3.12+-3776AB?style=flat&logo=python&logoColor=white)](https://python.org)
[![License](https://img.shields.io/github/license/bohd4nx/FragmentAPI?style=flat&color=lightgrey)](LICENSE)
[![Stars](https://img.shields.io/github/stars/bohd4nx/FragmentAPI?style=flat&color=yellow)](https://github.com/bohd4nx/FragmentAPI/stargazers)
[![Issues](https://img.shields.io/github/issues/bohd4nx/FragmentAPI?style=flat&color=red)](https://github.com/bohd4nx/FragmentAPI/issues)
[![CI](https://img.shields.io/github/actions/workflow/status/bohd4nx/FragmentAPI/tests.yml?style=flat&label=tests&logo=github)](https://github.com/bohd4nx/FragmentAPI/actions)
[Report Bug](https://github.com/bohd4nx/fragmentapi/issues) · [Request Feature](https://github.com/bohd4nx/fragmentapi/issues) · [**Donate TON**](https://app.tonkeeper.com/transfer/UQCppfw5DxWgdVHf3zkmZS8k1mt9oAUYxQLwq2fz3nhO8No5)
[Report Bug](https://github.com/bohd4nx/FragmentAPI/issues) · [Request Feature](https://github.com/bohd4nx/FragmentAPI/issues) · [**Donate TON**](https://app.tonkeeper.com/transfer/UQCppfw5DxWgdVHf3zkmZS8k1mt9oAUYxQLwq2fz3nhO8No5)
</div>
@@ -21,51 +22,94 @@
## ✨ Features
- 💰 **TON Advertisement Topups**Send TON directly to Fragment ad accounts (11,000,000,000 TON)
- 👑 **Telegram Premium Gifts**Purchase Premium subscriptions for any user (3, 6, or 12 months)
-**Telegram Stars Purchases**Buy Stars and send them to any Telegram user (501,000,000 Stars)
- 🔐 **Multi-wallet support**Configurable wallet contract version (V4R2 / V5R1)
- 💰 **TON Advertisement Topups**Top up Telegram Ads balance (11,000,000,000 TON)
- 👑 **Telegram Premium Gifts**Gift Premium to any user (3, 6, or 12 months)
-**Telegram Stars Purchases**Gift Stars to any Telegram user (501,000,000 Stars)
- 🔐 **Multi-wallet support**V4R2 and V5R1 wallet contract versions
-**Async-first** — Built on `httpx` and `asyncio`
---
## 📦 Installation
```bash
pip install fragmentapi
```
Requires **Python 3.12+**.
---
## 🚀 Quick Start
### 1. Installation
```python
import asyncio
from fragmentapi import FragmentClient
```bash
git clone https://github.com/bohd4nx/FragmentAPI.git
cd FragmentAPI
pip install -r requirements.txt
client = FragmentClient(
seed="word1 word2 ... word24",
api_key="YOUR_TONAPI_KEY",
cookies={
"stel_ssid": "...",
"stel_dt": "...",
"stel_token": "...",
"stel_ton_token": "...",
},
)
async def main():
# Gift 6 months of Telegram Premium
result = await client.gift_premium("@username", months=6)
print(result.transaction_id)
# Gift 500 Stars
result = await client.gift_stars("@username", amount=500)
print(result.transaction_id)
# Top up 10 TON to Ads balance
result = await client.topup_ton("@username", amount=10)
print(result.transaction_id)
asyncio.run(main())
```
### 2. Configuration
See the [`examples/`](examples/) folder for ready-to-run scripts.
```bash
cp .env.example .env
cp cookies.example.json cookies.json
```
---
Edit `.env`:
## 🔧 Configuration
```env
# 24-word TON wallet seed phrase
SEED = word1 word2 word3 ... word24
### `FragmentClient` parameters
# API key from @tonapibot on Telegram
API_KEY = your_tonapi_key_here
| Parameter | Type | Required | Default | Description |
| ---------------- | ------------- | -------- | -------- | -------------------------------------------------------- |
| `seed` | `str` | ✅ | — | 24-word TON wallet mnemonic phrase |
| `api_key` | `str` | ✅ | — | Tonapi key from [tonconsole.com](https://tonconsole.com) |
| `cookies` | `dict \| str` | ✅ | — | Fragment session cookies (dict or JSON string) |
| `wallet_version` | `str` | ❌ | `"V5R1"` | Wallet contract version: `"V4R2"` or `"V5R1"` |
# Wallet contract version: V4R2 or V5R1 (default: V5R1)
WALLET_VERSION = V5R1
```
### Methods
### 3. Getting Required Data
> Usernames can be passed with or without `@`.
#### 🍪 Fragment.com Cookies
| Method | Returns | Description | Limits |
| -------------------------------------------------- | ---------------- | ---------------------------------- | ------------------------- |
| `gift_premium(username, months, show_sender=True)` | `PremiumResult` | Gift Telegram Premium subscription | `months`: 3, 6, or 12 |
| `gift_stars(username, amount, show_sender=True)` | `StarsResult` | Gift Telegram Stars | `amount`: 501,000,000 |
| `topup_ton(username, amount, show_sender=True)` | `AdsTopupResult` | Top up Telegram Ads balance | `amount`: 11,000,000,000 |
**Prerequisites**: Log in to Telegram on Fragment and connect the TON wallet you'll use for payments.
---
1. Install [Cookie Editor](https://chromewebstore.google.com/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm) extension
2. Open [fragment.com](https://fragment.com) and make sure you're logged in
3. Click the Cookie Editor icon → **Export****Header String**
4. Split the result into the four fields in `cookies.json`:
## ⚙️ Getting Required Credentials
### 🍪 Fragment.com Cookies
**Prerequisites**: Log in to [fragment.com](https://fragment.com), connect your TON wallet.
1. Install [Cookie Editor](https://chromewebstore.google.com/detail/cookie-editor/hlkenndednhfkekhgcdicdfddnkalmdm)
2. Open [fragment.com](https://fragment.com) while logged in
3. Click the extension → **Export****JSON**
4. Extract these four fields:
```json
{
@@ -76,107 +120,48 @@ WALLET_VERSION = V5R1
}
```
#### 🔐 TON Wallet Seed Phrase
> ⚠️ Cookies expire. Refresh them if you start getting `FragmentPageError` or auth errors.
If you don't have a TON wallet, create one in [Tonkeeper](https://tonkeeper.com) (iOS / Android).
Go to **Settings → Backup**, copy the 24 words and paste them into `SEED` in `.env`.
> ⚠️ Never share your seed phrase with anyone. Store it offline.
#### 🔑 TON API Key
### 🔑 Tonapi Key
1. Go to [tonconsole.com](https://tonconsole.com)
2. Create an account and log in
3. Generate a new API key
4. Paste it into `API_KEY` in `.env`
2. Register and generate a new API key
3. Pass it as `api_key` to `FragmentClient`
#### 🔐 Wallet Version
### 🌱 Wallet Seed Phrase
If you don't have a TON wallet, create one in [Tonkeeper](https://tonkeeper.com).
Go to **Settings → Backup** → copy the 24 words.
> ⚠️ Never share your seed phrase. Store it offline.
### 🔐 Wallet Version
| Version | Use when |
| ------- | -------------------------------------------------------------- |
| `V5R1` | Default — Tonkeeper / MyTonWallet (wallets created after 2024) |
| `V4R2` | Older Tonkeeper wallets |
| `V4R2` | Older Tonkeeper or hardware wallets |
Not sure? Run this to check which address matches your wallet:
---
```bash
python3 -c "
import asyncio
from tonutils.clients import TonapiClient
from tonutils.contracts.wallet import WalletV4R2, WalletV5R1
from tonutils.types import NetworkGlobalID
from app.core import config
## 🗂️ Error Handling
client = TonapiClient(network=NetworkGlobalID.MAINNET, api_key=config.API_KEY)
w4, _, _, _ = WalletV4R2.from_mnemonic(client=client, mnemonic=config.SEED)
w5, _, _, _ = WalletV5R1.from_mnemonic(client=client, mnemonic=config.SEED)
print('V4R2:', w4.address.to_str(True, True))
print('V5R1:', w5.address.to_str(True, True))
"
```
### 4. Usage
#### Run Examples
```bash
python main.py
```
#### Programmatic Usage
All exceptions inherit from `FragmentError` — see [`fragmentapi/types/exceptions.py`](fragmentapi/types/exceptions.py) for the full list.
```python
import asyncio
from app.methods import topup_ton, buy_premium, buy_stars
from fragmentapi import FragmentClient, UserNotFoundError, ConfigurationError, WalletError
async def main():
# Send 10 TON to @username
result = await topup_ton("@username", 10)
print(result)
# Gift 6 months of Telegram Premium (anonymous — recipient won't see sender)
result = await buy_premium("@username", 6, show_sender=False)
print(result)
# Buy 500 Stars for @username
result = await buy_stars("@username", 500)
print(result)
asyncio.run(main())
try:
result = await client.gift_stars("@unknown", amount=100)
except UserNotFoundError:
print("User not found on Fragment")
except WalletError as e:
print(f"Wallet issue: {e}")
except ConfigurationError as e:
print(f"Bad params: {e}")
```
**Return format** (on success):
```python
{
"success": True,
"data": {
"transaction_id": "<TL-B ExternalMessage ...>",
"username": "@username",
"amount": 10, # or "months" for Premium
"timestamp": 1741234567
}
}
```
**Return format** (on failure):
```python
{
"success": False,
"error": "Telegram user '@unknown' was not found on Fragment."
}
```
### Supported Operations
| Operation | Function | Parameters | Limits |
| ------------------ | ----------------------------------------------------- | ----------------------------------- | ------------------- |
| **TON Topup** | `topup_ton(username, amount, show_sender=True)` | Username, TON amount, show sender | 11,000,000,000 TON |
| **Premium Gift** | `buy_premium(username, months, show_sender=True)` | Username, duration, show sender | 3, 6, or 12 months |
| **Stars Purchase** | `buy_stars(username, amount, show_sender=True)` | Username, Stars amount, show sender | 501,000,000 Stars |
Usernames can be passed with or without `@`.
---
<div align="center">