Skip to main content

BOTIX SDK для Python

Официальная клиентская библиотека для публичного API BOTIX — платформы визуального конструктора чат-ботов и AI-ассистентов.

PyPI version Python versions License: MIT CI

Что это

BOTIX — облачная SaaS-платформа визуального конструктора чат-ботов: Telegram, WhatsApp, ВКонтакте, виджет на сайте. SDK даёт типизированный доступ к публичному REST API BOTIX из Python-приложений: контакты, сообщения, сценарии, чаты, webhooks.

Установка

pip install botix

Минимальная версия Python — 3.9.

Первый запрос

Получите API-ключ в кабинете BOTIX: «Настройки → API-ключи → Создать ключ». Ключ показывается один раз — сохраните его.

import botix

client = botix.Client("btx_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

me = client.me()
print(me.data.project_id, me.data.scopes, me.data.plan_key)

Возвращается контекст текущего ключа: ID проекта, разрешённые scopes, тариф клиента и остаток rate-limit.

Отправка сообщения

response = client.messages.send(
    contact_id=42,
    content="Привет! Это сообщение из BOTIX SDK.",
    channel="telegram",  # опционально — иначе берётся last_channel контакта
)
print(response.data.id, response.data.status)
if response.replayed:
    print("Сервер вернул кешированный ответ по совпадению Idempotency-Key")

SDK автоматически генерирует Idempotency-Key (UUID v4) для защиты от случайных дублей при сетевых сбоях. Чтобы отключить: botix.Client(api_key, auto_idempotency=False). Свой ключ — client.messages.send(..., idempotency_key="my-uuid").

Webhooks: проверка подписи

BOTIX подписывает каждое входящее webhook-сообщение HMAC-SHA256 над сырым телом запроса. Секрет вы получили один раз при создании подписки через client.webhooks.create(...).

from flask import Flask, request, abort
import botix

app = Flask(__name__)
WEBHOOK_SECRET = "ваш_секрет_подписки"

@app.route("/botix-webhook", methods=["POST"])
def botix_webhook():
    raw_body = request.get_data()  # ВАЖНО: сырое тело, не request.json
    signature = request.headers.get("X-Botix-Signature", "")

    if not botix.verify_webhook(raw_body, signature, WEBHOOK_SECRET):
        abort(401, "Invalid signature")

    event = request.json
    print(event["event"], event["data"])
    return "", 200

Работа с ошибками

SDK кидает botix.ApiException на любой не-2xx ответ. Код ошибки BOTIX лежит в теле ответа.

import botix
import json

client = botix.Client("btx_live_...")

try:
    contact = client.contacts.get(99999)
except botix.ApiException as e:
    body = json.loads(e.body) if e.body else {}
    code = body.get("error", {}).get("code")
    print(f"HTTP {e.status} / {code}: {body.get('error', {}).get('message')}")

Возможные коды (полный список — в документации API):

Код HTTP Когда
MISSING_API_KEY 401 Нет заголовка Authorization
INVALID_API_KEY 401 Ключ не существует или подделан
KEY_REVOKED 401 Ключ отозван
INSUFFICIENT_SCOPE 403 У ключа нет нужного scope
API_NOT_AVAILABLE_ON_PLAN 403 Тариф клиента не включает API
TRIAL_READ_ONLY 403 Триал — мутирующие методы запрещены
RATE_LIMIT_EXCEEDED 429 Превышен per-minute или per-day лимит
NO_CHANNEL_AVAILABLE 422 Не удалось определить канал отправки
CHANNEL_NOT_SUPPORTED_YET 422 Канал ещё не подключён к API
CONTACT_NOT_REACHABLE 422 У контакта нет chat_id/phone для канала
DELIVERY_FAILED 502 Канал отверг отправку

Доступные ресурсы

client.me()                                        # GET  /me
client.contacts.list(page=1, per_page=50, ...)     # GET  /contacts
client.contacts.get(id)                            # GET  /contacts/{id}
client.contacts.create(**fields)                   # POST /contacts
client.contacts.update(id, **fields)               # PUT  /contacts/{id}
client.contacts.delete(id)                         # DELETE /contacts/{id}
client.contacts.add_tag(id, tag)                   # POST /contacts/{id}/tags
client.contacts.remove_tag(id, tag)                # DELETE /contacts/{id}/tags/{tag}

client.messages.list(...)                          # GET  /messages
client.messages.send(contact_id, content, ...)     # POST /messages

client.scenarios.list()                            # GET  /scenarios
client.scenarios.run(id, contact_id, ...)          # POST /scenarios/{id}/run

client.chats.list(...)                             # GET  /chats
client.chats.messages(chat_id)                     # GET  /chats/{id}/messages

client.channels.list()                             # GET  /channels

client.webhooks.list()                             # GET  /webhooks
client.webhooks.create(url, events)                # POST /webhooks
client.webhooks.update(id, ...)                    # PUT  /webhooks/{id}
client.webhooks.delete(id)                         # DELETE /webhooks/{id}
client.webhooks.test(id)                           # POST /webhooks/{id}/test

Примеры в examples/.

Ссылки

Лицензия

MIT © 2026 BOTIX (ИП Шпагин В.В.)

Metadata

Release files for botix 1.1.0

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

Source distribution (sdist)

Source distribution for botix 1.1.0
File Size Uploaded Provenance Actions
botix-1.1.0.tar.gz 67.6 kB Without provenance Details for botix-1.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 273.6 kB

Release files / botix-1.1.0.tar.gz

Download URL botix-1.1.0.tar.gz
Size 67.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c27abb5752e1baa696d4c5d7f56a28a17f64be6ff3469357193c2d8c1a29afbc
BLAKE2b-256 checksum
How to use checksums
d394439a516325aeb09cef14ed614b37f4aa557e15be66cc6e3ceca81944869e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Release files / botix-1.1.0-py3-none-any.whl

Download URL botix-1.1.0-py3-none-any.whl
Size 206.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
e1f4bc15c69160d9cfe9a4982565fe36a394d73dbcdbf1b4a7b575d40b74bd50
BLAKE2b-256 checksum
How to use checksums
e0f68e1a0429480c768d6092b2efeea1010fcfef94a87e78712324c375c0c27e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.9.6

Security for botix 1.1.0

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.

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files No provenance

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