Skip to main content

Async Python library for Fragment.com API - Purchase Telegram Stars, Premium, and TON topups

Project description

afragment

Async Python library for the Fragment.com API. Purchase Telegram Stars, Premium subscriptions, and TON balance topups programmatically.

Installation

pip install afragment

Or install from source:

pip install -e .

Authentication

You need two credentials from Fragment.com:

  • FRAGMENT_HASH - Session hash (from URL parameter)
  • FRAGMENT_COOKIE - Session cookie (from browser)

Quick Start

Purchasing Telegram Stars

import asyncio
from afragment import AsyncFragmentClient

# Wallet configuration (only address required, chain defaults to "-239")
WALLET_ACCOUNT = {
    "address": "your_wallet_address",
}

async def buy_stars():
    async with AsyncFragmentClient(
        fragment_hash="your_hash",
        fragment_cookie="your_cookie"
    ) as client:
        # Step 1: Search for recipient
        search = await client.search_stars_recipient("username", quantity=100)
        recipient = search["found"]["recipient"]
        print(f"Found: {search['found']['name']}")

        # Step 2: Initialize purchase (minimum 50 stars)
        init = await client.init_buy_stars_request(recipient, quantity=100)
        req_id = init["req_id"]
        print(f"Price: {init['amount']} TON")

        # Step 3: Get transaction details (device info is optional)
        tx = await client.get_buy_stars_link(req_id, WALLET_ACCOUNT)
        print(f"Send to: {tx['transaction']['messages'][0]['address']}")
        print(f"Amount: {tx['transaction']['messages'][0]['amount']} nanoTON")

asyncio.run(buy_stars())

Gifting Telegram Premium

async def gift_premium():
    async with AsyncFragmentClient(
        fragment_hash="your_hash",
        fragment_cookie="your_cookie"
    ) as client:
        # Step 1: Search for recipient
        search = await client.search_premium_gift_recipient("username")
        recipient = search["found"]["recipient"]

        # Step 2: Initialize purchase (3, 6, or 12 months)
        init = await client.init_gift_premium_request(recipient, months=3)
        req_id = init["req_id"]

        # Step 3: Get transaction details
        tx = await client.get_gift_premium_link(req_id, WALLET_ACCOUNT)

TON Balance Topup

async def topup_ton():
    async with AsyncFragmentClient(
        fragment_hash="your_hash",
        fragment_cookie="your_cookie"
    ) as client:
        # Step 1: Search for recipient
        search = await client.search_ads_topup_recipient("username")
        recipient = search["found"]["recipient"]

        # Step 2: Initialize topup (minimum 1 TON, whole numbers only)
        init = await client.init_ads_topup_request(recipient, amount=100)
        req_id = init["req_id"]

        # Step 3: Get transaction details
        tx = await client.get_ads_topup_link(req_id, WALLET_ACCOUNT)

Validation Rules

The library validates input before making API requests:

Method Parameter Validation
search_stars_recipient quantity Minimum 50
init_buy_stars_request quantity Minimum 50
init_gift_premium_request months Must be 3, 6, or 12
init_ads_topup_request amount Minimum 1, whole numbers only

Utility Functions

Payload Decoding

from afragment import decode_payload, extract_ref_id, format_transaction_comment

# Decode base64 payload from transaction
payload = tx["transaction"]["messages"][0]["payload"]
decoded = decode_payload(payload)

# Extract reference ID
ref_id = extract_ref_id(payload)
print(f"Reference: {ref_id}")

# Format transaction comments
comment = format_transaction_comment("stars", quantity=100, ref_id=ref_id)
# Output: "100 Telegram Stars\n\nRef#abc123"

comment = format_transaction_comment("premium", months=3, ref_id=ref_id)
# Output: "Telegram Premium for 3 months\n\nRef#abc123"

comment = format_transaction_comment("topup", ref_id=ref_id)
# Output: "Telegram account top up\n\nRef#abc123"

Amount Conversion

from afragment import nano_to_ton, ton_to_nano

# Convert between TON and nanoTON
ton = nano_to_ton(1500000000)  # 1.5 TON
nano = ton_to_nano(1.5)        # 1500000000 nanoTON

Error Handling

from afragment import (
    AsyncFragmentClient,
    FragmentAPIError,
    AuthenticationError,
    PriceChangedError,
    InvalidRecipientError,
)

async def safe_purchase():
    async with AsyncFragmentClient(
        fragment_hash="your_hash",
        fragment_cookie="your_cookie"
    ) as client:
        try:
            # Validation error if quantity < 50
            search = await client.search_stars_recipient("username", 100)
        except ValueError as e:
            print(f"Validation error: {e}")
            return
        except InvalidRecipientError:
            print("User not found!")
            return

        # Retry on price change
        for attempt in range(3):
            try:
                init = await client.init_buy_stars_request(
                    search["found"]["recipient"], 100
                )
                break
            except PriceChangedError:
                print(f"Price changed, retrying... ({attempt + 1}/3)")
                await asyncio.sleep(1)
        else:
            print("Failed after 3 attempts")
            return

        try:
            tx = await client.get_buy_stars_link(init["req_id"], WALLET_ACCOUNT)
        except AuthenticationError:
            print("Session expired, please refresh credentials")
            return

API Reference

Client Methods

Method Description Validation
search_stars_recipient(query, quantity) Find user for Stars purchase quantity >= 50
init_buy_stars_request(recipient, quantity) Initialize Stars purchase quantity >= 50
get_buy_stars_link(id, account, [device]) Get Stars transaction details account required, device optional
search_premium_gift_recipient(query) Find user for Premium gift -
init_gift_premium_request(recipient, months) Initialize Premium purchase months in (3, 6, 12)
get_gift_premium_link(id, account, [device]) Get Premium transaction details account required, device optional
search_ads_topup_recipient(query) Find user for TON topup -
init_ads_topup_request(recipient, amount) Initialize TON topup amount >= 1, int only
get_ads_topup_link(id, account, [device]) Get TON topup transaction details account required, device optional

Exceptions

Exception Description
FragmentAPIError Base exception for all API errors
AuthenticationError Invalid or expired credentials
PriceChangedError Price changed during request (retry recommended)
InvalidRecipientError User not found or not eligible
ValueError Invalid input (validation failed)

Wallet Account Format

{
    "address": "UQ...",  # Your TON wallet address (required)
    # "chain": "-239",   # Optional, defaults to "-239" (TON mainnet)
}

Device Info Format (Optional)

Device info is optional. The library uses Tonkeeper defaults:

{
    "platform": "android",
    "appName": "Tonkeeper",
    "appVersion": "5.0.18",
    "maxProtocolVersion": 2,
    "features": ["SendTransaction", {"name": "SendTransaction", "maxMessages": 4}]
}

You can pass custom device info if needed:

tx = await client.get_buy_stars_link(req_id, WALLET_ACCOUNT, custom_device_info)

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

afragment-0.1.0.tar.gz (12.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

afragment-0.1.0-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

Details for the file afragment-0.1.0.tar.gz.

File metadata

  • Download URL: afragment-0.1.0.tar.gz
  • Upload date:
  • Size: 12.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.1

File hashes

Hashes for afragment-0.1.0.tar.gz
Algorithm Hash digest
SHA256 33e28392198449c432285dcc9a702fc993a7733ee34e058bd2c07bf8ea2188a7
MD5 a86e54f1d2b46d0c7b511526e4c7a905
BLAKE2b-256 942bed35a2f91d328d0ad47fcc665a6b73df68200e95880aec9e3f844ac6329a

See more details on using hashes here.

File details

Details for the file afragment-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: afragment-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.1

File hashes

Hashes for afragment-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c73b11eb9170414f9efc6f6c30e2f294bc8d42fabc491a8b321a2937115f3e0c
MD5 0dc5f3ba727d11e8452eaf95ce5ccc71
BLAKE2b-256 1e4c879c065f7af6df104c90624916d87db92451d778c789cb0b6e66c810a39c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page