Skip to main content

Pastuh Ads — Python SDK

Асинхронный Python SDK для Pastuh Ads Partner API v1: выдача OP-заданий (обязательных подписок), интерактивный OP-блок в Telegram, клики, подтверждения /start, Premium-наблюдения.

Полная документация: README_RU.md · CHANGELOG · docs/

Установка

pip install pastuh-ads
# с примерами для aiogram 3.x:
pip install "pastuh-ads[aiogram]"

Python ≥ 3.10. Единственная обязательная зависимость — httpx.

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

1. Получите API-ключ

Ключ выдаётся в кабинете Pastuh Ads для вашего источника трафика (формат opk_…). Нужны также числовые SOURCE_ID и PLACEMENT_ID.

export PASTUH_ADS_API_KEY=opk_...
export PASTUH_ADS_SOURCE_ID=50
export PASTUH_ADS_PLACEMENT_ID=1

2. Получение заданий (op-list)

from pastuh_ads import PastuhAdsClient

ads = PastuhAdsClient(
    base_url="https://pastuhads.com/api/partner/v1",
    api_key=os.environ["PASTUH_ADS_API_KEY"],
    source_id=int(os.environ["PASTUH_ADS_SOURCE_ID"]),
    placement_id=int(os.environ["PASTUH_ADS_PLACEMENT_ID"]),
)

op = await ads.get_op_list(telegram_user_id, user=message.from_user)
# op.op_session_id, op.tasks[], op.access_allowed, op.expires_at

3. Отметка показа — mark_shown

После фактического отображения блока пользователю:

await ads.mark_shown(op.op_session_id)

4. Интерактивный OP-блок (одно сообщение)

InteractiveOpBlock реализует эталонную механику: одно OP-сообщение, клавиатура сокращается по мере выполнения, временный TTL-слот для tokenless-бота, reopen-CTA без повторной оплаты.

from pastuh_ads import InteractiveOpBlock

block = InteractiveOpBlock(
    ads,
    send_message=tg_send,        # async (chat_id, text, rows) -> message_id
    edit_markup=tg_edit_markup,  # async (chat_id, message_id, rows)
    edit_text=tg_edit_text,      # async (chat_id, message_id, text, rows)
    delete_message=tg_delete,    # async (chat_id, message_id)
    slot_ttl_seconds=15.0,
)

# /start → одно сообщение со всеми заданиями
await block.open(telegram_user_id=uid, chat_id=cid, user=message.from_user)

# callback_query → роутинг paop:*
handled = await block.handle_callback(
    telegram_user_id=callback.from_user.id,
    chat_id=callback.message.chat.id,
    data=callback.data,
    answer=callback.answer,
)

Callback-data бота:

data Действие
paop:open:{task_id} Оплачиваемый клик → серверная фиксация → TTL-слот
paop:reopen:{task_id} Повторное открытие оплаченного слота (без API)
paop:check legacy-клавиатуры SDK <1.3 → POST /check (в новой кнопки нет — проверка event-driven: throttled /check на событиях пользователя + bounded fallback)

Готовый пример: examples/aiogram3_interactive_op.py. Без aiogram/SDK — голый aiohttp: examples/aiohttp_interactive_op.py.

5. Подтверждение действий

Задания subscription_confirmed / join_request_submitted / bot_start_confirmed подтверждаются серверными событиями платформы — переход по ссылке сам по себе ничего не завершает. Кнопка задания исчезает из OP-блока только после подтверждения (через /check или GET /status).

Оплачиваемый клик (bot_tracked_click) фиксируется один раз через POST /tasks/{id}/callback-click — идемпотентно (charged).

6. Ошибки

from pastuh_ads import PastuhAdsError

try:
    await ads.get_op_list(uid)
except PastuhAdsError as exc:
    exc.status_code  # HTTP-статус API
    exc.error_code   # машинный код ошибки (session_expired, …)
    exc.message      # человекочитаемое описание

InteractiveOpBlock не пробрасывает Telegram-исключения наружу: временные сбои — ограниченный backoff + ленивое восстановление, on_error-hook для метрик.

7. Пережитие рестарта

saved = block.dump_state()      # → в Redis/файл
block.restore_state(saved)      # при старте процесса
await block.resume()            # перечитать status, пересобрать клавиатуры

Обновление

pip install -U pastuh-ads

Миграции между версиями: docs/MIGRATION_SDK_1.2.0_RU.md. __version__ — pastuh_ads.__version__; запросы подписаны User-Agent: pastuh-ads/<version>.

Разработка

pip install -e ".[dev]"
pytest
python -m build

Лицензия

Proprietary — условия согласовываются с правообладателем до публикации отдельной лицензии.

Metadata

Release files for pastuh-ads 1.3.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 pastuh-ads 1.3.1
File Size Uploaded Provenance Actions
pastuh_ads-1.3.1.tar.gz 94.5 kB With provenance Details for pastuh_ads-1.3.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pastuh-ads 1.3.1
File Interpreter ABI Platform Actions
pastuh_ads-1.3.1-py3-none-any.whl Python 3 none any Details for pastuh_ads-1.3.1-py3-none-any.whl

Total release size: 150.8 kB

Release files / pastuh_ads-1.3.1.tar.gz

Download URL pastuh_ads-1.3.1.tar.gz
Size 94.5 kB
Tags Source
SHA-256 checksum
How to use checksums
1d24d652dd593ec3a7cfa0d38ac209fc4c85b365ff55a4e628110f5ed15af0c9
BLAKE2b-256 checksum
How to use checksums
ef61b3140957434e22ae856fef22b0b244a1e9326ec05fc43035412b2d7ee7c9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Release files / pastuh_ads-1.3.1-py3-none-any.whl

Download URL pastuh_ads-1.3.1-py3-none-any.whl
Size 56.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8cd8bc644726db1f016b1c4c01f8328cfc9e49ef8f706fd6d233feb9bafc93f9
BLAKE2b-256 checksum
How to use checksums
94e8833925114db7670af286f76f352fe13e95d2d34502d7f10a735c79ae7c98
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

Security for pastuh-ads 1.3.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pastuh_ads-1.3.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 25, 2026.

Transparency log

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