Metadata-Version: 2.3
Name: py-wecom-sdk
Version: 1.0.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: anyio>=4.16.0
Requires-Dist: diskcache>=5.6.3
Requires-Dist: httpx>=0.28.1
Requires-Dist: pydantic>=2.14.3
Requires-Dist: diskcache ; extra == 'all'
Requires-Dist: redis ; extra == 'all'
Requires-Dist: diskcache>=5.6.3 ; 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

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

[![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)
[![Build](https://img.shields.io/badge/build-uv_build-41B883.svg)](https://docs.astral.sh/uv/)
[![Lint](https://img.shields.io/badge/lint-ruff-FFA94D.svg)](https://docs.astral.sh/ruff/)

---

## ✨ Features

- 🔀 **同步 / 异步一体** —— 同一接口签名，`BaseAPI` 用 `httpx.Client`，`BaseAsyncAPI` 用 `httpx.AsyncClient`
- 📦 **Provider 聚合入口** —— `WeComAPIProvider` / `WeComAsyncAPIProvider` 持有全部子域，子域属性 `_api` 后缀
- 🧩 **模块化设计** —— `contact` / `message` / `media` / `group_robot` / `oa.*` 各自独立，按需引入
- 🎯 **强类型响应** —— 所有响应均由 `pydantic` v2 `CommonResponse` 校验，属性 / 字段访问 IDE 友好
- 🔐 **可插拔 Token 缓存** —— 内置内存 / `diskcache` / `redis` 三种实现，可自定义扩展
- 📝 **完整类型标注** —— `mypy strict` 模式通过
- 🧪 **真实集成测试** —— 56 passed / 17 skipped（无权限），覆盖所有已实现接口
- 🌏 **国内友好** —— 默认 `https://qyapi.weixin.qq.com/`，可自定义 `base_url`

---

## 📦 Installation

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

# pip
pip install py-wecom-sdk

# 包含 diskcache 缓存后端
uv add py-wecom-sdk[diskcache]

# 包含 redis 缓存后端
uv add py-wecom-sdk[redis]
```

**Python ≥ 3.10**。依赖仅 `httpx`、`pydantic`、`anyio`。

---

## 🚀 Quick Start

### 同步

```python
from py_wecom_sdk import WeComAPIProvider

api = WeComAPIProvider(
    corpid="wwXXXXXXXXXXXXXXXX",
    corpsecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    agentid=1000002,
)

# 发送应用消息
resp = api.message_api.message_send(
    {
        "touser": "Guolei",
        "msgtype": "text",
        "agentid": 1000002,
        "text": {"content": "Hello WeCom SDK!"},
    }
)
print(resp.ok, resp.errcode)  # True 0

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

api.close()
```

### 异步

```python
import asyncio
from py_wecom_sdk import WeComAsyncAPIProvider


async def main():
    api = WeComAsyncAPIProvider(
        corpid="wwXXXXXXXXXXXXXXXX",
        corpsecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
        agentid=1000002,
    )
    resp = await api.message_api.message_send(
        {
            "touser": "Guolei",
            "msgtype": "markdown",
            "agentid": 1000002,
            "markdown": {"content": "## Hello\n> from async"},
        }
    )
    await api.close()


asyncio.run(main())
```

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

```python
from py_wecom_sdk import WeComGroupRobotAPI

api = WeComGroupRobotAPI(key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")

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

with api:
    # 上传文件 → 发送文件
    uploaded = api.webhook_upload_media(b"file content", filename="report.txt")
    api.webhook_send_file(uploaded.media_id)
```

---

## 📚 Subdomains

Provider 构造函数签名与 `BaseAPI` / `BaseAsyncAPI` **完全一致**：

```python
WeComAPIProvider(
    corpid=None,
    corpsecret=None,
    agentid=None,
    access_token_cache=None,  # BaseAccessTokenCache 实例
    base_url="https://qyapi.weixin.qq.com/",
    timeout=60.0,  # float | (connect, read, write, pool)
    client=None,  # 自定义 httpx.Client
    client_kwargs=None,  # 未传 client 时的创建参数
)
```

子域属性统一以 `_api` 结尾：

| 属性 | 模块 | 官方文档 |
|---|---|---|
| `provider.contact_api` | 通讯录 | [90193](https://developer.work.weixin.qq.com/document/path/90193) |
| `provider.message_api` | 应用消息 | [90236](https://developer.work.weixin.qq.com/document/path/90236) |
| `provider.media_api` | 素材管理 | [91738](https://developer.work.weixin.qq.com/document/path/91738) |
| `provider.oa_wedoc_api` | 文档 / 表格 / 多维表格 | [97892](https://developer.work.weixin.qq.com/document/path/97892) |
| `provider.oa_exmail_api` | 邮件 | [95486](https://developer.work.weixin.qq.com/document/path/95486) |
| `provider.oa_schedule_api` | 日程 | [93624](https://developer.work.weixin.qq.com/document/path/93624) |

### 已实现接口统计

| 模块 | 同步 | 异步 | 说明 |
|---|---|---|---|
| contact | ~36 | ✅ 全部 | 部门 / 标签 / 成员 CRUD + 异步导入导出 |
| message | ✅ 6 | ✅ 6 | 消息发送 / 撤回 / 群聊创建更新获取发送 |
| media | ✅ 4 | ✅ 4 | 临时 / 永久素材上传、下载、JSSDK ticket |
| group_robot | ✅ 11 | ✅ 11 | 所有消息类型 + 文件上传 |
| oa.wedoc | ~35 | ✅ 35 | 文档 / 表格 / 多维表格完整 API |
| oa.exmail | ✅ 5 | ✅ 5 | 发送邮件、查询收件箱、管理邮箱账号 |
| oa.schedule | ✅ 11 | ✅ 11 | 日历 + 日程完整 CRUD |

### 方法命名规则

所有请求方法遵循 `/cgi-bin/<seg1>/<seg2>` → `<seg1>_<seg2>` 映射：

```
/cgi-bin/user/simplelist         → user_simplelist()
/cgi-bin/tag/addtagusers         → tag_addtagusers()
/cgi-bin/oa/calendar/add         → oa_calendar_add()
/cgi-bin/exmail/app/compose_send → exmail_app_compose_send()
/cgi-bin/webhook/send            → webhook_send()        # 群机器人 webhook_ 前缀
/cgi-bin/webhook/upload_media    → webhook_upload_media()
```

---

## 🗂️ Project Structure

```
py_wecom_sdk/
├── src/py_wecom_sdk/
│   ├── __init__.py                  # 包导出（Provider 入口）
│   ├── provider.py                  # WeComAPIProvider / WeComAsyncAPIProvider
│   ├── utils/
│   │   └── __init__.py              # build_multipart_file() 公共工具
│   └── core/
│       ├── base/
│       │   ├── _api.py              # BaseAPI / BaseAsyncAPI + Token 缓存
│       │   └── _models.py           # CommonResponse / AccessTokenResponse
│       ├── contact/                 # 通讯录 API
│       ├── message/                  # 应用消息 API
│       ├── media/                    # 素材管理 API
│       ├── group_robot/              # 群机器人 Webhook API（webhook_ 前缀）
│       └── oa/
│           ├── wedoc/               # 文档 / 表格 / 多维表格 API
│           ├── exmail/               # 邮件 API
│           └── schedule/             # 日程 API
├── tests/
│   ├── conftest.py                  # .env 加载 + 限流保护 fixture
│   ├── test_base.py                 # Provider / access_token
│   ├── test_contact.py              # 通讯录（11 同步 + 12 异步）
│   ├── test_group_robot.py          # 群机器人（10 同步 + 10 异步）
│   ├── test_media.py                # 素材上传下载
│   ├── test_message.py              # 应用消息发送撤回
│   ├── test_oa_exmail.py            # OA 邮件
│   └── test_oa_schedule.py          # OA 日程
├── examples/
│   ├── contact.py                   # 通讯录查询 + CRUD 示例
│   ├── group_robot.py                # 群机器人全消息类型示例
│   ├── media.py                      # 素材上传 / 永久图片 / JSSDK ticket
│   ├── message.py                    # 应用消息发送示例
│   ├── oa_exmail.py                  # OA 邮件发送示例
│   └── oa_schedule.py                # OA 日历 + 日程完整链路示例
├── .env.example                     # 凭证模板
├── pyproject.toml                   # PEP 621 项目元数据 + ruff / mypy / pytest
└── README.md
```

---

## 🧪 Testing

所有集成测试位于 `tests/`，基于 pytest + pytest-asyncio。

### 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_CONTACT_CORPID=${WECOM_CORPID}
WECOM_CONTACT_CORPSECRET=${WECOM_SECRET}
WECOM_OA_CORPID=${WECOM_CORPID}
WECOM_OA_CORPSECRET=${WECOM_SECRET}
WECOM_TEST_USERID="Guolei"
WECOM_TEST_EMAIL="you@example.com"
```

### 2. 运行全部测试

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

# 执行全部测试
uv run pytest tests/ -v

# 执行单个模块
uv run pytest tests/test_contact.py -v

# 跳过需要真实网络的测试（没有 .env 也能跑）
uv run pytest tests/ -v -k "not real_network"
```

### 测试结果

```
================== 56 passed, 17 skipped in 02:15 ==================
```

- **56 passed** — 所有已授权接口真实调用通过
- **17 skipped** — 因 `errcode=48002 api forbidden` 自动跳过（未授权接口在企业微信后台开启权限后自动转为 passed）
- 每个用例后自动 1.5s 限流保护，避免触发企业微信 `45009 API 频率超限`

---

## 💡 Advanced

### 自定义 Access Token 缓存

```python
from py_wecom_sdk import WeComAPIProvider
from py_wecom_sdk.core.base import RedisAccessTokenCache, DiskcacheAccessTokenCache

# 本地文件 / SQLite 缓存（默认）
provider = WeComAPIProvider(
    corpid="...",
    corpsecret="...",
    access_token_cache=DiskcacheAccessTokenCache(),
)

# 分布式 Redis 缓存
provider = WeComAPIProvider(
    corpid="...",
    corpsecret="...",
    access_token_cache=RedisAccessTokenCache(redis_url="redis://localhost:6379/0"),
)
```

### 自定义 HTTP 客户端

```python
import httpx
from py_wecom_sdk import WeComAPIProvider

client = httpx.Client(
    base_url="https://qyapi.weixin.qq.com/",
    timeout=30.0,
    proxies={"https://": "http://proxy.example.com:8080"},
    headers={"X-Custom": "value"},
)
provider = WeComAPIProvider(corpid="...", corpsecret="...", client=client)
```

### 使用独立子域客户端（不通过 Provider）

```python
from py_wecom_sdk.core.base import BaseAPI
from py_wecom_sdk.core.contact import ContactAPI

base = BaseAPI(corpid="...", corpsecret="...")
contact = ContactAPI(base)
resp = contact.department_list()
```

---

## 📋 TODO & Roadmap

- [ ] Wedoc（文档 / 表格 / 多维表格）真实集成测试（需应用授权）
- [ ] 支持企业微信第三方应用（SuiteTicket / AuthCode）
- [ ] 支持服务商（ServiceProvider）代开发调用
- [ ] Webhook 回调事件验证（消息接收、变更通知）
- [ ] 发布至 PyPI

---

## 📖 License

[MIT](LICENSE) © guolei
