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

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.3
File Size Uploaded Provenance Actions
pastuh_ads-1.3.3.tar.gz 108.8 kB With provenance Details for pastuh_ads-1.3.3.tar.gz

Built distribution (wheel)

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

Total release size: 170.9 kB

Release files / pastuh_ads-1.3.3.tar.gz

Download URL pastuh_ads-1.3.3.tar.gz
Size 108.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e7dedb694813acf774c79946c85ec3a69a79399b84c9840d8e10aa538313dac1
BLAKE2b-256 checksum
How to use checksums
e8141062d6c12bdf7f4632a0b76872211bfd38bf31d91e2fb1b8f0e1c84f4fab
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.3-py3-none-any.whl

Download URL pastuh_ads-1.3.3-py3-none-any.whl
Size 62.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2f942a7470e9c0221fbeccd1728d30f279b0f54e3295a9b6af79067d50639488
BLAKE2b-256 checksum
How to use checksums
f41b1d8d6477447de876ca93c7dcbd1eaf2c34916e1b4eab2bc520e009bb6191
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.3

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