Skip to main content

py-tjbrhk-toolkit

天津博瑞皓科博瑞云音箱官方 API 现代化 Python 工具包 —— 类型安全、同步 / 异步一致、开箱即用的语音播报客户端。

Python httpx pydantic License


✨ 特性

能力 说明
云音箱通知 通过 Token + ID 调用 notify.php 提交语音播报,支持支付播报、语音提醒等场景
同步 + 异步 Tjbrhk / AsyncTjbrhk API 签名完全一致,可自由切换
连接池复用 基于 httpx,支持 context manager 自动关闭连接,也可手动 close()
错误分层 ConfigError / ValidationError / HTTPError 统一继承 TjbrhkError
类型安全 Pydantic v2 响应建模 + mypy strict(disallow_untyped_defs / warn_return_any)
现代化 Python 3.10+,X | Y 联合类型、slots dataclass、PEP 561 类型标记

📦 安装

推荐使用 uv:

uv add py-tjbrhk-toolkit

使用 pip 亦可:

pip install py-tjbrhk-toolkit

开发模式:

git clone <your-repo>
cd py_tjbrhk_toolkit
uv sync                          # 创建 venv + 安装依赖 + 安装本包
uv run pytest tests -v

🚀 五分钟上手

Tjbrhk / AsyncTjbrhk 是顶层组合客户端:持有底层连接池,并通过 client.speaker 暴露云音箱服务,后续可平滑扩展更多服务。

同步播报

from py_tjbrhk_toolkit import Tjbrhk

with Tjbrhk(
    token="你的云音箱 Token",
    id="你的云音箱 ID",
) as client:
    response = client.speaker.notify("您好,欢迎光临", vol=80)
    print(response.errcode, response.errmsg, response.ok)

异步播报(FastAPI / asyncio)

from py_tjbrhk_toolkit import AsyncTjbrhk

async def handler() -> None:
    async with AsyncTjbrhk(
        token="你的云音箱 Token",
        id="你的云音箱 ID",
    ) as client:
        response = await client.speaker.notify("收到一笔新的付款", vol=80)
        print(response.ok)

同步客户端用 with、异步客户端用 async with 管理连接;也可分别调用 Tjbrhk.close() 与 AsyncTjbrhk.close() 手动关闭。

也可以直接传入完整配置 Tjbrhk(config=SpeakerConfig(...)),此时其余便捷参数被忽略。

🏗️ 架构总览

py_tjbrhk_toolkit/
├── __init__.py            包根导出(客户端 / 模型 / 异常 / 配置)
├── client.py              顶层 Tjbrhk / AsyncTjbrhk 组合客户端
├── core/                  底层基础设施(不直接使用)
│   ├── base.py            BaseClient / AsyncBaseClient(httpx + 错误转换)
│   ├── config.py          SpeakerConfig dataclass
│   ├── exceptions.py      TjbrhkError 异常族
│   └── models.py          Pydantic v2 响应模型
└── services/              业务服务层(每个 API 领域一个子包)
    ├── __init__.py        子包说明
    └── speaker/           云音箱通知服务
        ├── __init__.py    导出 SpeakerService / AsyncSpeakerService
        └── client.py      notify.php 服务实现(组合 BaseClient)

⚙️ 客户端配置

Tjbrhk 与 AsyncTjbrhk 使用相同的构造参数:

参数 必填 默认值 说明
token 是 — 云音箱 Token。
id 是 — 云音箱 ID。
base_url 否 https://speaker.17laimai.cn 云音箱服务接口地址。
version 否 1 接口版本。
timeout 否 30.0 HTTP 请求超时时间,单位为秒。
httpx_kwargs 否 {} 透传给 httpx.Client / httpx.AsyncClient 的额外参数(代理、TLS、传输器等)。

需要更细粒度控制时,也可以直接构造 SpeakerConfig:

from py_tjbrhk_toolkit import SpeakerConfig

config = SpeakerConfig(token="...", id="...", timeout=10.0)
print(config.url("/notify.php"))

📢 notify 接口

notify(
    message,
    *,
    seq=None,
    vol=None,
    speed=None,
    trace_no=None,
    id=None,
    token=None,
    version=None,
)
参数 类型 必填 说明
message str 是 播报内容,最长 128 个 UTF-8 字节
seq int | str 否 通讯去重顺序号
vol int | str 否 音量设置
speed int | str 否 语速设置
trace_no str 否 请求追踪字符串
id str 否 覆盖客户端配置的云音箱 ID
token str 否 覆盖客户端配置的 Token
version str 否 覆盖客户端配置的接口版本

接口返回 SpeakerNotifyResponse,字段 errcode、errmsg、detail 与接口响应一致; response.ok 在 errcode 等于 0 或 "0" 时为 True。

消息中的数字默认按金额播报;如需按号码或编号播报,可按接口约定使用方括号,例如 "[123]"。 音箱型号和接口版本对 speed 等参数的支持可能不同,请以官方接口文档为准。

🔐 环境变量与示例

examples/ 目录下提供两个可直接运行的示例,凭证全部从环境变量读取:

文件 场景 依赖
01_speaker_sync.py 同步发送播报 SPEAKER_ID / SPEAKER_TOKEN
02_speaker_async.py 异步发送播报 SPEAKER_ID / SPEAKER_TOKEN

复制配置模板并填写真实凭证:

cp tests/.env.example .env
环境变量 必填 默认值 说明
SPEAKER_ID 是 — 云音箱 ID。
SPEAKER_TOKEN 是 — 云音箱 Token。
SPEAKER_BASE_URL 否 https://speaker.17laimai.cn 接口地址。
SPEAKER_VERSION 否 1 接口版本。

示例会从仓库根目录加载 .env,系统中已有的环境变量优先。运行:

uv run python examples/01_speaker_sync.py
uv run python examples/02_speaker_async.py

.env 包含设备凭据,请勿提交到版本控制。

⚠️ 异常体系

from py_tjbrhk_toolkit import ConfigError, HTTPError, TjbrhkError, ValidationError

try:
    with Tjbrhk(token="...", id="...") as client:
        client.speaker.notify("您好")
except ValidationError:
    # 参数不符合接口约定,例如 message 超过 128 个 UTF-8 字节
    ...
except ConfigError:
    # token / id / base_url 为空
    ...
except HTTPError as exc:
    # 网络异常、非 2xx 状态码或响应不是 JSON 对象
    print(f"云音箱请求失败: {exc}(status={exc.status_code})")
except TjbrhkError:
    # 兜底:所有本包错误
    ...

🧪 测试

测试全部为真实网络请求,会向真实云音箱推送语音播报。凭证从环境变量读取, 缺少 SPEAKER_ID / SPEAKER_TOKEN 时相关用例自动 skip,不会中断其它用例。

cp tests/.env.example .env   # 填写真实凭证
uv run pytest tests -v

测试矩阵:

tests/
├── conftest.py                 fixtures + python-dotenv 加载 .env
└── speaker/
    ├── test_notify_sync.py     同步播报 + 本地参数校验
    └── test_notify_async.py    异步播报 + 本地参数校验

注意: 默认测试会触发真实设备语音播报。请勿在不适合播报的设备或环境中执行。

🔧 开发

uv sync
uv run ruff check src tests      # Lint
uv run ruff format src tests     # Format
uv run mypy src/py_tjbrhk_toolkit # 类型检查(strict 模式)
uv run pytest tests -v           # 测试

pyproject.toml 关键配置:

[tool.mypy]
disallow_untyped_defs = true
warn_return_any = true
strict_optional = true

[tool.ruff]
select = ["E", "F", "I", "N", "W", "B", "UP", "RUF"]
ignore = ["RUF001", "RUF002", "RUF003"]   # 中文全角标点不强制

👤 作者

📄 License

MIT —— LICENSE

Metadata

Release files for py-tjbrhk-toolkit 5.0.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 py-tjbrhk-toolkit 5.0.0
File Size Uploaded Provenance Actions
py_tjbrhk_toolkit-5.0.0.tar.gz 12.5 kB Without provenance Details for py_tjbrhk_toolkit-5.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for py-tjbrhk-toolkit 5.0.0
File Interpreter ABI Platform Actions
py_tjbrhk_toolkit-5.0.0-py3-none-any.whl Python 3 none any Details for py_tjbrhk_toolkit-5.0.0-py3-none-any.whl

Total release size: 29.1 kB

Release files / py_tjbrhk_toolkit-5.0.0.tar.gz

Download URL py_tjbrhk_toolkit-5.0.0.tar.gz
Size 12.5 kB
Tags Source
SHA-256 checksum
How to use checksums
5a464310d0c7f67498de5226db731229f422bde435af00afe6299e8975d9e02f
BLAKE2b-256 checksum
How to use checksums
4ee28e1bb701172163fa59efcf9b37f603b990ee231cb7dbf392cdece433c981
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / py_tjbrhk_toolkit-5.0.0-py3-none-any.whl

Download URL py_tjbrhk_toolkit-5.0.0-py3-none-any.whl
Size 16.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
0c819400c0994757ceff2adc04a6c29b406dae7ffbd1a1d7bb65f3be47c3f17a
BLAKE2b-256 checksum
How to use checksums
729ed3d69d7072c0887dfc83504fcaa90ae7bc2f01573c4f083d4527458c25f6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for py-tjbrhk-toolkit 5.0.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.

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