Skip to main content

Python client for the Fragment API

Project description

Fragment API Python

Professional Python library for Fragment.com API with async and sync support. Send Telegram Stars, Premium, and TON with automatic wallet validation.

Features

  • ✅ Async & Sync interfaces
  • ✅ 3 payment methods (Stars, Premium, TON)
  • ✅ Direct TON transfers to any address
  • ✅ Recipient lookup (get user info & avatar)
  • ✅ Automatic wallet balance validation
  • ✅ WalletV4R2 support
  • ✅ Comprehensive error handling
  • ✅ Type hints & logging

Installation

pip install fragment-api-py

Quick Start

Synchronous

from FragmentAPI import SyncFragmentAPI

api = SyncFragmentAPI(
    cookies="your_cookies",
    hash_value="your_hash",
    wallet_mnemonic="your mnemonic...",
    wallet_api_key="your_api_key"
)

# Get recipient info with avatar
recipient = api.get_recipient_stars('username')
print(f"Name: {recipient.name}")
print(f"Avatar: {recipient.avatar}")

# Send stars
result = api.buy_stars('username', 100)
if result.success:
    print(f"TX: {result.transaction_hash}")

api.close()

Asynchronous

import asyncio
from FragmentAPI import AsyncFragmentAPI

async def main():
    api = AsyncFragmentAPI(
        cookies="your_cookies",
        hash_value="your_hash",
        wallet_mnemonic="your mnemonic...",
        wallet_api_key="your_api_key"
    )
    
    # Get recipient info with avatar
    recipient = await api.get_recipient_stars('username')
    print(f"Name: {recipient.name}")
    print(f"Avatar: {recipient.avatar}")
    
    # Send stars
    result = await api.buy_stars('username', 100)
    if result.success:
        print(f"TX: {result.transaction_hash}")
    
    await api.close()

asyncio.run(main())

Methods

Recipient Lookup

get_recipient_stars(username)

Get recipient info for Stars transfer

  • Returns: UserInfo with name, recipient address, avatar (URL or base64)

get_recipient_premium(username)

Get recipient info for Premium gift

  • Returns: UserInfo with name, recipient address, avatar

get_recipient_ton(username)

Get recipient info for Ads account top-up

  • Returns: UserInfo with name, recipient address, avatar

Payments

buy_stars(username, quantity)

Send Telegram Stars to user

  • username (str): Target username
  • quantity (int): Number of stars (1-999999)

gift_premium(username, months)

Gift Premium subscription (3, 6, or 12 months)

  • username (str): Target username
  • months (int): Duration in months

topup_ton(username, amount)

Top up Telegram Ads account with TON

  • username (str): Target username
  • amount (int): Amount of TON (1-999999)

transfer_ton(to_address, amount, memo=None)

Direct TON transfer to any address or username

  • to_address (str): Destination address (TON address or username like user.t.me)
  • amount (float): Amount of TON to send
  • memo (str, optional): Comment/memo for the transaction
  • Returns: TransferResult with success status, transaction_hash, memo, and error (if any)

Wallet

get_wallet_balance()

Get current wallet balance and address

  • Returns: Dictionary with balance in TON/nanotons and address

Recipient Info

# Get user info before sending payment
user = api.get_recipient_stars('john_doe')

if user.found:
    print(f"Name: {user.name}")
    print(f"Address: {user.recipient}")
    print(f"Avatar: {user.avatar}")  # URL or base64 encoded image

UserInfo object:

  • name - User's display name
  • recipient - Blockchain address
  • found - Boolean flag
  • avatar - Avatar URL (HTTP/HTTPS) or base64 encoded image

Direct TON Transfer

Send TON directly to any address or Telegram username:

Asynchronous

import asyncio
from FragmentAPI import AsyncFragmentAPI

async def main():
    api = AsyncFragmentAPI(
        cookies="your_cookies",
        hash_value="your_hash",
        wallet_mnemonic="your mnemonic...",
        wallet_api_key="your_api_key"
    )
    
    # Check balance first
    balance = await api.get_wallet_balance()
    print(f"Balance: {balance['balance_ton']} TON")
    print(f"Address: {balance['address']}")
    
    # Transfer to username (t.me format)
    result = await api.transfer_ton("username.t.me", 0.5, "Payment for services")
    
    # Or transfer to TON address
    # result = await api.transfer_ton("EQDrjaLahLkMB-hMCmkzOyBuHJ139ZUYmPHu6RRBKnbRELWt", 0.5)
    
    if result.success:
        print(f"Success! Hash: {result.transaction_hash}")
        print(f"Memo: {result.memo}")
    else:
        print(f"Error: {result.error}")
    
    await api.close()

asyncio.run(main())

Synchronous

from FragmentAPI import SyncFragmentAPI

api = SyncFragmentAPI(
    cookies="your_cookies",
    hash_value="your_hash",
    wallet_mnemonic="your mnemonic...",
    wallet_api_key="your_api_key"
)

# Check balance
balance = api.get_wallet_balance()
print(f"Balance: {balance['balance_ton']} TON")
print(f"Address: {balance['address']}")

# Transfer with memo
result = api.transfer_ton("username.t.me", 0.01, "test payment")

if result.success:
    print(f"Success! Hash: {result.transaction_hash}")
    print(f"Memo: {result.memo}")
else:
    print(f"Error: {result.error}")

api.close()

TransferResult Object

The transfer_ton method returns a TransferResult object:

Attribute Type Description
success bool Whether the transfer was successful
transaction_hash str | None Transaction hash on success
memo str | None The memo/comment included in transaction
error str | None Error message if transfer failed

Setup

1. Get Fragment Cookies

  1. Open fragment.com in browser
  2. Press F12 → Application → Cookies
  3. Copy cookies: stel_ssid, stel_token, stel_dt, stel_ton_token
  4. Combine: stel_ssid=value; stel_token=value; ...

2. Get Hash Value

From DevTools Network tab → fragment.com/api requests → copy hash parameter

3. Setup TON Wallet

  1. Get 24-word seed phrase from TON wallet (Tonkeeper, MyTonWallet, etc)
  2. Fund wallet with TON for transactions

4. Get API Key

  1. Go to https://tonconsole.com
  2. Create project
  3. Generate API key from Settings

Exceptions

  • AuthenticationError - Invalid cookies/hash
  • UserNotFoundError - User doesn't exist
  • InvalidAmountError - Invalid quantity/amount
  • InsufficientBalanceError - Low wallet balance
  • TransactionError - TX execution failed
  • NetworkError - Network request failed
  • WalletError - Wallet operation failed
  • PaymentInitiationError - Fragment API error

Error Handling

from FragmentAPI import InsufficientBalanceError, UserNotFoundError, WalletError

try:
    # Get recipient info
    user = api.get_recipient_stars('username')
    
    # Send payment
    result = api.buy_stars('username', 100)
    if not result.success:
        print(f"Error: {result.error}")
        
    # Direct transfer
    transfer = api.transfer_ton('address.t.me', 1.0, 'memo')
    if not transfer.success:
        print(f"Transfer error: {transfer.error}")
        
except InsufficientBalanceError as e:
    print(f"Low balance: {e}")
except UserNotFoundError as e:
    print(f"User not found: {e}")
except WalletError as e:
    print(f"Wallet error: {e}")
finally:
    api.close()

Security

Store credentials in environment variables:

import os

api = SyncFragmentAPI(
    cookies=os.getenv('FRAGMENT_COOKIES'),
    hash_value=os.getenv('FRAGMENT_HASH'),
    wallet_mnemonic=os.getenv('WALLET_MNEMONIC'),
    wallet_api_key=os.getenv('WALLET_API_KEY')
)

Requirements

  • Python 3.7+
  • requests >= 2.28.0
  • aiohttp >= 3.8.0
  • tonutils >= 0.3.0
  • pytoniq-core >= 0.1.0

Documentation

Full documentation: https://github.com/S1qwy/fragment-api-py

License

MIT License

Support

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

fragment_api_py-3.1.0.tar.gz (13.9 kB view details)

Uploaded Source

Built Distribution

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

fragment_api_py-3.1.0-py3-none-any.whl (16.7 kB view details)

Uploaded Python 3

File details

Details for the file fragment_api_py-3.1.0.tar.gz.

File metadata

  • Download URL: fragment_api_py-3.1.0.tar.gz
  • Upload date:
  • Size: 13.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.12

File hashes

Hashes for fragment_api_py-3.1.0.tar.gz
Algorithm Hash digest
SHA256 285c2fd552bfc20924b67d5677a3e983df8df239aab2fb17818682ed98ee58fd
MD5 42fdc0e58875c3e1a877fa87ef78c557
BLAKE2b-256 e5b7fbabf24d8289a6b558fac4e052d939d2a7fd931f50e27e7d5da39ccea062

See more details on using hashes here.

File details

Details for the file fragment_api_py-3.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fragment_api_py-3.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 70056be10a9b883d9b7d78d6f2c7b8362c78a5dd29a0ff80ddfb999e72feea51
MD5 a6ba2a079a0859dc320df01dcc20dc9b
BLAKE2b-256 74f4f1b29823681d03ea025d9636720f327da9d135e75f80179d4433dec13a5e

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