py-wecom-toolkit 4.2.4__tar.gz → 5.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {py_wecom_toolkit-4.2.4 → py_wecom_toolkit-5.0.0}/.gitignore +1 -5
- py_wecom_toolkit-5.0.0/PKG-INFO +338 -0
- py_wecom_toolkit-5.0.0/README.md +279 -0
- py_wecom_toolkit-5.0.0/pyproject.toml +152 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/__init__.py +173 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/client.py +194 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/__init__.py +78 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/auth.py +152 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/base.py +280 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/cache.py +239 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/config.py +44 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/crypto.py +115 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/exceptions.py +136 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/models.py +93 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/core/utils.py +64 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/__init__.py +3 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/contact/__init__.py +17 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/contact/client.py +186 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/media/__init__.py +3 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/media/client.py +165 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/message/__init__.py +3 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/message/client.py +396 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/oauth/__init__.py +3 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/oauth/client.py +99 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/token/__init__.py +3 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/token/client.py +42 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/webhook/__init__.py +7 -0
- py_wecom_toolkit-5.0.0/src/py_wecom_toolkit/services/webhook/client.py +610 -0
- py_wecom_toolkit-4.2.4/PKG-INFO +0 -246
- py_wecom_toolkit-4.2.4/README.md +0 -190
- py_wecom_toolkit-4.2.4/pyproject.toml +0 -184
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/__init__.py +0 -8
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/__init__.py +0 -45
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/_caches.py +0 -95
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/_clients.py +0 -241
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/_models.py +0 -38
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/materials/__init__.py +0 -21
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/materials/_clients.py +0 -420
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/materials/_models.py +0 -49
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/messages/__init__.py +0 -85
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/messages/_clients.py +0 -186
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/server/messages/_msgtypes.py +0 -159
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/webhook/__init__.py +0 -68
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/webhook/_clients.py +0 -671
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/webhook/_models.py +0 -43
- py_wecom_toolkit-4.2.4/src/py_wecom_toolkit/webhook/_msgtypes.py +0 -225
- {py_wecom_toolkit-4.2.4 → py_wecom_toolkit-5.0.0}/LICENSE +0 -0
- {py_wecom_toolkit-4.2.4 → py_wecom_toolkit-5.0.0}/src/py_wecom_toolkit/py.typed +0 -0
|
@@ -94,9 +94,6 @@ ipython_config.py
|
|
|
94
94
|
# install all needed dependencies.
|
|
95
95
|
#Pipfile.lock
|
|
96
96
|
|
|
97
|
-
# uv
|
|
98
|
-
uv.lock
|
|
99
|
-
|
|
100
97
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
|
101
98
|
__pypackages__/
|
|
102
99
|
|
|
@@ -140,6 +137,5 @@ dmypy.json
|
|
|
140
137
|
# Cython debug symbols
|
|
141
138
|
cython_debug/
|
|
142
139
|
.DS_Store
|
|
143
|
-
.idea
|
|
144
140
|
.vscode
|
|
145
|
-
.
|
|
141
|
+
uv.lock
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: py-wecom-toolkit
|
|
3
|
+
Version: 5.0.0
|
|
4
|
+
Summary: 企业微信(WeCom)官方 API 现代化 Python 工具包,支持同步 / 异步全服务端接口
|
|
5
|
+
Project-URL: Homepage, https://gitee.com/guolei19850528/py_wecom_toolkit
|
|
6
|
+
Project-URL: Repository, https://gitee.com/guolei19850528/py_wecom_toolkit
|
|
7
|
+
Author-email: Guo Lei <174000902@qq.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: WeCom,wecom-sdk,企业微信,企业微信API
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Communications :: Chat
|
|
22
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Classifier: Typing :: Typed
|
|
25
|
+
Requires-Python: >=3.10
|
|
26
|
+
Requires-Dist: cryptography>=42.0.0
|
|
27
|
+
Requires-Dist: diskcache>=5.6.0
|
|
28
|
+
Requires-Dist: httpx>=0.27.0
|
|
29
|
+
Requires-Dist: pydantic>=2.7.0
|
|
30
|
+
Requires-Dist: pyjwt>=2.8.0
|
|
31
|
+
Requires-Dist: redis>=5.0.0
|
|
32
|
+
Provides-Extra: all
|
|
33
|
+
Requires-Dist: cache; extra == 'all'
|
|
34
|
+
Requires-Dist: mypy>=1.13.0; extra == 'all'
|
|
35
|
+
Requires-Dist: pre-commit>=4.0.0; extra == 'all'
|
|
36
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'all'
|
|
37
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
|
|
38
|
+
Requires-Dist: pytest>=8.3.0; extra == 'all'
|
|
39
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == 'all'
|
|
40
|
+
Requires-Dist: respx>=0.21.0; extra == 'all'
|
|
41
|
+
Requires-Dist: ruff>=0.9.0; extra == 'all'
|
|
42
|
+
Provides-Extra: cache
|
|
43
|
+
Requires-Dist: diskcache>=5.6.0; extra == 'cache'
|
|
44
|
+
Requires-Dist: redis>=5.0.0; extra == 'cache'
|
|
45
|
+
Provides-Extra: dev
|
|
46
|
+
Requires-Dist: cache; extra == 'dev'
|
|
47
|
+
Requires-Dist: mypy>=1.13.0; extra == 'dev'
|
|
48
|
+
Requires-Dist: pre-commit>=4.0.0; extra == 'dev'
|
|
49
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
|
|
50
|
+
Requires-Dist: ruff>=0.9.0; extra == 'dev'
|
|
51
|
+
Provides-Extra: test
|
|
52
|
+
Requires-Dist: cache; extra == 'test'
|
|
53
|
+
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'test'
|
|
54
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
|
|
55
|
+
Requires-Dist: pytest>=8.3.0; extra == 'test'
|
|
56
|
+
Requires-Dist: python-dotenv>=1.0.0; extra == 'test'
|
|
57
|
+
Requires-Dist: respx>=0.21.0; extra == 'test'
|
|
58
|
+
Description-Content-Type: text/markdown
|
|
59
|
+
|
|
60
|
+
# py-wecom-toolkit
|
|
61
|
+
|
|
62
|
+
企业微信(WeCom / Work / WeChat Work)官方 API 现代化 Python 工具包 —— 类型安全、全量同步 / 异步、零配置自动 Token 管理。
|
|
63
|
+
|
|
64
|
+
[](https://www.python.org/)
|
|
65
|
+
[](https://www.python-httpx.org/)
|
|
66
|
+
[](https://docs.pydantic.dev/)
|
|
67
|
+
[](./LICENSE)
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## ✨ 特性
|
|
72
|
+
|
|
73
|
+
| 能力 | 说明 |
|
|
74
|
+
|------|------|
|
|
75
|
+
| **完整 API** | 覆盖群机器人、应用消息、素材、通讯录、网页授权、回调加解密 |
|
|
76
|
+
| **同步 + 异步** | 每个服务一对 `Service` / `AsyncService`,API 签名完全一致 |
|
|
77
|
+
| **自动 Token** | 默认 `DiskTokenCache` 持久化(跨重启复用);Redis / Memory 可切换 |
|
|
78
|
+
| **错误分层** | `APIError` 按 errcode 自动细分(TokenExpired / RateLimit / NoPrivilege 等) |
|
|
79
|
+
| **类型安全** | Pydantic v2 响应建模 + mypy strict(disallow_untyped_defs / warn_return_any) |
|
|
80
|
+
| **现代化** | Python 3.10+,`Self` / `X \| Y` 联合类型 / `TypeAlias` / `populate_by_name` |
|
|
81
|
+
| **零配置** | `uv add py-wecom-toolkit` 即用:默认 DiskTokenCache 写 `~/.py_wecom_toolkit/cache` |
|
|
82
|
+
|
|
83
|
+
## 📦 安装
|
|
84
|
+
|
|
85
|
+
推荐使用 [uv](https://docs.astral.sh/uv/)(极速 Python 包管理器):
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
# 基础安装(默认 DiskTokenCache)
|
|
89
|
+
uv add py-wecom-toolkit
|
|
90
|
+
|
|
91
|
+
# 含 Redis 分布式缓存
|
|
92
|
+
uv add "py-wecom-toolkit[cache]"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
使用 pip 亦可:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
pip install py-wecom-toolkit
|
|
99
|
+
pip install py-wecom-toolkit[cache] # 额外安装 redis
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
开发模式:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
git clone <your-repo>
|
|
106
|
+
cd py_wecom_toolkit
|
|
107
|
+
uv sync # 创建 venv + 安装依赖 + 安装本包
|
|
108
|
+
uv run pytest tests -v
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## 🚀 五分钟上手
|
|
112
|
+
|
|
113
|
+
### 群机器人(独立,仅需 webhook key)
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from py_wecom_toolkit import WebhookClient
|
|
117
|
+
|
|
118
|
+
with WebhookClient(
|
|
119
|
+
key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
120
|
+
mentioned_list=["@all"], # 默认每次都 @ 所有人
|
|
121
|
+
) as wb:
|
|
122
|
+
wb.send_text("你好,来自 py-wecom-toolkit @all")
|
|
123
|
+
wb.send_markdown("**重要通知**\n> 生产环境告警")
|
|
124
|
+
wb.send_file(upload["media_id"]) # 先 upload_media 再 send_file
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
### 服务端应用(自动 token 缓存)
|
|
128
|
+
|
|
129
|
+
```python
|
|
130
|
+
from py_wecom_toolkit import WeCom
|
|
131
|
+
|
|
132
|
+
with WeCom(
|
|
133
|
+
corpid="wx...", # 企业 ID
|
|
134
|
+
corpsecret="...", # 应用 Secret
|
|
135
|
+
agentid=1000002, # 应用 AgentId
|
|
136
|
+
) as client:
|
|
137
|
+
|
|
138
|
+
# 发消息
|
|
139
|
+
client.message.send_text("hello", touser="@all")
|
|
140
|
+
client.message.send_markdown("**md**\n> 支持 Markdown 语法", touser="@all")
|
|
141
|
+
client.message.send_textcard(title="标题", description="正文",
|
|
142
|
+
url="https://...", btntxt="查看",
|
|
143
|
+
agentid=1000002, touser="@all")
|
|
144
|
+
client.message.send_news(articles=[{...}], agentid=1000002, touser="@all")
|
|
145
|
+
|
|
146
|
+
# 素材(上传拿到 media_id → 发送)
|
|
147
|
+
media = client.media.upload_media(b"content", media_type="file",
|
|
148
|
+
filename="a.txt")
|
|
149
|
+
client.message.send_file(media_id=media.media_id, agentid=1000002)
|
|
150
|
+
|
|
151
|
+
# 通讯录
|
|
152
|
+
zhangsan = client.user.get("zhangsan")
|
|
153
|
+
dept = client.department.list()
|
|
154
|
+
tags = client.tag.list_tags()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### 异步(FastAPI / aiohttp)
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
from py_wecom_toolkit import AsyncWeCom
|
|
161
|
+
|
|
162
|
+
async def handler():
|
|
163
|
+
async with AsyncWeCom(corpid="wx...", corpsecret="...") as wc:
|
|
164
|
+
await wc.message.send_text("[async] 异步消息", agentid=1000002)
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## 🏗️ 架构总览
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
py_wecom_toolkit/
|
|
171
|
+
├── client.py WeCom / AsyncWeCom 顶层组合客户端
|
|
172
|
+
├── core/ 底层基础设施(不直接使用)
|
|
173
|
+
│ ├── auth.py TokenManager / AsyncTokenManager(缓存 + 校验 + 刷新)
|
|
174
|
+
│ ├── base.py BaseClient / AsyncBaseClient(httpx + token 注入 + 错误转换)
|
|
175
|
+
│ ├── cache.py 三种缓存实现 + TokenCache Protocol + make_cache_key
|
|
176
|
+
│ ├── config.py ClientConfig dataclass
|
|
177
|
+
│ ├── crypto.py MessageCrypto(AES-GCM 加解密 + 签名校验)
|
|
178
|
+
│ ├── exceptions.py APIError 按 errcode 自动细分的异常族
|
|
179
|
+
│ ├── models.py Pydantic v2 响应模型
|
|
180
|
+
│ └── utils.py join_recipients / prepare_file_input
|
|
181
|
+
└── services/ 业务服务层(全部通过 WeCom().xxx 访问)
|
|
182
|
+
├── webhook/ 群机器人(独立,不需要 token)
|
|
183
|
+
├── token/ access_token 管理 + get_api_domain_ip
|
|
184
|
+
├── message/ 9 种应用消息类型
|
|
185
|
+
├── media/ 临时素材 / 永久图片
|
|
186
|
+
├── contact/ User / Department / Tag 全 CRUD
|
|
187
|
+
└── oauth/ 网页授权 + 回调加解密(crypto 工具类单独导出)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
### Token 缓存
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from py_wecom_toolkit import WeCom, DiskTokenCache, RedisTokenCache, MemoryTokenCache
|
|
194
|
+
|
|
195
|
+
# 默认(磁盘持久化,跨重启复用)
|
|
196
|
+
WeCom(corpid=..., corpsecret=...)
|
|
197
|
+
|
|
198
|
+
# 分布式(多进程 / K8s 多副本)
|
|
199
|
+
WeCom(..., cache=RedisTokenCache(host="redis.example.com", port=6379))
|
|
200
|
+
|
|
201
|
+
# 零依赖内存(一次性脚本)
|
|
202
|
+
WeCom(..., cache=MemoryTokenCache())
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
统一缓存 key 格式:`py_wecom_toolkit:{corpid}`(不含 corpsecret,同一企业下不同应用 Secret 共享 token)。
|
|
206
|
+
|
|
207
|
+
### 异常体系
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
from py_wecom_toolkit import APIError, RateLimitError, TokenExpiredError
|
|
211
|
+
|
|
212
|
+
with WeCom(...) as wc:
|
|
213
|
+
try:
|
|
214
|
+
wc.message.send_text("hello", agentid=1000002, touser="@all")
|
|
215
|
+
except TokenExpiredError:
|
|
216
|
+
# 实际使用很少遇到 —— BaseClient 会在 42001 时自动 refresh 再重试一次
|
|
217
|
+
wc.token.refresh()
|
|
218
|
+
except RateLimitError as e:
|
|
219
|
+
# 45009 限频 —— 指数退避重试
|
|
220
|
+
log.warning(f"限频 errcode={e.errcode}")
|
|
221
|
+
except APIError as e:
|
|
222
|
+
# 兜底:所有业务层错误
|
|
223
|
+
log.error(f"API errcode={e.errcode} errmsg={e.errmsg} raw={e.raw}")
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
### 回调加解密
|
|
227
|
+
|
|
228
|
+
```python
|
|
229
|
+
from py_wecom_toolkit import MessageCrypto, verify_signature
|
|
230
|
+
|
|
231
|
+
crypto = MessageCrypto(
|
|
232
|
+
token="回调 Token",
|
|
233
|
+
encoding_aes_key="EncodingAESKey",
|
|
234
|
+
corp_id="wx...",
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
# GET: 解密 echostr
|
|
238
|
+
plain = crypto.decrypt_message(
|
|
239
|
+
echostr_encrypted, msg_signature, timestamp, nonce
|
|
240
|
+
)
|
|
241
|
+
# 把 plain 原样返回给企业微信
|
|
242
|
+
|
|
243
|
+
# POST: 解密消息推送
|
|
244
|
+
plain_xml = crypto.decrypt_message(
|
|
245
|
+
encrypted_xml_body, msg_signature, timestamp, nonce
|
|
246
|
+
)
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
## 📁 完整示例
|
|
250
|
+
|
|
251
|
+
[examples/](./examples) 目录下 5 个可独立运行的示例,覆盖所有核心能力:
|
|
252
|
+
|
|
253
|
+
| 文件 | 场景 | 依赖 |
|
|
254
|
+
|------|------|------|
|
|
255
|
+
| `01_webhook_basic.py` | 群机器人 9 种消息类型 | WEBHOOK_KEY |
|
|
256
|
+
| `02_wecom_basic.py` | 服务端应用消息 / 素材 / 通讯录 | CORPID / CORPSECRET / AGENTID |
|
|
257
|
+
| `03_cache_backends.py` | Disk / Memory / Redis 三种缓存切换 | 无(演示) |
|
|
258
|
+
| `04_error_handling.py` | APIError 子类 + 生产级 try/except 模板 | 无(演示) |
|
|
259
|
+
| `05_oauth_callback.py` | 网页授权 URL 构造 + 回调加解密 | 无(演示) |
|
|
260
|
+
|
|
261
|
+
运行:
|
|
262
|
+
|
|
263
|
+
```bash
|
|
264
|
+
cp tests/.env.example tests/.env # 填入真实凭证
|
|
265
|
+
uv run python examples/02_wecom_basic.py
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## 🧪 测试
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
# 全量(真实网络请求,未配置凭证的会自动 skip,退出码 0)
|
|
272
|
+
cp tests/.env.example tests/.env # 填入 WEBHOOK_KEY / CORPID / CORPSECRET / AGENTID
|
|
273
|
+
uv run pytest tests -v
|
|
274
|
+
|
|
275
|
+
# 只跑某模块
|
|
276
|
+
uv run pytest tests/test_webhook.py -v
|
|
277
|
+
uv run pytest tests/server/test_message.py -v
|
|
278
|
+
|
|
279
|
+
# 跳过真实网络,只跑本地逻辑(缓存 key / 参数校验)
|
|
280
|
+
uv run pytest tests/server/test_token.py -v
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
测试矩阵:
|
|
284
|
+
|
|
285
|
+
```
|
|
286
|
+
tests/
|
|
287
|
+
├── conftest.py fixtures + python-dotenv 加载 .env
|
|
288
|
+
├── test_webhook.py 14 tests(同步 + 异步 + 边界校验)
|
|
289
|
+
└── server/ 按 services 粒度拆分
|
|
290
|
+
├── test_token.py 5 tests(含 DiskTokenCache roundtrip)
|
|
291
|
+
├── test_media.py 7 tests(upload → get 回读内容一致)
|
|
292
|
+
├── test_message.py 12 tests(9 种消息类型 + 异步)
|
|
293
|
+
└── test_contact.py 8 tests(通讯录只读查询)
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
## 🔧 开发
|
|
297
|
+
|
|
298
|
+
```bash
|
|
299
|
+
uv sync # 安装依赖
|
|
300
|
+
uv run ruff check src tests # Lint
|
|
301
|
+
uv run ruff format src tests # Format
|
|
302
|
+
uv run mypy src/py_wecom_toolkit # 类型检查(strict 模式)
|
|
303
|
+
uv run pytest tests -v # 测试
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
pyproject.toml 关键配置:
|
|
307
|
+
|
|
308
|
+
```toml
|
|
309
|
+
[tool.mypy]
|
|
310
|
+
disallow_untyped_defs = true
|
|
311
|
+
warn_return_any = true
|
|
312
|
+
strict_optional = true
|
|
313
|
+
|
|
314
|
+
[tool.ruff]
|
|
315
|
+
select = ["E", "F", "I", "N", "W", "B", "UP", "RUF"]
|
|
316
|
+
ignore = ["RUF001", "RUF002", "RUF003"] # 中文全角标点不强制
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
## 📚 官方文档
|
|
320
|
+
|
|
321
|
+
| 主题 | URL |
|
|
322
|
+
|------|-----|
|
|
323
|
+
| 企业微信开放平台总入口 | https://developer.work.weixin.qq.com/document/path/90664 |
|
|
324
|
+
| 群机器人 | https://developer.work.weixin.qq.com/document/path/91770 |
|
|
325
|
+
| 发送应用消息 | https://developer.work.weixin.qq.com/document/path/90236 |
|
|
326
|
+
| 临时素材 | https://developer.work.weixin.qq.com/document/path/90253 |
|
|
327
|
+
| 永久图片 | https://developer.work.weixin.qq.com/document/path/90256 |
|
|
328
|
+
| 通讯录用户 | https://developer.work.weixin.qq.com/document/path/90195 |
|
|
329
|
+
| 通讯录部门 | https://developer.work.weixin.qq.com/document/path/90203 |
|
|
330
|
+
| 通讯录标签 | https://developer.work.weixin.qq.com/document/path/90209 |
|
|
331
|
+
| Token / 频率限制 | https://developer.work.weixin.qq.com/document/path/92530 |
|
|
332
|
+
| 消息接收与回调 | https://developer.work.weixin.qq.com/document/path/90968 |
|
|
333
|
+
| 网页授权 | https://developer.work.weixin.qq.com/document/path/91138 |
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
## 📄 License
|
|
337
|
+
|
|
338
|
+
MIT —— [LICENSE](./LICENSE)
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
# py-wecom-toolkit
|
|
2
|
+
|
|
3
|
+
企业微信(WeCom / Work / WeChat Work)官方 API 现代化 Python 工具包 —— 类型安全、全量同步 / 异步、零配置自动 Token 管理。
|
|
4
|
+
|
|
5
|
+
[](https://www.python.org/)
|
|
6
|
+
[](https://www.python-httpx.org/)
|
|
7
|
+
[](https://docs.pydantic.dev/)
|
|
8
|
+
[](./LICENSE)
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## ✨ 特性
|
|
13
|
+
|
|
14
|
+
| 能力 | 说明 |
|
|
15
|
+
|------|------|
|
|
16
|
+
| **完整 API** | 覆盖群机器人、应用消息、素材、通讯录、网页授权、回调加解密 |
|
|
17
|
+
| **同步 + 异步** | 每个服务一对 `Service` / `AsyncService`,API 签名完全一致 |
|
|
18
|
+
| **自动 Token** | 默认 `DiskTokenCache` 持久化(跨重启复用);Redis / Memory 可切换 |
|
|
19
|
+
| **错误分层** | `APIError` 按 errcode 自动细分(TokenExpired / RateLimit / NoPrivilege 等) |
|
|
20
|
+
| **类型安全** | Pydantic v2 响应建模 + mypy strict(disallow_untyped_defs / warn_return_any) |
|
|
21
|
+
| **现代化** | Python 3.10+,`Self` / `X \| Y` 联合类型 / `TypeAlias` / `populate_by_name` |
|
|
22
|
+
| **零配置** | `uv add py-wecom-toolkit` 即用:默认 DiskTokenCache 写 `~/.py_wecom_toolkit/cache` |
|
|
23
|
+
|
|
24
|
+
## 📦 安装
|
|
25
|
+
|
|
26
|
+
推荐使用 [uv](https://docs.astral.sh/uv/)(极速 Python 包管理器):
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
# 基础安装(默认 DiskTokenCache)
|
|
30
|
+
uv add py-wecom-toolkit
|
|
31
|
+
|
|
32
|
+
# 含 Redis 分布式缓存
|
|
33
|
+
uv add "py-wecom-toolkit[cache]"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
使用 pip 亦可:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install py-wecom-toolkit
|
|
40
|
+
pip install py-wecom-toolkit[cache] # 额外安装 redis
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
开发模式:
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
git clone <your-repo>
|
|
47
|
+
cd py_wecom_toolkit
|
|
48
|
+
uv sync # 创建 venv + 安装依赖 + 安装本包
|
|
49
|
+
uv run pytest tests -v
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## 🚀 五分钟上手
|
|
53
|
+
|
|
54
|
+
### 群机器人(独立,仅需 webhook key)
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from py_wecom_toolkit import WebhookClient
|
|
58
|
+
|
|
59
|
+
with WebhookClient(
|
|
60
|
+
key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
|
61
|
+
mentioned_list=["@all"], # 默认每次都 @ 所有人
|
|
62
|
+
) as wb:
|
|
63
|
+
wb.send_text("你好,来自 py-wecom-toolkit @all")
|
|
64
|
+
wb.send_markdown("**重要通知**\n> 生产环境告警")
|
|
65
|
+
wb.send_file(upload["media_id"]) # 先 upload_media 再 send_file
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 服务端应用(自动 token 缓存)
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from py_wecom_toolkit import WeCom
|
|
72
|
+
|
|
73
|
+
with WeCom(
|
|
74
|
+
corpid="wx...", # 企业 ID
|
|
75
|
+
corpsecret="...", # 应用 Secret
|
|
76
|
+
agentid=1000002, # 应用 AgentId
|
|
77
|
+
) as client:
|
|
78
|
+
|
|
79
|
+
# 发消息
|
|
80
|
+
client.message.send_text("hello", touser="@all")
|
|
81
|
+
client.message.send_markdown("**md**\n> 支持 Markdown 语法", touser="@all")
|
|
82
|
+
client.message.send_textcard(title="标题", description="正文",
|
|
83
|
+
url="https://...", btntxt="查看",
|
|
84
|
+
agentid=1000002, touser="@all")
|
|
85
|
+
client.message.send_news(articles=[{...}], agentid=1000002, touser="@all")
|
|
86
|
+
|
|
87
|
+
# 素材(上传拿到 media_id → 发送)
|
|
88
|
+
media = client.media.upload_media(b"content", media_type="file",
|
|
89
|
+
filename="a.txt")
|
|
90
|
+
client.message.send_file(media_id=media.media_id, agentid=1000002)
|
|
91
|
+
|
|
92
|
+
# 通讯录
|
|
93
|
+
zhangsan = client.user.get("zhangsan")
|
|
94
|
+
dept = client.department.list()
|
|
95
|
+
tags = client.tag.list_tags()
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### 异步(FastAPI / aiohttp)
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from py_wecom_toolkit import AsyncWeCom
|
|
102
|
+
|
|
103
|
+
async def handler():
|
|
104
|
+
async with AsyncWeCom(corpid="wx...", corpsecret="...") as wc:
|
|
105
|
+
await wc.message.send_text("[async] 异步消息", agentid=1000002)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## 🏗️ 架构总览
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
py_wecom_toolkit/
|
|
112
|
+
├── client.py WeCom / AsyncWeCom 顶层组合客户端
|
|
113
|
+
├── core/ 底层基础设施(不直接使用)
|
|
114
|
+
│ ├── auth.py TokenManager / AsyncTokenManager(缓存 + 校验 + 刷新)
|
|
115
|
+
│ ├── base.py BaseClient / AsyncBaseClient(httpx + token 注入 + 错误转换)
|
|
116
|
+
│ ├── cache.py 三种缓存实现 + TokenCache Protocol + make_cache_key
|
|
117
|
+
│ ├── config.py ClientConfig dataclass
|
|
118
|
+
│ ├── crypto.py MessageCrypto(AES-GCM 加解密 + 签名校验)
|
|
119
|
+
│ ├── exceptions.py APIError 按 errcode 自动细分的异常族
|
|
120
|
+
│ ├── models.py Pydantic v2 响应模型
|
|
121
|
+
│ └── utils.py join_recipients / prepare_file_input
|
|
122
|
+
└── services/ 业务服务层(全部通过 WeCom().xxx 访问)
|
|
123
|
+
├── webhook/ 群机器人(独立,不需要 token)
|
|
124
|
+
├── token/ access_token 管理 + get_api_domain_ip
|
|
125
|
+
├── message/ 9 种应用消息类型
|
|
126
|
+
├── media/ 临时素材 / 永久图片
|
|
127
|
+
├── contact/ User / Department / Tag 全 CRUD
|
|
128
|
+
└── oauth/ 网页授权 + 回调加解密(crypto 工具类单独导出)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
### Token 缓存
|
|
132
|
+
|
|
133
|
+
```python
|
|
134
|
+
from py_wecom_toolkit import WeCom, DiskTokenCache, RedisTokenCache, MemoryTokenCache
|
|
135
|
+
|
|
136
|
+
# 默认(磁盘持久化,跨重启复用)
|
|
137
|
+
WeCom(corpid=..., corpsecret=...)
|
|
138
|
+
|
|
139
|
+
# 分布式(多进程 / K8s 多副本)
|
|
140
|
+
WeCom(..., cache=RedisTokenCache(host="redis.example.com", port=6379))
|
|
141
|
+
|
|
142
|
+
# 零依赖内存(一次性脚本)
|
|
143
|
+
WeCom(..., cache=MemoryTokenCache())
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
统一缓存 key 格式:`py_wecom_toolkit:{corpid}`(不含 corpsecret,同一企业下不同应用 Secret 共享 token)。
|
|
147
|
+
|
|
148
|
+
### 异常体系
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from py_wecom_toolkit import APIError, RateLimitError, TokenExpiredError
|
|
152
|
+
|
|
153
|
+
with WeCom(...) as wc:
|
|
154
|
+
try:
|
|
155
|
+
wc.message.send_text("hello", agentid=1000002, touser="@all")
|
|
156
|
+
except TokenExpiredError:
|
|
157
|
+
# 实际使用很少遇到 —— BaseClient 会在 42001 时自动 refresh 再重试一次
|
|
158
|
+
wc.token.refresh()
|
|
159
|
+
except RateLimitError as e:
|
|
160
|
+
# 45009 限频 —— 指数退避重试
|
|
161
|
+
log.warning(f"限频 errcode={e.errcode}")
|
|
162
|
+
except APIError as e:
|
|
163
|
+
# 兜底:所有业务层错误
|
|
164
|
+
log.error(f"API errcode={e.errcode} errmsg={e.errmsg} raw={e.raw}")
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### 回调加解密
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
from py_wecom_toolkit import MessageCrypto, verify_signature
|
|
171
|
+
|
|
172
|
+
crypto = MessageCrypto(
|
|
173
|
+
token="回调 Token",
|
|
174
|
+
encoding_aes_key="EncodingAESKey",
|
|
175
|
+
corp_id="wx...",
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# GET: 解密 echostr
|
|
179
|
+
plain = crypto.decrypt_message(
|
|
180
|
+
echostr_encrypted, msg_signature, timestamp, nonce
|
|
181
|
+
)
|
|
182
|
+
# 把 plain 原样返回给企业微信
|
|
183
|
+
|
|
184
|
+
# POST: 解密消息推送
|
|
185
|
+
plain_xml = crypto.decrypt_message(
|
|
186
|
+
encrypted_xml_body, msg_signature, timestamp, nonce
|
|
187
|
+
)
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## 📁 完整示例
|
|
191
|
+
|
|
192
|
+
[examples/](./examples) 目录下 5 个可独立运行的示例,覆盖所有核心能力:
|
|
193
|
+
|
|
194
|
+
| 文件 | 场景 | 依赖 |
|
|
195
|
+
|------|------|------|
|
|
196
|
+
| `01_webhook_basic.py` | 群机器人 9 种消息类型 | WEBHOOK_KEY |
|
|
197
|
+
| `02_wecom_basic.py` | 服务端应用消息 / 素材 / 通讯录 | CORPID / CORPSECRET / AGENTID |
|
|
198
|
+
| `03_cache_backends.py` | Disk / Memory / Redis 三种缓存切换 | 无(演示) |
|
|
199
|
+
| `04_error_handling.py` | APIError 子类 + 生产级 try/except 模板 | 无(演示) |
|
|
200
|
+
| `05_oauth_callback.py` | 网页授权 URL 构造 + 回调加解密 | 无(演示) |
|
|
201
|
+
|
|
202
|
+
运行:
|
|
203
|
+
|
|
204
|
+
```bash
|
|
205
|
+
cp tests/.env.example tests/.env # 填入真实凭证
|
|
206
|
+
uv run python examples/02_wecom_basic.py
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## 🧪 测试
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
# 全量(真实网络请求,未配置凭证的会自动 skip,退出码 0)
|
|
213
|
+
cp tests/.env.example tests/.env # 填入 WEBHOOK_KEY / CORPID / CORPSECRET / AGENTID
|
|
214
|
+
uv run pytest tests -v
|
|
215
|
+
|
|
216
|
+
# 只跑某模块
|
|
217
|
+
uv run pytest tests/test_webhook.py -v
|
|
218
|
+
uv run pytest tests/server/test_message.py -v
|
|
219
|
+
|
|
220
|
+
# 跳过真实网络,只跑本地逻辑(缓存 key / 参数校验)
|
|
221
|
+
uv run pytest tests/server/test_token.py -v
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
测试矩阵:
|
|
225
|
+
|
|
226
|
+
```
|
|
227
|
+
tests/
|
|
228
|
+
├── conftest.py fixtures + python-dotenv 加载 .env
|
|
229
|
+
├── test_webhook.py 14 tests(同步 + 异步 + 边界校验)
|
|
230
|
+
└── server/ 按 services 粒度拆分
|
|
231
|
+
├── test_token.py 5 tests(含 DiskTokenCache roundtrip)
|
|
232
|
+
├── test_media.py 7 tests(upload → get 回读内容一致)
|
|
233
|
+
├── test_message.py 12 tests(9 种消息类型 + 异步)
|
|
234
|
+
└── test_contact.py 8 tests(通讯录只读查询)
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
## 🔧 开发
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
uv sync # 安装依赖
|
|
241
|
+
uv run ruff check src tests # Lint
|
|
242
|
+
uv run ruff format src tests # Format
|
|
243
|
+
uv run mypy src/py_wecom_toolkit # 类型检查(strict 模式)
|
|
244
|
+
uv run pytest tests -v # 测试
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
pyproject.toml 关键配置:
|
|
248
|
+
|
|
249
|
+
```toml
|
|
250
|
+
[tool.mypy]
|
|
251
|
+
disallow_untyped_defs = true
|
|
252
|
+
warn_return_any = true
|
|
253
|
+
strict_optional = true
|
|
254
|
+
|
|
255
|
+
[tool.ruff]
|
|
256
|
+
select = ["E", "F", "I", "N", "W", "B", "UP", "RUF"]
|
|
257
|
+
ignore = ["RUF001", "RUF002", "RUF003"] # 中文全角标点不强制
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
## 📚 官方文档
|
|
261
|
+
|
|
262
|
+
| 主题 | URL |
|
|
263
|
+
|------|-----|
|
|
264
|
+
| 企业微信开放平台总入口 | https://developer.work.weixin.qq.com/document/path/90664 |
|
|
265
|
+
| 群机器人 | https://developer.work.weixin.qq.com/document/path/91770 |
|
|
266
|
+
| 发送应用消息 | https://developer.work.weixin.qq.com/document/path/90236 |
|
|
267
|
+
| 临时素材 | https://developer.work.weixin.qq.com/document/path/90253 |
|
|
268
|
+
| 永久图片 | https://developer.work.weixin.qq.com/document/path/90256 |
|
|
269
|
+
| 通讯录用户 | https://developer.work.weixin.qq.com/document/path/90195 |
|
|
270
|
+
| 通讯录部门 | https://developer.work.weixin.qq.com/document/path/90203 |
|
|
271
|
+
| 通讯录标签 | https://developer.work.weixin.qq.com/document/path/90209 |
|
|
272
|
+
| Token / 频率限制 | https://developer.work.weixin.qq.com/document/path/92530 |
|
|
273
|
+
| 消息接收与回调 | https://developer.work.weixin.qq.com/document/path/90968 |
|
|
274
|
+
| 网页授权 | https://developer.work.weixin.qq.com/document/path/91138 |
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
## 📄 License
|
|
278
|
+
|
|
279
|
+
MIT —— [LICENSE](./LICENSE)
|