Metadata-Version: 2.5
Name: pynotifyhub
Version: 0.2.0
Summary: Unified multi-channel notification library: Slack, Discord, Telegram, WeCom, DingTalk, Lark/Feishu, Bark, and voice calls with level-based routing.
Project-URL: Homepage, https://github.com/Allen-zjx/notify-hub
Project-URL: Repository, https://github.com/Allen-zjx/notify-hub
Project-URL: Changelog, https://github.com/Allen-zjx/notify-hub/blob/main/CHANGELOG.md
Author: Allen-zjx
License-Expression: MIT
License-File: LICENSE
Keywords: alert,bark,dingtalk,discord,feishu,lark,notification,slack,telegram,twilio,wecom
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
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: Topic :: Communications
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: tomli>=2.0; python_version < '3.11'
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# notify-hub

[![PyPI](https://img.shields.io/pypi/v/pynotifyhub)](https://pypi.org/project/pynotifyhub/)
[![Python](https://img.shields.io/pypi/pyversions/pynotifyhub)](https://pypi.org/project/pynotifyhub/)
[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)

Unified multi-channel notification library for Python.

Send alerts to **Slack, Discord, Telegram, WeCom (企业微信), DingTalk (钉钉),
Lark/Feishu (飞书), Bark, and phone voice calls (Twilio)** through one API, with
level-based routing configured per application — so you never write
notification glue code again.

```python
from notify_hub import Hub

with Hub.from_config("notify-hub.toml") as hub:
    hub.notify("database is down", level="CRITICAL")  # sends in the background
```

What that one call does is decided entirely by config: which channels fire
for which level, how attachments degrade per channel, retries, dedup,
rate limits, and where the audit log goes.

> 📖 **中文使用说明（30 秒跑通 + 全渠道接入指南）：[docs/usage.md](docs/usage.md)**

## Features

- **8 channels, one interface** — Slack, Discord, Telegram, WeCom, DingTalk,
  Lark/Feishu, Bark, phone voice calls (Twilio, pluggable for other providers).
- **Level-based routing** — builtin `DEBUG..CRITICAL` plus your own custom
  levels (`TRADE_HALT = 45`); each app maps levels to channels in config,
  matching rules are unioned.
- **Background delivery** — `notify()` submits work without waiting for network I/O in both sync
  and asyncio hosts; fan-out runs concurrently on a lazily-started
  background event loop. Await the handle (async) or `wait()` on it (sync)
  only when you need the outcome.
- **Failure isolation & retries** — one channel failing never affects the
  others and never raises into your code; transient errors (429/5xx,
  network) retry with exponential backoff + jitter.
- **Attachments with graceful degradation** — images/files from a path,
  bytes, or URL; channels declare capabilities and unsupported content is
  dropped / linked / failed per your policy (phone calls read text via TTS).
- **Anti-storm guards** — per-channel success dedup window (default 60 s) and
  per-channel token-bucket rate limits, so a crash loop can't ring your
  phone 1000 times.
- **Bounded pending work** — at most 1,000 admitted notifications per hub by default;
  overflow returns `rejected_reason="queue_full"` without waiting or creating send tasks.
- **Audit log** — every notification outcome recorded (per-channel status, attempts,
  latency, errors) as JSON Lines or text, to a file and/or your own
  `logging.Logger`.
- **A well-behaved library** — stdlib dataclasses, one hard dependency
  (`httpx`), zero threads until first use, nothing written or configured
  unless you ask.

## Installation

```bash
pip install pynotifyhub
```

Requires Python 3.10+. Install `pynotifyhub` and import `notify_hub`.

To upgrade an existing installation for Bark support:

```bash
python -m pip install --upgrade pynotifyhub
```

Version 0.2.0 adds Bark, bounded pending notifications and delivery reliability fixes.
The default pending limit is now 1,000; inspect `rejected_reason` when submitting
bursts, or explicitly configure `[hub].max_pending = 0` to disable the limit.

## Quickstart

### 1. Configure once (TOML or a dict)

```toml
# notify-hub.toml
[hub]
default_channels = ["slack-ops"]

[channels.slack-ops]
type = "slack"
webhook_url = "${SLACK_WEBHOOK_URL}"      # expanded from the environment

[channels.oncall-phone]
type = "phone"
provider = "twilio"
account_sid = "${TWILIO_ACCOUNT_SID}"
auth_token = "${TWILIO_AUTH_TOKEN}"
from_number = "+15550001111"
to_numbers = ["+15552223333"]
rate_limit = { per_minute = 2, burst = 1 }

[[routes]]
min_level = "WARNING"
channels = ["slack-ops"]

[[routes]]
levels = ["CRITICAL"]
channels = ["oncall-phone"]               # CRITICAL also matches the rule above
```

See [`examples/notify-hub.example.toml`](examples/notify-hub.example.toml)
for every channel and option. A standalone [Bark configuration](examples/bark.toml) is also included.

### 2. Send

```python
from notify_hub import Attachment, Hub

with Hub.from_config("notify-hub.toml") as hub:
    hub.warning("disk at 85%")  # fire-and-forget
    hub.critical("db down")  # slack + phone call

    handle = hub.notify(
        "deploy finished",
        level="INFO",
        title="Release v2.1",
        attachments=[Attachment.image("https://example.com/chart.png")],
    )
    result = handle.wait(timeout=30)  # only if you need it
    print(result.ok)
```

Async hosts use the same hub:

```python
async with Hub.from_config("notify-hub.toml") as hub:
    hub.error("worker crashed")  # submits background delivery
    result = await hub.notify_async("done")  # or await the outcome
```

Custom levels:

```python
hub.levels.register("TRADE_HALT", 45)  # or [levels.custom] in TOML
hub.notify("strategy halted", level="TRADE_HALT")
```

### 3. Observe

With `[log]` enabled, each notification is recorded with per-channel attempt counts:

```json
{"ts": "2026-06-11T12:00:00+00:00", "level": "CRITICAL", "fingerprint": "9f3a...",
 "preview": "db down", "suppressed_by_dedup": false,
 "channels": [{"id": "slack-ops", "ok": true, "attempts": 1, "latency_ms": 212.4,
               "error": null, "degraded": [], "skipped_reason": null}]}
```

## Bark quickstart

Set `BARK_DEVICE_KEY` in your environment using the device key from the Bark app.
Save the following as `bark.toml`:

```toml
[channels.phone]
type = "bark"
device_key = "${BARK_DEVICE_KEY}"
server_url = "https://api.day.app"
sound = "minuet"
group = "alerts"

[[routes]]
min_level = "WARNING"
channels = ["phone"]
```

```python
from notify_hub import Hub

with Hub.from_config("bark.toml") as hub:
    result = hub.warning("Disk usage reached 85%", title="Server alert").wait(30)
    print(result.delivered_count)
```

The server URL is a base address; do not append your device key or `/push`.
The key is sent in the POST body. Custom Bark servers are supported.
Each channel targets one device. `sound`, `group`, `badge`, `icon`, `url` and
`push_level` are optional. Hub severity selects routes; it does not automatically
set Bark's push level. A successful result confirms server acceptance, not display
or acknowledgement on the phone.

## Delivery semantics

- Submission has caller-side validation, allocation, locking and initial thread-start costs;
  it does not have a fixed return-time guarantee.
- Dedup is per channel and fingerprints the level, title and body (not attachments
  or metadata). An in-flight send reserves its key; only success starts the
  configured window. Failure, cancellation and rate limiting release the key.
  Disabling dedup also disables in-flight suppression.
- Deduplicated channels now appear in `channel_results` with
  `skipped_reason="dedup"`. `suppressed_by_dedup` is true only when all selected
  channels are deduplicated. A mixed result can contain both sends and skips.
- `result.ok` retains its original meaning: no non-skipped channel failed. Check
  `delivered_count`, `skipped_count` and `failed_count` to distinguish delivery,
  suppression and an empty route. Rejected submissions have `ok=False`,
  `rejected_reason="queue_full"` and zero channel counts. Delivery means the adapter completed, not
  that a person read the notification or answered a call.
- Built-in multi-step adapters checkpoint confirmed successes during one
  notification's retries. Successful phone recipients, text sends and completed
  upload steps are not repeated. A new notification starts fresh checkpoints.
  Third-party adapters still receive repeated `send()` calls on retries.
- A lost response can leave acceptance unknown. `ChannelResult.delivery_uncertain`
  flags read/write failures or cancellation after a send attempt began, including
  when a later retry succeeds. Exactly-once delivery is not guaranteed.
- `[hub].max_pending` (or `Hub(max_pending=...)`) limits queued and running
  notifications, including retry and audit work. Default: `1000`; `0` disables
  the bound. Overflow does not wait, route or send; inspect `rejected_reason`.
  Rejections are counted in the next completed notification's audit record as
  `rejected_by_capacity`, or flushed as a summary on close. They are not logged
  individually on the caller's thread or queued as additional log tasks.
- Cancelling or timing out an asynchronous waiter only stops that wait. The
  underlying delivery continues and retains its pending slot until complete;
  another waiter can still get the result. Close the hub to cancel pending sends.
- `close(timeout=10)` stops new submissions, waits up to the drain timeout, then
  cancels remaining work, awaits cleanup and closes resources. Cleanup has a
  separate budget. Cancelled channels have `cancelled=True`, `ok=False`, and a
  final audit record. Use `await hub.aclose()` in async code. Custom adapters must
  cooperate with cancellation; forced process termination cannot flush messages.

## Channel capability matrix

| Channel | Text | Markdown | Image | File | Notes |
|---|:---:|:---:|:---:|:---:|---|
| Slack | ✅ | ✅ (mrkdwn) | ✅* | ✅* | *URL images free via blocks; uploads need `bot_token` + `file_channel` |
| Discord | ✅ | ✅ | ✅ | ✅ | multipart, ≤10 files |
| Telegram | ✅ | ✅ (HTML) | ✅ | ✅ | single image + short text sent as captioned photo |
| WeCom 企业微信 | ✅ | ✅ | ✅ | ✅ | image ≤2 MB jpg/png; file via `upload_media` |
| DingTalk 钉钉 | ✅ | ✅ | — | — | HMAC signing or keyword prefix |
| Lark/Feishu 飞书 | ✅ | ✅ (post) | ✅* | — | *images need `app_id`+`app_secret` (custom app); both feishu.cn and larksuite.com |
| Bark | ✅ | — | — | — | REST push; official or self-hosted server, one device per channel |
| Phone (Twilio) | ✅ (TTS) | — | — | — | text stripped of markdown/URLs, read aloud |

Unsupported content degrades per `[degrade]` policy — by default it is
dropped quietly and noted in the result, never failing the notification.

## Writing your own channel

```python
from notify_hub import Capability, Channel, Message, register_channel


@register_channel
class MyChannel(Channel):
    name = "mychannel"
    capabilities = Capability.TEXT

    async def send(
        self, message: Message
    ) -> None: ...  # raise ChannelSendError on failure; hub handles retry/logging
```

Or publish it as an entry point in the `notify_hub.channels` group.
Voice providers (e.g. Vonage) subclass `VoiceProvider` the same way.

## Design notes

- The TOML schema and routing semantics are language-neutral by design —
  they are the contract for planned Go and Rust ports.
- v2 reserves `escalation` (ack + auto-escalate chains) and `digest`
  (aggregation windows) fields in routing rules; they parse today and warn,
  but do nothing yet.

## Development

```bash
pip install -e ".[dev]"
pytest                 # tests
ruff check . && ruff format --check .
mypy
```

## License

MIT
