Metadata-Version: 2.5
Name: py-wecom-toolkit
Version: 5.0.1
Summary: 企业微信（WeCom）官方 API 现代化 Python 工具包，支持同步 / 异步全服务端接口
Project-URL: Homepage, https://gitee.com/guolei19850528/py_wecom_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_wecom_toolkit
Author-email: Guo Lei <174000902@qq.com>
License: MIT
License-File: LICENSE
Keywords: WeCom,wecom-sdk,企业微信,企业微信API
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 :: Only
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 :: Chat
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography>=42.0.0
Requires-Dist: diskcache>=5.6.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: pyjwt>=2.8.0
Requires-Dist: redis>=5.0.0
Provides-Extra: all
Requires-Dist: mypy>=1.13.0; extra == 'all'
Requires-Dist: pre-commit>=4.0.0; extra == 'all'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'all'
Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
Requires-Dist: pytest>=8.3.0; extra == 'all'
Requires-Dist: python-dotenv>=1.0.0; extra == 'all'
Requires-Dist: respx>=0.21.0; extra == 'all'
Requires-Dist: ruff>=0.9.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pre-commit>=4.0.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
Requires-Dist: ruff>=0.9.0; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'test'
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
Requires-Dist: pytest>=8.3.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-wecom-toolkit

企业微信（WeCom / Work / WeChat Work）官方 API 现代化 Python 工具包 —— 类型安全、全量同步 / 异步、零配置自动 Token 管理。

[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
[![httpx](https://img.shields.io/badge/httpx-0.27%2B-lightgray.svg)](https://www.python-httpx.org/)
[![pydantic](https://img.shields.io/badge/pydantic-2.7%2B-e96462.svg)](https://docs.pydantic.dev/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)

---

## ✨ 特性

| 能力 | 说明 |
|------|------|
| **完整 API** | 覆盖群机器人、应用消息、素材、通讯录、网页授权、回调加解密 |
| **同步 + 异步** | 每个服务一对 `Service` / `AsyncService`，API 签名完全一致 |
| **自动 Token** | 默认 `DiskTokenCache` 持久化（跨重启复用，目录 `~/.cache/py_wecom_toolkit`）；Redis / Memory 可切换 |
| **错误分层** | `APIError` 按 errcode 自动细分（TokenExpired / RateLimit / NoPrivilege 等） |
| **类型安全** | Pydantic v2 响应建模 + mypy strict（disallow_untyped_defs / warn_return_any） |
| **现代化** | Python 3.10+，`Self` / `X \| Y` 联合类型 / `TypeAlias` / `populate_by_name` |
| **零配置** | `uv add py-wecom-toolkit` 即用：DiskTokenCache + RedisTokenCache 均已内置 |

## 📦 安装

推荐使用 [uv](https://docs.astral.sh/uv/)（极速 Python 包管理器）：

```bash
uv add py-wecom-toolkit
```

使用 pip 亦可：

```bash
pip install py-wecom-toolkit
```

DiskTokenCache（默认持久化，跨重启复用）与 RedisTokenCache（分布式多进程共享）均为核心依赖，无需额外安装。

开发模式：

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

## 🚀 五分钟上手

### 群机器人（独立，仅需 webhook key）

```python
from py_wecom_toolkit import WebhookClient

with WebhookClient(
    key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
    mentioned_list=["@all"],       # 默认每次都 @ 所有人
) as wb:
    wb.send_text("你好，来自 py-wecom-toolkit @all")
    wb.send_markdown("**重要通知**\n> 生产环境告警")
    wb.send_file(upload["media_id"])  # 先 upload_media 再 send_file
```

### 服务端应用（自动 token 缓存）

```python
from py_wecom_toolkit import WeCom

with WeCom(
    corpid="wx...",       # 企业 ID
    corpsecret="...",     # 应用 Secret
    agentid=1000002,      # 应用 AgentId
) as client:

    # 发消息
    client.message.send_text("hello", touser="@all")
    client.message.send_markdown("**md**\n> 支持 Markdown 语法", touser="@all")
    client.message.send_textcard(title="标题", description="正文",
                                  url="https://...", btntxt="查看",
                                  agentid=1000002, touser="@all")
    client.message.send_news(articles=[{...}], agentid=1000002, touser="@all")

    # 素材（上传拿到 media_id → 发送）
    media = client.media.upload_media(b"content", media_type="file",
                                       filename="a.txt")
    client.message.send_file(media_id=media.media_id, agentid=1000002)

    # 通讯录
    zhangsan = client.user.get("zhangsan")
    dept = client.department.list()
    tags = client.tag.list_tags()
```

### 异步（FastAPI / aiohttp）

```python
from py_wecom_toolkit import AsyncWeCom

async def handler():
    async with AsyncWeCom(corpid="wx...", corpsecret="...") as wc:
        await wc.message.send_text("[async] 异步消息", agentid=1000002)
```

## 🏗️ 架构总览

```
py_wecom_toolkit/
├── client.py              WeCom / AsyncWeCom 顶层组合客户端
├── core/                  底层基础设施（不直接使用）
│   ├── auth.py            TokenManager / AsyncTokenManager（缓存 + 校验 + 刷新）
│   ├── base.py            BaseClient / AsyncBaseClient（httpx + token 注入 + 错误转换）
│   ├── cache.py           三种缓存实现 + TokenCache Protocol + make_cache_key
│   ├── config.py          ClientConfig dataclass
│   ├── crypto.py          MessageCrypto（AES-GCM 加解密 + 签名校验）
│   ├── exceptions.py      APIError 按 errcode 自动细分的异常族
│   ├── models.py          Pydantic v2 响应模型
│   └── utils.py           join_recipients / prepare_file_input
└── services/              业务服务层（全部通过 WeCom().xxx 访问）
    ├── webhook/           群机器人（独立，不需要 token）
    ├── token/             access_token 管理 + get_api_domain_ip
    ├── message/           9 种应用消息类型
    ├── media/             临时素材 / 永久图片
    ├── contact/           User / Department / Tag 全 CRUD
    └── oauth/             网页授权 + 回调加解密（crypto 工具类单独导出）
```

### Token 缓存

```python
from py_wecom_toolkit import WeCom, DiskTokenCache, RedisTokenCache, MemoryTokenCache

# 默认（磁盘持久化，跨重启复用，目录 ~/.cache/py_wecom_toolkit）
WeCom(corpid=..., corpsecret=...)

# 分布式（多进程 / K8s 多副本）
WeCom(..., cache=RedisTokenCache(host="redis.example.com", port=6379))

# 零依赖内存（一次性脚本）
WeCom(..., cache=MemoryTokenCache())
```

统一缓存 key 格式：`py_wecom_toolkit:{corpid}`（不含 corpsecret，同一企业下不同应用 Secret 共享 token）。

### 异常体系

```python
from py_wecom_toolkit import APIError, RateLimitError, TokenExpiredError

with WeCom(...) as wc:
    try:
        wc.message.send_text("hello", agentid=1000002, touser="@all")
    except TokenExpiredError:
        # 实际使用很少遇到 —— BaseClient 会在 42001 时自动 refresh 再重试一次
        wc.token.refresh()
    except RateLimitError as e:
        # 45009 限频 —— 指数退避重试
        log.warning(f"限频 errcode={e.errcode}")
    except APIError as e:
        # 兜底：所有业务层错误
        log.error(f"API errcode={e.errcode} errmsg={e.errmsg} raw={e.raw}")
```

### 回调加解密

```python
from py_wecom_toolkit import MessageCrypto, verify_signature

crypto = MessageCrypto(
    token="回调 Token",
    encoding_aes_key="EncodingAESKey",
    corp_id="wx...",
)

# GET: 解密 echostr
plain = crypto.decrypt_message(
    echostr_encrypted, msg_signature, timestamp, nonce
)
# 把 plain 原样返回给企业微信

# POST: 解密消息推送
plain_xml = crypto.decrypt_message(
    encrypted_xml_body, msg_signature, timestamp, nonce
)
```

## 📁 完整示例

[examples/](./examples) 目录下 5 个可独立运行的示例，覆盖所有核心能力：

| 文件 | 场景 | 依赖 |
|------|------|------|
| `01_webhook_basic.py` | 群机器人 9 种消息类型 | WEBHOOK_KEY |
| `02_wecom_basic.py` | 服务端应用消息 / 素材 / 通讯录 | CORPID / CORPSECRET / AGENTID |
| `03_cache_backends.py` | Disk / Memory / Redis 三种缓存切换 | 无（演示） |
| `04_error_handling.py` | APIError 子类 + 生产级 try/except 模板 | 无（演示） |
| `05_oauth_callback.py` | 网页授权 URL 构造 + 回调加解密 | 无（演示） |

运行：

```bash
cp tests/.env.example tests/.env   # 填入真实凭证
uv run python examples/02_wecom_basic.py
```

## 🧪 测试

```bash
# 全量（真实网络请求，未配置凭证的会自动 skip，退出码 0）
cp tests/.env.example tests/.env   # 填入 WEBHOOK_KEY / CORPID / CORPSECRET / AGENTID
uv run pytest tests -v

# 只跑某模块
uv run pytest tests/test_webhook.py -v
uv run pytest tests/server/test_message.py -v

# 跳过真实网络，只跑本地逻辑（缓存 key / 参数校验）
uv run pytest tests/server/test_token.py -v
```

测试矩阵：

```
tests/
├── conftest.py          fixtures + python-dotenv 加载 .env
├── test_webhook.py      14 tests（同步 + 异步 + 边界校验）
└── server/              按 services 粒度拆分
    ├── test_token.py      5 tests（含 DiskTokenCache roundtrip）
    ├── test_media.py      7 tests（upload → get 回读内容一致）
    ├── test_message.py   12 tests（9 种消息类型 + 异步）
    └── test_contact.py    8 tests（通讯录只读查询）
```

## 🔧 开发

```bash
uv sync                          # 安装依赖
uv run ruff check src tests      # Lint
uv run ruff format src tests     # Format
uv run mypy src/py_wecom_toolkit # 类型检查（strict 模式）
uv run pytest tests -v           # 测试
```

pyproject.toml 关键配置：

```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"]   # 中文全角标点不强制
```

## 📚 官方文档

| 主题 | URL |
|------|-----|
| 企业微信开放平台总入口 | https://developer.work.weixin.qq.com/document/path/90664 |
| 群机器人 | https://developer.work.weixin.qq.com/document/path/91770 |
| 发送应用消息 | https://developer.work.weixin.qq.com/document/path/90236 |
| 临时素材 | https://developer.work.weixin.qq.com/document/path/90253 |
| 永久图片 | https://developer.work.weixin.qq.com/document/path/90256 |
| 通讯录用户 | https://developer.work.weixin.qq.com/document/path/90195 |
| 通讯录部门 | https://developer.work.weixin.qq.com/document/path/90203 |
| 通讯录标签 | https://developer.work.weixin.qq.com/document/path/90209 |
| Token / 频率限制 | https://developer.work.weixin.qq.com/document/path/92530 |
| 消息接收与回调 | https://developer.work.weixin.qq.com/document/path/90968 |
| 网页授权 | https://developer.work.weixin.qq.com/document/path/91138 |


## 📄 License

MIT —— [LICENSE](./LICENSE)
