Metadata-Version: 2.3
Name: py-wecom-sdk
Version: 0.1.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: License :: OSI Approved :: MIT License
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: anyio>=4.16.0
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.14.3
Requires-Dist: diskcache>=5.6.0 ; extra == 'all'
Requires-Dist: redis>=5.0.0 ; extra == 'all'
Requires-Dist: diskcache>=5.6.0 ; extra == 'diskcache'
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: all
Provides-Extra: diskcache
Provides-Extra: redis
Description-Content-Type: text/markdown

# py_wecom_sdk

[![Python](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-MIT-green)](https://opensource.org/licenses/MIT)
[![httpx](https://img.shields.io/badge/httpx-0.28%2B-orange)](https://github.com/encode/httpx)
[![pydantic](https://img.shields.io/badge/pydantic-2.14%2B-emerald)](https://github.com/pydantic/pydantic)

企业微信（WeCom）开放接口的 Python SDK，基于 **httpx + pydantic v2**，**同步 / 异步统一封装**。

> 官方文档：<https://developer.work.weixin.qq.com/document/path/91770>

---

## ✨ 特性

- **同步 / 异步统一 API** — `GroupRobotAPI` 与 `GroupRobotAsyncAPI` 接口完全一致，只需替换 import
- **类型安全** — pydantic v2 自动校验所有请求 / 响应，Mypy strict 模式 100% 通过
- **零魔法基类** — 同步 / 异步共享 `_BaseAPI`，初始化和资源管理逻辑一次实现
- **丰富的消息类型** — 文本、Markdown、Markdown V2、图片、图文、文件、语音、模板卡片
- **素材上传支持** — `upload_media()` 统一处理文件 / 语音上传并返回 `media_id`
- **HTTP 连接池管理** — `close()` / `with` / `async with` 三种方式释放连接
- **企业级依赖** — httpx（encode 维护）+ pydantic v2（比 v1 快 5-50 倍）

## 📦 安装

### 使用 pip

```bash
pip install py-wecom-sdk
```

### 使用 uv（推荐）

```bash
uv add py-wecom-sdk
```

### 安装可选依赖

```bash
# DiskCache 本地缓存后端
uv add "py-wecom-sdk[diskcache]"

# Redis 分布式缓存后端
uv add "py-wecom-sdk[redis]"

# 全部可选依赖
uv add "py-wecom-sdk[all]"
```

## 🚀 快速开始

### 同步客户端

```python
from py_wecom_sdk import WeComAPIProvider

api = WeComAPIProvider.group_robot_api(key="YOUR_WEBHOOK_KEY")

# 发送文本
resp = api.send_text("Hello, WeCom!")
assert resp.ok

# 发送 Markdown
api.send_markdown("## 标题\n> <font color='info'>重要通知</font>")

# 发送图文
api.send_news([{"title": "标题", "url": "https://example.com"}])

# 发送文件（需先上传）
uploaded = api.upload_media("/path/to/file.pdf", media_type="file")
api.send_file(uploaded.media_id)

# 释放连接池
api.close()
# 或使用上下文管理器：
# with WeComAPIProvider.group_robot_api(key="YOUR_KEY") as api: ...
```

### 异步客户端

```python
import asyncio
from py_wecom_sdk import WeComAPIProvider

async def main():
    async with WeComAPIProvider.group_robot_async_api(key="YOUR_WEBHOOK_KEY") as api:
        resp = await api.send_text("Hello from async!")
        assert resp.ok
        await api.send_markdown_v2("**Markdown V2** 也很好用")
        uploaded = await api.upload_media(b"fake data", filename="demo.txt", media_type="file")
        await api.send_file(uploaded.media_id)

asyncio.run(main())
```

### 通过原始 dict 发送任意消息类型

所有便捷方法底层都调用 `send(payload)`，你可以直接传入符合企业微信协议的字典：

```python
api.send({"msgtype": "text", "text": {"content": "原始 dict", "mentioned_list": ["userid1"]}})
```

## 📖 功能清单

### `GroupRobotAPI` / `GroupRobotAsyncAPI`

| 方法 | 功能 | 官方文档 |
|------|------|----------|
| `send(payload)` | 发送任意类型消息（原始 dict） | — |
| `send_text(content, mentioned_list, mentioned_mobile_list)` | 文本消息，支持 @ 指定成员 | [文本类型](https://developer.work.weixin.qq.com/document/path/91770#文本类型) |
| `send_markdown(content)` | Markdown 消息 | [Markdown 类型](https://developer.work.weixin.qq.com/document/path/91770#markdown类型) |
| `send_markdown_v2(content)` | Markdown V2 消息 | [Markdown V2](https://developer.work.weixin.qq.com/document/path/91770#markdown-v2类型) |
| `send_image(base64, md5)` | 图片消息（限 2MB，JPG / PNG） | [图片类型](https://developer.work.weixin.qq.com/document/path/91770#图片类型) |
| `send_news(articles)` | 图文消息（1-8 条） | [图文类型](https://developer.work.weixin.qq.com/document/path/91770#图文类型) |
| `send_file(media_id)` | 文件消息（需先上传） | [文件类型](https://developer.work.weixin.qq.com/document/path/91770#文件类型) |
| `send_voice(media_id)` | 语音消息（需先上传） | [语音类型](https://developer.work.weixin.qq.com/document/path/91770#语音类型) |
| `send_template_card(card)` | 模板卡片（text_notice / news_notice） | [模板卡片](https://developer.work.weixin.qq.com/document/path/91770#模版卡片类型) |
| `upload_media(media, filename, media_type)` | 上传文件 / 语音素材，返回 `media_id` | [文件上传接口](https://developer.work.weixin.qq.com/document/path/91770#文件上传接口) |

### `send_text` 默认 @ 配置

实例化时可传入默认 @ 列表，每次 `send_text` 会自动合并：

```python
api = WeComAPIProvider.group_robot_api(
    key="YOUR_KEY",
    mentioned_list=["userid1"],       # 每次自动 @ userid1
    mentioned_mobile_list=["13800138000"],
)
api.send_text("重要通知", mentioned_list=["userid2"])  # 合并 @ userid1 + userid2
```

### `UploadMediaResponse.ok` 多一层校验

上传响应除了业务成功（`errcode == 0`），还额外校验 `media_id` 非空：

```python
uploaded = api.upload_media("/path/to/file.pdf", media_type="file")
if not uploaded.ok:
    print(f"上传失败：errcode={uploaded.errcode}, errmsg={uploaded.errmsg}")
```

## 🏗️ 项目结构

```
py_wecom_sdk/
├── pyproject.toml                  # 项目配置（PEP 621 + Ruff + Mypy + Pytest）
├── LICENSE                         # MIT License
├── README.md                       # 中文文档
├── README.en.md                    # 英文文档
├── .python-version                 # 锁定 Python 版本（3.10）
├── .gitignore
├── .env.example                    # 示例 .env 文件
│
├── src/
│   └── py_wecom_sdk/               # 包根目录（src-layout）
│       ├── __init__.py             # 导出 WeComAPIProvider
│       ├── provider.py             # APIProvider 统一入口
│       └── core/
│           ├── group_robot/        # 群机器人模块 ✅ 已实现
│           │   ├── __init__.py     # 公共导出
│           │   ├── _api.py         # GroupRobotAPI + GroupRobotAsyncAPI + _BaseAPI
│           │   └── _models.py      # SendResponse / UploadMediaResponse / BaseResponse
│           └── token/              # access_token 模块 🚧 预留
│               ├── __init__.py
│               ├── _client.py
│               └── _models.py
│
├── examples/
│   └── group_robot.py              # 群机器人完整示例（同步 + 异步 + 多消息类型）
│
└── tests/
    ├── conftest.py
    └── test_group_robot.py         # 单元测试（respx mock）
```

## 🛠️ 开发

### 环境准备

```bash
# 克隆仓库
git clone https://gitee.com/guolei19850528/py_wecom_sdk.git
cd py_wecom_sdk

# 安装 uv（包管理器）
curl -LsSf https://astral.sh/uv/install.sh | sh

# 创建虚拟环境 + 安装全部依赖（含 dev）
uv sync --group dev
```

### 代码质量

```bash
# Ruff：lint（修复） + format
uv run ruff check --fix src tests
uv run ruff format src tests

# Mypy（strict 模式）
uv run mypy src
```

### 测试

```bash
# 运行全部测试（离线，使用 respx mock）
uv run pytest

# 运行需要真实网络的集成测试
cp .env.example .env
# 编辑 .env 填入 WECOM_GROUP_ROBOT_API_KEY
uv run pytest -m real_network
```

### 示例运行

```bash
# 编辑 .env 填入机器人 key
cp .env.example .env
vim .env

# 同步发送
uv run python examples/group_robot.py

# 异步发送 + 图片 / 文件 / 语音
uv run python examples/group_robot.py --async --image ./test.png --file ./report.pdf
```

### 构建发布

```bash
# 构建 wheel + sdist
uv build

# 发布到 PyPI / Gitee
uv publish --repository gitee
```

## 📋 路线图

- [x] 群机器人模块（group_robot）
  - [x] 同步 / 异步统一 API
  - [x] 全部 9 种消息类型
  - [x] 素材上传接口
  - [x] pydantic 数据模型校验
- [ ] access_token 模块（token）
  - [ ] 缓存后端：内存 / DiskCache / Redis
  - [ ] 自动刷新 + 并发去重
- [ ] 通讯录模块（contact）
- [ ] 消息推送模块（message）

## 📄 许可证

本项目基于 **MIT License** 开源，详见 [LICENSE](LICENSE)。

## 📎 相关链接

- [企业微信开发者中心](https://developer.work.weixin.qq.com/)
- [群机器人接口文档](https://developer.work.weixin.qq.com/document/path/91770)
- [httpx 官方仓库](https://github.com/encode/httpx)
- [pydantic v2 文档](https://docs.pydantic.dev/)
- [uv 官方仓库](https://github.com/astral-sh/uv)
