Metadata-Version: 2.5
Name: py-lmobile-toolkit
Version: 4.1.0
Summary: Synchronous and asynchronous Lmobile (微网通联) SMS API client for Python / 微网通联短信接口同步与异步客户端
Project-URL: HomePage, https://gitee.com/guolei19850528/py_lmobile_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_lmobile_toolkit
Author-email: 郭磊 <174000902@qq.com>
License: MIT
License-File: LICENSE
Keywords: 微网通联,短信,短信发送,短信接口
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx<1.0,>=0.24.0
Requires-Dist: pydantic<3.0,>=2.0.0
Provides-Extra: all
Requires-Dist: mkdocs-material>=9.0.0; extra == 'all'
Requires-Dist: mkdocs>=1.5.0; extra == 'all'
Requires-Dist: mypy>=1.10.0; extra == 'all'
Requires-Dist: pre-commit>=3.7.0; extra == 'all'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'all'
Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
Requires-Dist: pytest>=8.0.0; extra == 'all'
Requires-Dist: python-dotenv>=1.0.0; extra == 'all'
Requires-Dist: respx>=0.21.0; extra == 'all'
Requires-Dist: ruff>=0.8.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pre-commit>=3.7.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'test'
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
Requires-Dist: pytest>=8.0.0; extra == 'test'
Requires-Dist: python-dotenv>=1.0.0; extra == 'test'
Requires-Dist: respx>=0.21.0; extra == 'test'
Description-Content-Type: text/markdown

# py-lmobile-toolkit

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

[中文](README.md) | [English](README.en.md)

## 功能

- **微网通联短信接口**：提交短信，支持同步和异步客户端，均支持上下文管理器以自动关闭 HTTP 连接。
- **类型模型**：基于 Pydantic 定义请求和响应模型。

## 安装

```bash
pip install py-lmobile-toolkit
```

使用 uv：

```bash
uv add py-lmobile-toolkit
```

需要开发与测试工具时，从仓库安装：

```bash
uv sync --extra dev --extra test
```

## 包结构

```text
src/py_lmobile_toolkit/
├── __init__.py
├── py.typed
└── sms/
    ├── __init__.py
    ├── _clients.py
    └── _models.py
examples/
└── sms/
    ├── .env.example
    ├── send_sms_async.py
    └── send_sms_sync.py
tests/
└── sms/
    ├── .env.example
    ├── conftest.py
    ├── test_send_sms_async.py
    └── test_send_sms_sync.py
```

包根导出 `sms` 模块。各模块对外公开的名称带有 `Sms` 前缀，避免名称冲突；`_` 开头的文件是内部实现模块。

## 使用

### 1. sms 模块 - 短信发送

短信模块通过平台账户、密码和产品编号初始化客户端。`send_sms` 支持单个号码、逗号分隔的号码字符串或号码序列。

#### 1.1 发送短信

**同步发送：**

```python
from py_lmobile_toolkit.sms import SmsClient

with SmsClient(
    account_id="短信平台账户",
    password="短信平台密码",
    product_id=1012,
) as client:
    response = client.send_sms(
        ["13800000001", "13800000002"],
        "【已报备签名】这是一条测试短信",
    )
    if response.ok:
        print(f"短信提交成功，消息编号：{response.MsgId}")
    else:
        print(f"短信提交失败：{response.Reason}")
```

**异步发送：**

```python
import asyncio

from py_lmobile_toolkit.sms import SmsAsyncClient


async def main() -> None:
    async with SmsAsyncClient(
        account_id="短信平台账户",
        password="短信平台密码",
        product_id=1012,
    ) as client:
        response = await client.send_sms(
            "13800000001,13800000002",
            "【已报备签名】这是一条测试短信",
        )
        if response.ok:
            print(f"短信提交成功，消息编号：{response.MsgId}")
        else:
            print(f"短信提交失败：{response.Reason}")


asyncio.run(main())
```

#### 1.2 客户端配置

同步客户端 `SmsClient` 和异步客户端 `SmsAsyncClient` 使用相同的构造参数：

| 参数 | 必填 | 默认值 | 说明 |
|------|------|--------|------|
| `account_id` | 是 | — | 短信平台账户。 |
| `password` | 是 | — | 短信平台密码。 |
| `product_id` | 是 | — | 短信产品编号，支持正整数或数字字符串；客户端会转换为正整数。 |
| `password_encryption_key` | 否 | `SMmsEncryptKey` | 短信接口使用的密码加密密钥。 |
| `base_url` | 否 | `https://api.51welink.com` | 短信服务接口地址。 |
| `timeout` | 否 | `30.0` | HTTP 请求超时时间，单位为秒。 |

#### 1.3 短信发送参数及响应

`send_sms(phone_nos, content, *, extend_no=None, send_time=None, out_id=None)` 支持以下参数：

| 参数 | 说明 |
|------|------|
| `phone_nos` | 一个号码、号码序列，或英文逗号分隔的号码字符串。 |
| `content` | 短信正文，长度为 1 至 1000 个字符，应包含已报备签名。 |
| `extend_no` | 可选企业扩展码，最多 12 位数字。 |
| `send_time` | 可选定时发送时间，可传字符串或 `datetime`。 |
| `out_id` | 可选用户自定义标识，最多 32 个字符。 |

接口返回 `SendSmsResponse`，其属性名与平台响应字段一致：`Result`、`Reason`、`MsgId` 和 `SplitCount`。`response.ok` 在 `Result` 等于 `succ`（忽略大小写）时为 `True`。

#### 1.4 使用环境变量运行示例

示例脚本从**运行命令时的当前目录**加载 `.env` 文件，且系统中已有的环境变量优先。复制配置模板并填写平台账户、密码、产品编号、接收号码及短信签名：

```bash
cp examples/sms/.env.example .env
```

完成配置后运行同步或异步示例：

```bash
python examples/sms/send_sms_sync.py
```

```bash
python examples/sms/send_sms_async.py
```

`.env` 文件包含账户凭据，请勿提交到版本控制。

#### 1.5 异常处理

客户端配置无效或请求参数不符合模型校验时会产生 `ValueError`；HTTP 网络请求失败时会产生 `RuntimeError`。调用方可根据需要显式处理：

```python
try:
    # 在此处初始化客户端并调用 send_sms。
    ...
except (ValueError, RuntimeError) as exc:
    print(f"短信请求失败：{exc}")
```

## 配置示例与测试

示例脚本读取环境变量；仓库提供 [examples/sms/.env.example](examples/sms/.env.example) 作为配置模板。将所需变量设置在仓库根目录的 `.env` 中，或在运行脚本前导出环境变量。

测试配置位于 [tests/sms/.env.example](tests/sms/.env.example)。复制到对应测试目录的 `.env` 并填入有效凭证。配置包含 `ACCOUNT_ID`、`PASSWORD`、`PRODUCT_ID`、`PHONE_NOS` 和 `SMS_SIGNATURE`。

```bash
pytest
```

测试配置在缺少必需环境变量时会跳过相应测试。pytest 默认配置会输出终端、HTML 和 XML 覆盖率报告。

## 开发

```bash
ruff check .
ruff format --check .
python -m compileall -q src examples tests
```

项目支持 Python 3.9 及以上版本。核心依赖包括 httpx 和 Pydantic；开发、测试、文档工具可通过 `pyproject.toml` 中的可选依赖组安装。

## 许可证

本项目基于 [MIT 许可证](LICENSE) 开源。
