Metadata-Version: 2.4
Name: a24wh
Version: 0.1.2
Summary: Bitrix24 webhook helper library by Automatization24.
Author: Automatization24
License-Expression: MIT
Project-URL: Homepage, https://github.com/automatization24/a24wh
Project-URL: Repository, https://github.com/automatization24/a24wh
Keywords: bitrix24,webhook,rest,automatization24
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.31.0
Dynamic: license-file

## a24wh

Python library for Bitrix24 incoming webhooks by Automatization24.

Библиотека Python для работы с входящими вебхуками Bitrix24 от Automatization24.

## README (EN)

### Version

The package uses classic semantic versioning.

Current version:

```text
0.1.2
```

### Public API

Only 6 public helpers are exported from `a24wh`:

```python
from a24wh import request24, req24, save_json, batch_list, batch_by_params, to_chat
```

### Install

Install from PyPI:

```bash
pip install a24wh
```

Supported Python versions:

```text
3.10, 3.11, 3.12, 3.13, 3.14
```

### Quick Start

#### `request24(...)`

```python
import os
from a24wh import request24

response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

`request24(...)` is the helper for classic Bitrix24 REST.

#### `req24(...)`

```python
import os
from a24wh import req24

response = req24(
    method="crm.item.list",
    parameters={
        "select": ["id", "title"],
        "filter": {
            ">id": 0,
            },
        },
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

`req24(...)` is the helper for Bitrix24 REST v3.

List method with automatic pagination:

```python
import os
from a24wh import request24

response = request24(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 0},
        "select": ["ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=True,
    )
```

#### `save_json(...)`

```python
from a24wh import save_json

save_json(response, file_title="crm.deal.get")
```

#### `batch_list(...)`

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 14},
        "select": ["ID", "STAGE_ID", "CONTACT_ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

#### `batch_by_params(...)`

```python
import os
from a24wh import batch_by_params

response = batch_by_params(
    method="crm.deal.get",
    params_list=[
        {"id": 56328},
        {"id": 56370},
        {"id": 56380},
        ],
    webhook_url=os.getenv("WEBHOOK"),
    )
```

#### `to_chat(...)`

```python
import os
from a24wh import to_chat

response = to_chat(
    text="Test message",
    chat_id="chat11111",
    webhook_url=os.getenv("WEBHOOK_CHAT"),
    )
```

### Response Structure

`request24(...)`, `req24(...)`, `batch_list(...)`, and `batch_by_params(...)` always return a `dict`.

Success example:

```python
{"result": ...}
```

Error example:

```python
{
    "error_result": True,
    "error_type": "http_error",
    "error_code": "500",
    "error_message": "Bitrix24 returned HTTP 500.",
    "method": "crm.deal.get",
    "portal": "example.bitrix24.ru",
    "status_code": 500,
    }
```

Recommended check:

```python
if "error_result" in response:
    print(response["error_message"])
else:
    print(response)
```

### Environment Variables

Copy-ready `.env` block with library defaults:

```env
A24WH_DEFAULT_WEBHOOK_URL=
A24WH_TIMEOUT=60
A24WH_RETRY_COUNT=3
A24WH_RETRY_DELAY=1.0
A24WH_REQUEST_DELAY=1.0
A24WH_AUTO_CONFIGURE_LOGGING=0
A24WH_LOG_LEVEL=INFO
A24WH_LOG_TO_CONSOLE=1
A24WH_LOG_TO_FILE=0
A24WH_LOG_FILE=a24wh.log
```

You can paste this block into `.env` and change only the values you need.

To enable verbose local logging, change these values in the same block:

```env
A24WH_AUTO_CONFIGURE_LOGGING=1
A24WH_LOG_LEVEL=DEBUG
A24WH_LOG_TO_FILE=1
```

If `webhook_url=None`, the library tries to use `A24WH_DEFAULT_WEBHOOK_URL`.

That gives you two working styles:

1. Explicit webhook in code:

```python
response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

2. Default webhook from environment:

```python
response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=None,
    all_iters=False,
    )
```

### Logging

The library logger name is `a24wh`.

The package does not override application logging automatically unless local auto logging is enabled through environment
variables from the block above.

### Usage Examples

Batch list example:

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 14},
        "select": ["ID", "TITLE", "STAGE_ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Batch by params example:

```python
import os
from a24wh import batch_by_params

response = batch_by_params(
    method="crm.deal.get",
    params_list=[
        {"id": 56328},
        {"id": 56370},
        {"id": 56380},
        ],
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Smart process list example:

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.item.list",
    parameters={
        "entityTypeId": 190,
        "filter": {"=categoryId": 3},
        "select": ["id", "title", "stageId"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Save response to JSON:

```python
from a24wh import save_json

save_json(response, file_title="crm.deal.list")
```

### Tests

```bash
cd /path/to/a24wh
python -m unittest discover -s tests -v
```

## README (RU)

### Версия

Пакет использует классическую семантическую версионность.

Текущая версия:

```text
0.1.2
```

### Публичный API

Из `a24wh` наружу экспортируются только 6 публичных методов:

```python
from a24wh import request24, req24, save_json, batch_list, batch_by_params, to_chat
```

### Установка

Установка из PyPI:

```bash
pip install a24wh
```

Поддерживаемые версии Python:

```text
3.10, 3.11, 3.12, 3.13, 3.14
```

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

#### `request24(...)`

```python
import os
from a24wh import request24

response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

`request24(...)` используйте для классического REST Bitrix24.

#### `req24(...)`

```python
import os
from a24wh import req24

response = req24(
    method="crm.item.list",
    parameters={
        "select": ["id", "title"],
        "filter": {
            ">id": 0,
            },
        },
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

`req24(...)` используйте для REST v3 Bitrix24.

Списочный метод с автоматическим сбором всех страниц:

```python
import os
from a24wh import request24

response = request24(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 0},
        "select": ["ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=True,
    )
```

#### `save_json(...)`

```python
from a24wh import save_json

save_json(response, file_title="crm.deal.get")
```

#### `batch_list(...)`

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 14},
        "select": ["ID", "STAGE_ID", "CONTACT_ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

#### `batch_by_params(...)`

```python
import os
from a24wh import batch_by_params

response = batch_by_params(
    method="crm.deal.get",
    params_list=[
        {"id": 56328},
        {"id": 56370},
        {"id": 56380},
        ],
    webhook_url=os.getenv("WEBHOOK"),
    )
```

#### `to_chat(...)`

```python
import os
from a24wh import to_chat

response = to_chat(
    text="Тестовое сообщение",
    chat_id="chat11111",
    webhook_url=os.getenv("WEBHOOK_CHAT"),
    )
```

### Структура ответа

`request24(...)`, `req24(...)`, `batch_list(...)` и `batch_by_params(...)` всегда возвращают `dict`.

Пример успешного ответа:

```python
{"result": ...}
```

Пример ответа с ошибкой:

```python
{
    "error_result": True,
    "error_type": "http_error",
    "error_code": "500",
    "error_message": "Bitrix24 returned HTTP 500.",
    "method": "crm.deal.get",
    "portal": "example.bitrix24.ru",
    "status_code": 500,
    }
```

Рекомендуемая проверка:

```python
if "error_result" in response:
    print(response["error_message"])
else:
    print(response)
```

### Переменные окружения

Готовый блок `.env` со значениями по умолчанию библиотеки:

```env
A24WH_DEFAULT_WEBHOOK_URL=
A24WH_TIMEOUT=60
A24WH_RETRY_COUNT=3
A24WH_RETRY_DELAY=1.0
A24WH_REQUEST_DELAY=1.0
A24WH_AUTO_CONFIGURE_LOGGING=0
A24WH_LOG_LEVEL=INFO
A24WH_LOG_TO_CONSOLE=1
A24WH_LOG_TO_FILE=0
A24WH_LOG_FILE=a24wh.log
```

Можно вставить этот блок в `.env` и поменять только нужные значения.

Чтобы включить подробное локальное логирование, поменяй в этом же блоке такие значения:

```env
A24WH_AUTO_CONFIGURE_LOGGING=1
A24WH_LOG_LEVEL=DEBUG
A24WH_LOG_TO_FILE=1
```

Если `webhook_url=None`, библиотека пытается использовать `A24WH_DEFAULT_WEBHOOK_URL`.

Это дает два рабочих варианта:

1. Явно передавать webhook в коде:

```python
response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=os.getenv("WEBHOOK"),
    all_iters=False,
    )
```

2. Использовать дефолтный webhook из окружения:

```python
response = request24(
    method="crm.deal.get",
    parameters={"id": 10},
    webhook_url=None,
    all_iters=False,
    )
```

### Логирование

Имя логгера библиотеки: `a24wh`.

Пакет не переопределяет логирование приложения автоматически, пока ты сам не включишь локальную автоконфигурацию через
переменные окружения из блока выше.

### Примеры использования

Пример batch list:

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.deal.list",
    parameters={
        "order": {"ID": "ASC"},
        "filter": {"=CATEGORY_ID": 14},
        "select": ["ID", "TITLE", "STAGE_ID"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Пример batch by params:

```python
import os
from a24wh import batch_by_params

response = batch_by_params(
    method="crm.deal.get",
    params_list=[
        {"id": 56328},
        {"id": 56370},
        {"id": 56380},
        ],
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Пример для списка смарт-процесса:

```python
import os
from a24wh import batch_list

response = batch_list(
    method="crm.item.list",
    parameters={
        "entityTypeId": 190,
        "filter": {"=categoryId": 3},
        "select": ["id", "title", "stageId"],
        },
    webhook_url=os.getenv("WEBHOOK"),
    )
```

Сохранение ответа в JSON:

```python
from a24wh import save_json

save_json(response, file_title="crm.deal.list")
```

### Тесты

```bash
cd /path/to/a24wh
python -m unittest discover -s tests -v
```
