Metadata-Version: 2.3
Name: py-wecom-sdk
Version: 1.2.0
Summary: 企业微信（WeCom）开放接口的 Python SDK，基于 httpx + pydantic，同步与异步统一封装。
Keywords: wecom,wechat-work,企业微信,sdk,httpx,pydantic,群机器人
Author: guolei
Author-email: guolei <174000902@qq.com>
License: MIT License
         
         Copyright (c) 2026 郭磊
         
         Permission is hereby granted, free of charge, to any person obtaining a copy
         of this software and associated documentation files (the "Software"), to deal
         in the Software without restriction, including without limitation the rights
         to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
         copies of the Software, and to permit persons to whom the Software is
         furnished to do so, subject to the following conditions:
         
         The above copyright notice and this permission notice shall be included in all
         copies or substantial portions of the Software.
         
         THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
         IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
         FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
         AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
         LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
         OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
         SOFTWARE.
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: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.14.3
Requires-Dist: diskcache>=5.6.1
Requires-Dist: redis>=5.0.0 ; extra == 'redis'
Maintainer: guolei
Maintainer-email: guolei <174000902@qq.com>
Requires-Python: >=3.10
Project-URL: Homepage, https://gitee.com/guolei19850528/py_wecom_sdk
Project-URL: Repository, https://gitee.com/guolei19850528/py_wecom_sdk.git
Project-URL: Issues, https://gitee.com/guolei19850528/py_wecom_sdk/issues
Provides-Extra: redis
Description-Content-Type: text/markdown

# py-wecom-sdk

企业微信（WeCom）开放接口的 **Python SDK**，基于 `httpx` + `pydantic` v2，**同步**风格、强类型响应、可插拔 access_token 缓存。

[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

---

## ✨ Features

- **统一 Provider 入口** — `WeComAPIProvider` 聚合 media / message / contact 全部业务域
- **群机器人独立客户端** — `WeComGroupRobotAPI(key=...)` 一键发送所有 webhook 消息类型
- **强类型响应** — `pydantic` v2 自动校验，`resp.ok()` / `resp.raise_for_status()` 统一处理
- **可插拔 Token 缓存** — `diskcache` 默认本地 / `redis` 可选分布式 / 任意自定义继承
- **完整类型标注** — `mypy strict` 通过
- **真实集成测试** — 50 passed，覆盖所有已实现接口
- **国内友好** — 默认 `https://qyapi.weixin.qq.com/`，可自定义 `base_url`

---

## 📦 Installation

```bash
# uv（推荐）
uv add py-wecom-sdk

# pip
pip install py-wecom-sdk

# 加上 Redis 分布式缓存支持（多进程 / 集群部署）
pip install py-wecom-sdk[redis]
```

**Python ≥ 3.10**。

### 依赖组成

| 依赖 | 类型 | 说明 |
|------|------|------|
| `httpx>=0.28.1` | 默认 | HTTP 客户端底层 |
| `pydantic>=2.14.3` | 默认 | 响应模型校验 + 配置模型 |
| `diskcache>=5.6.1` | 默认 | access_token 默认本地缓存，零配置可用 |
| `redis>=5.0.0` | 可选 | access_token 分布式缓存，`py-wecom-sdk[redis]` 安装 |

> 💡 没装 `redis` 也没问题 —— 只有显式实例化 `WeComAccessTokenRedisCache` 时才会 `import redis`，默认用的是 `WeComAccessTokenDiskcacheCache`。

---

## 🚀 Quick Start

### 应用消息 + 通讯录 + 素材（主 Provider）

```python
from py_wecom_sdk.provider import WeComAPIProvider
from py_wecom_sdk.core.base.config import WeComAPIConfig

config = WeComAPIConfig(
    corpid="wwXXXXXXXXXXXXXXXX",
    corpsecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    agentid=1000002,
)
provider = WeComAPIProvider(config)

# 发送应用消息
resp = provider.message_send_api.message_send_text(
    content="Hello WeCom SDK!",
    touser="Guolei",
)
print(resp.ok, resp.errcode)  # True 0

# 查询成员
resp = provider.contact_user_api.user_get("Guolei")
print(resp.name, resp.department)  # 郭磊 [60]

# 查询部门列表
resp = provider.contact_department_api.department_list()
for dept in resp.department:
    print(dept["name"])

# 上传临时素材 → 发送图片消息
upload = provider.media_api.media_upload("chart.png", media_type="image")
provider.message_send_api.message_send_image(upload.media_id, touser="Guolei")

provider.close()
```

### 群机器人 Webhook（独立客户端）

```python
from py_wecom_sdk.core.group_robot.api import WeComGroupRobotAPI
from py_wecom_sdk.core.group_robot.config import WeComGroupRobotAPIConfig

robot = WeComGroupRobotAPI(
    WeComGroupRobotAPIConfig(key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
)

robot.webhook_send_text("Hello robot!")
robot.webhook_send_markdown("## Title\n> content")
robot.webhook_send_news([{"title": "News", "url": "https://..."}])

# 上传文件 → 发送文件消息
uploaded = robot.webhook_upload_media("report.txt", media_type="file")
robot.webhook_send_file(media_id=uploaded.media_id)
```

---

## 📚 API 参考

### Provider 属性

| Provider 属性 | 类 | 业务域 |
|---|---|---|
| `provider.media_api` | `MediaAPI` | 素材管理 |
| `provider.message_send_api` | `MessageSendAPI` | 应用消息 |
| `provider.contact_user_api` | `ContactUserAPI` | 通讯录成员 |
| `provider.contact_department_api` | `ContactDepartmentAPI` | 通讯录部门 |
| `provider.contact_tag_api` | `ContactTagAPI` | 通讯录标签 |

---

### MediaAPI — 素材管理

官方文档：[90253 上传临时素材](https://developer.work.weixin.qq.com/document/path/90253) · [90254 下载临时素材](https://developer.work.weixin.qq.com/document/path/90254) · [90256 上传永久图片](https://developer.work.weixin.qq.com/document/path/90256)

| 方法 | 说明 |
|---|---|
| `media_upload(file, media_type)` | 上传临时素材（image / voice / video / file），返回 `media_id` |
| `media_get(media_id, range_header=None)` | 下载临时素材，返回 `MediaDownloadResult(content, filename, content_type)` |
| `media_uploadimg(file)` | 上传永久图片（每月 3000 张），返回 `url` |

```python
# 上传 → 下载 → 保存
upload = provider.media_api.media_upload("report.pdf", media_type="file")
print(upload.media_id)

result = provider.media_api.media_get(upload.media_id)
result.save_to("downloaded.pdf")

# 永久图片（url 永久有效）
permanent = provider.media_api.media_uploadimg("banner.png")
print(permanent.url)  # https://wework.qpic.cn/...
```

---

### MessageSendAPI — 应用消息发送

官方文档：[90236 发送应用消息](https://developer.work.weixin.qq.com/document/path/90236)

| 方法 | msgtype | 说明 |
|---|---|---|
| `message_send(payload)` | 底层 | 直接传完整 JSON，自动补 agentid |
| `message_send_text(...)` | text | 文本消息，支持 safe / enable_duplicate_check |
| `message_send_markdown(...)` | markdown | Markdown 消息 |
| `message_send_image(media_id, ...)` | image | 图片（media_id 来自 `MediaAPI.media_upload`） |
| `message_send_voice(media_id, ...)` | voice | 语音 |
| `message_send_video(media_id, *, title, description, ...)` | video | 视频 |
| `message_send_file(media_id, ...)` | file | 文件 |
| `message_send_textcard(*, title, description, url, btntxt, ...)` | textcard | 文本卡片 |
| `message_send_news(articles, ...)` | news | 图文，1~8 条 |
| `message_send_template_card(template_card, ...)` | template_card | 模板卡片 |

所有便捷方法：
- `touser / toparty / totag` 至少指定一个（否则 `ValueError`）
- 自动从 `config.agentid` 补 `agentid`
- 返回 `WeComCommonResponse`（含 `msgid` / `invaliduser` 等 extra 字段）

```python
# 组合：先拿 media_id，再发消息
upload = provider.media_api.media_upload("photo.png", media_type="image")
provider.message_send_api.message_send_image(upload.media_id, touser="Guolei")
```

---

### ContactUserAPI — 通讯录成员

官方文档：[90301](https://developer.work.weixin.qq.com/document/path/90301) · [90306](https://developer.work.weixin.qq.com/document/path/90306) · [90308](https://developer.work.weixin.qq.com/document/path/90308) · [90302](https://developer.work.weixin.qq.com/document/path/90302) · [90303](https://developer.work.weixin.qq.com/document/path/90303) · [90307](https://developer.work.weixin.qq.com/document/path/90307)

| 方法 | 官方文档 | 说明 |
|---|---|---|
| `user_get(userid)` | 90301 | 获取成员详情 |
| `user_list(department_id, fetch_child=0)` | 90306 | 获取部门成员**详细**列表 |
| `user_simplelist(department_id, fetch_child=1)` | 90308 | 获取部门成员**简化**列表 |
| `user_convert_to_openid(userid)` | 90302 | userid → openid |
| `user_convert_to_userid(openid)` | 90303 | openid → userid |
| `user_check_mobile(mobile)` | 90307 | 校验手机号是否已绑定企业 |

```python
resp = provider.contact_user_api.user_get("Guolei")
print(resp.name, resp.position, resp.department)  # 郭磊 IT工程师 [60]
```

---

### ContactDepartmentAPI — 通讯录部门

官方文档：[90210](https://developer.work.weixin.qq.com/document/path/90210) · [90213](https://developer.work.weixin.qq.com/document/path/90213)

| 方法 | 官方文档 | 说明 |
|---|---|---|
| `department_list(id=None)` | 90210 | 获取部门列表，`id=None` 时返回全部 |
| `department_get(id)` | 90213 | 获取部门详情 |

---

### ContactTagAPI — 通讯录标签

官方文档：[90216](https://developer.work.weixin.qq.com/document/path/90216) · [90217](https://developer.work.weixin.qq.com/document/path/90217)

| 方法 | 官方文档 | 说明 |
|---|---|---|
| `tag_list()` | 90216 | 获取全部标签 |
| `tag_get(tagid)` | 90217 | 获取标签下的成员列表 |

---

### WeComGroupRobotAPI — 群机器人 Webhook

官方文档：[91770 群机器人](https://developer.work.weixin.qq.com/document/path/91770)

| 方法 | 说明 |
|---|---|
| `webhook_send(payload)` | 底层 webhook 入口 |
| `webhook_send_text(content)` | 文本消息，支持 mentions |
| `webhook_send_markdown(content)` | Markdown 消息 |
| `webhook_send_markdown_v2(content)` | 增强版 Markdown（表格 / 图片 / 分割线） |
| `webhook_send_image(file_or_bytes, *, base64, md5)` | 图片消息 |
| `webhook_send_news(articles)` | 图文，1~8 条 |
| `webhook_send_file(file_or_media_id, *, media_id)` | 文件消息 |
| `webhook_send_voice(file_or_media_id, *, media_id)` | 语音消息 |
| `webhook_send_template_card(template_card)` | 模板卡片 |
| `webhook_upload_media(file, media_type)` | 上传群机器人临时素材 |

---

## 🗂️ Project Structure

```
py_wecom_sdk/
├── src/py_wecom_sdk/
│   ├── __init__.py                      # 包入口（仅导出 provider 子模块）
│   ├── _version.py                      # __version__ = "1.1.0"，供 pyproject.toml 动态读取
│   ├── provider.py                      # WeComAPIProvider：主入口，组装 5 个业务子 API
│   ├── utils/
│   │   ├── __init__.py
│   │   └── misc.py                      # read_file_bytes / compute_base64_md5 / build_multipart_file
│   └── core/
│       ├── __init__.py
│       ├── base/                        # 基础 HTTP / 配置 / 响应模型
│       │   ├── __init__.py
│       │   ├── api.py                   # WeComBaseAPI / WeComAPI + HTTP 方法 + token 管理 + context manager
│       │   ├── config.py                # WeComAPIConfig + 默认常量（base_url / timeout / gettoken）
│       │   ├── models.py                # WeComBaseResponse / WeComCommonResponse / WeComAccessTokenResponse
│       │   ├── cache.py                 # WeComAccessTokenBaseCache + diskcache / Redis 实现
│       │   └── exceptions.py            # WeComAPIError（errcode + errmsg）
│       ├── group_robot/                 # 群机器人 webhook（独立于主 Provider）
│       │   ├── __init__.py
│       │   ├── api.py                   # WeComGroupRobotAPI / WeComGroupRobotBaseAPI
│       │   └── config.py                # WeComGroupRobotAPIConfig（key / 提及 / 默认 URL）
│       ├── media/                       # 素材管理
│       │   ├── __init__.py
│       │   └── api.py                   # MediaAPI + MediaDownloadResult
│       ├── message/                     # 应用消息
│       │   ├── __init__.py
│       │   └── send_api.py              # MessageSendAPI（1 底层 + 9 便捷方法）
│       └── contact/                     # 通讯录（查询）
│           ├── __init__.py
│           ├── user_api.py              # ContactUserAPI（6 方法）
│           ├── department_api.py        # ContactDepartmentAPI（2 方法）
│           └── tag_api.py               # ContactTagAPI（2 方法）
├── tests/
│   ├── conftest.py                      # 仅负责 load_dotenv(.env)
│   ├── test_wecom_group_robot.py        # 群机器人（真实网络）
│   ├── test_wecom_media.py              # 素材上传下载（真实网络）
│   ├── test_wecom_message.py            # 应用消息发送（真实网络，接收人固定 Guolei）
│   └── test_wecom_contact.py            # 通讯录查询（真实网络）
├── .env.example                         # 凭证模板
├── pyproject.toml                       # PEP 621 元数据 + uv_build + ruff / mypy / pytest
├── uv.lock                              # uv 锁定依赖
└── README.md
```

**23 个源文件 / 5 个测试文件**，全部同步风格，无预留异步 / OA / 第三方应用等未实现模块。

---

## 🧪 Testing

### 1. 准备凭证

复制 `.env.example` 为 `.env` 并填写：

```env
WECOM_CORPID="wwXXXXXXXXXXXXXXXX"
WECOM_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
WECOM_AGENTID="1000002"
WECOM_GROUP_ROBOT_API_KEY="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
WECOM_TEST_USERID="Guolei"
```

### 2. 运行

```bash
# 安装开发依赖
uv sync --group dev

# 全部测试（真实网络请求）
uv run pytest tests/ -v -s

# 单模块
uv run pytest tests/test_wecom_contact.py -v -s
```

### 测试结果

```
==================== 50 passed in ~18s ====================
```

所有测试均带 `print` 输出，运行时可看到每个接口的真实返回值。

---

## 💡 Advanced

### Access Token 缓存

SDK 内置三种实现，均继承自抽象基类 `WeComAccessTokenBaseCache`（只需实现 `get` / `set`）：

| 实现 | 依赖 | 适用场景 |
|------|------|----------|
| `WeComAccessTokenDiskcacheCache` | `diskcache`（默认自带） | 单机 / 单进程，持久化到磁盘 |
| `WeComAccessTokenRedisCache` | `redis`（可选） | 多进程 / 分布式 / 容器化部署 |
| 自定义实现 | — | 继承 `WeComAccessTokenBaseCache` |

```python
from py_wecom_sdk.provider import WeComAPIProvider
from py_wecom_sdk.core.base.cache import (
    WeComAccessTokenBaseCache,
    WeComAccessTokenDiskcacheCache,
    WeComAccessTokenRedisCache,
)

# 默认 diskcache（零配置）
provider = WeComAPIProvider(WeComAPIConfig(
    corpid="ww_xxx", corpsecret="yyy", agentid=1000002,
))

# 显式 diskcache
provider = WeComAPIProvider(WeComAPIConfig(
    corpid="ww_xxx", corpsecret="yyy", agentid=1000002,
    access_token_cache=WeComAccessTokenDiskcacheCache(
        directory="/var/cache/py_wecom_sdk/token", timeout=60
    ),
))

# Redis 分布式缓存（需先 pip install py-wecom-sdk[redis]）
provider = WeComAPIProvider(WeComAPIConfig(
    corpid="ww_xxx", corpsecret="yyy", agentid=1000002,
    access_token_cache=WeComAccessTokenRedisCache("redis://localhost:6379/0"),
))

# 自定义
class MyCache(WeComAccessTokenBaseCache):
    def get(self, key: str) -> str | None: ...
    def set(self, key: str, value: str, ttl: float = 6900) -> None: ...
```

> 💡 access_token TTL 默认 **6900 秒**（官方 7200 秒提前 300 秒过期，避免边界问题）。

### 自定义 HTTP 客户端

```python
import httpx
from py_wecom_sdk.provider import WeComAPIProvider
from py_wecom_sdk.core.base.config import WeComAPIConfig

client = httpx.Client(
    base_url="https://qyapi.weixin.qq.com/",
    timeout=30.0,
    proxies={"https://": "http://proxy.example.com:8080"},
)
provider = WeComAPIProvider(WeComAPIConfig(
    corpid="ww_xxx", corpsecret="yyy", agentid=1000002,
), client=client)
```

### Context Manager

```python
# 显式 close
provider = WeComAPIProvider(config)
provider.refresh_access_token()
...
provider.close()

# 或 context manager 自动关闭
with WeComAPIProvider(config) as provider:
    provider.refresh_access_token()
    ...
```

### 错误处理

所有响应均为 `WeComCommonResponse`，两种统一处理方式：

```python
resp = provider.contact_user_api.user_get("not_exist")

# 方式 1：ok()
if resp.ok():
    print(resp.name)
else:
    print(f"errcode={resp.errcode}, errmsg={resp.errmsg}")

# 方式 2：raise_for_status() 抛 WeComAPIError
try:
    resp.raise_for_status()
except WeComAPIError as e:
    print(f"errcode={e.errcode}, errmsg={e.errmsg}")
```

### 导入路径

```python
# ✅ 推荐：从子模块导入
from py_wecom_sdk.provider import WeComAPIProvider
from py_wecom_sdk.core.base.config import WeComAPIConfig
from py_wecom_sdk.core.base.cache import WeComAccessTokenDiskcacheCache

# ✅ 也可以：先 import 子模块
import py_wecom_sdk
provider = py_wecom_sdk.provider.WeComAPIProvider(config)

# ❌ 不再支持：直接从包顶层导入
# from py_wecom_sdk import WeComAPIProvider  → ImportError
```

---

## 📖 License

[MIT](LICENSE) © guolei
