Skip to main content

fastsub

Официальный Python SDK FastSub — монетизация Telegram-ботов на обязательной подписке.

pip install fastsub

Быстрый старт

from fastsub import FastSub

async with FastSub(api_key="fsp_live_...") as fs:
    answer = await fs.request_op(user_id=123456789)
    for task in answer.tasks:
        print(task.title, task.link)

Ключа ещё нет? Его можно получить, не открывая бота:

async with FastSub.bootstrap(confirm_key="fsc_...", bot_token="123:ABC") as fs:
    print(fs.api_key)

Синхронный бот

from fastsub import FastSubSync

with FastSubSync(api_key="fsp_live_...") as fs:
    answer = fs.request_op(user_id=123456789)

aiogram — три строки вместо вызова в каждом хендлере

dp.message.middleware(FastSubMiddleware(fs))
dp.callback_query.middleware(FastSubMiddleware(fs))
dp.include_router(fastsub_check_router(fs))

Если что-то идёт не так

SDK намеренно не роняет вашего бота из-за наших проблем: middleware пропустит юзера дальше, telebot_gate вернёт True. Раньше это происходило молча — теперь есть логи:

logging.getLogger("fastsub").setLevel(logging.DEBUG)

Вебхуки

from fastsub import WebhookEvents, fastsub_webhook_router

events = WebhookEvents()

@events.on("resource.verified")
async def paid(event):
    await credit(event.user_id, event.publisher_payout_rub)

@events.on("resource.unsubscribed", "resource.reverted")
async def taken_back(event):
    if event.money_was_taken:          # отписался, не дожив до конца холда
        await debit(event.user_id, event.publisher_payout_rub)

app.include_router(fastsub_webhook_router(SECRET, events))

Подпись проверяется до вызова обработчика. Вручную — verify_webhook(secret, body, signature).

Обработчик получает WebhookEvent: event.money_is_mine, event.money_was_taken, event.in_hold — вместо угадывания, что значит payout_reversed. Словарём он быть не перестал, старые обработчики менять не нужно.

Повторы приёмник отсеивает сам по X-FastSub-Delivery-Id: доставка у нас «хотя бы один раз», так что без этого бонус начисляется дважды. На нескольких воркерах памяти одного процесса мало — передайте свою проверку:

def seen(delivery_id: str) -> bool:
    return bool(redis.set(f"fs:{delivery_id}", 1, nx=True, ex=86400))

fastsub_webhook_router(SECRET, events, dedupe=seen)

Не на FastAPI — есть fastsub_aiohttp_handler и, для синхронных ботов, fastsub_flask_blueprint(SECRET, on_event).

Рекламодателю

from fastsub import FastSubAdvertiser

async with FastSubAdvertiser(api_key="fsa_live_...") as adv:
    order = await adv.order(123)
    print(order["forecast"]["text"], order["retention"]["summary"])

Документация: https://fastsub.org/docs Что изменилось: CHANGELOG.md в пакете, он же — «Обновления» в нашем боте.

Metadata

Release files for fastsub 2.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastsub 2.1.1
File Size Uploaded Provenance Actions
fastsub-2.1.1.tar.gz 35.5 kB Without provenance Details for fastsub-2.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for fastsub 2.1.1
File Interpreter ABI Platform Actions
fastsub-2.1.1-py3-none-any.whl Python 3 none any Details for fastsub-2.1.1-py3-none-any.whl

Total release size: 66.2 kB

Release files / fastsub-2.1.1.tar.gz

Download URL fastsub-2.1.1.tar.gz
Size 35.5 kB
Tags Source
SHA-256 checksum
How to use checksums
a123262cc77f949da4777b1c993a4d8fa9c025b34593b5dc5e71c9a3a689a902
BLAKE2b-256 checksum
How to use checksums
0ded773201efd915fcf1f8355d2431262d0ef8edbbdbb6de6a8e24347db4f71e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / fastsub-2.1.1-py3-none-any.whl

Download URL fastsub-2.1.1-py3-none-any.whl
Size 30.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ec65bbe8898cda7e3618c42e16aa7c2bcc5e5f63051c2aee87333be79f866388
BLAKE2b-256 checksum
How to use checksums
562f72a1e4a2ef124811ae1bcbb9957674c9a1c55b0a1df37fe06b0a9dbcbc5a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for fastsub 2.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page