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,
    # SDK >= 1.3.2: background adaptive sync is ON by default — completed
    # slots disappear without "Check" or a repeated /start (one batched
    # POST /op-sessions/sync per bot). auto_sync=False restores 1.3.1.
)

# /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.2

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.2
File Size Uploaded Provenance Actions
pastuh_ads-1.3.2.tar.gz 106.8 kB With provenance Details for pastuh_ads-1.3.2.tar.gz

Built distribution (wheel)

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

Total release size: 168.2 kB

Release files / pastuh_ads-1.3.2.tar.gz

Download URL pastuh_ads-1.3.2.tar.gz
Size 106.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e47fbad7670b19260682ae3808107c2a9c1fd008345db331b699295f5ef973be
BLAKE2b-256 checksum
How to use checksums
223f1ab03842a180dd8ee3216d340f567d5d7b6efa517f79f84de9645af9bd02
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.2-py3-none-any.whl

Download URL pastuh_ads-1.3.2-py3-none-any.whl
Size 61.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
20122f72191603a9e9fc5af8430d9fd7a99f16cfd8d213266a59c06177d88b69
BLAKE2b-256 checksum
How to use checksums
9df1cd7844f2c693c0075e5f8679c05108fc821815ee0b86a4e8f79b1ce92312
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.2

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.2.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