py-wecom-sdk
企业微信官方 API 的 Python SDK,Mixin 聚合架构 + 统一响应模型。
目录
项目简介
py-wecom-sdk 是对企业微信开放平台 API 的轻量 Python 封装。
核心设计:把企业微信两套完全不同的鉴权机制(主应用域用 corpsecret → access_token,群机器人域用 Webhook key)拆成两个独立顶层门面,内部再用 Mixin 聚合把通讯录 / 素材 / 消息等业务域模块化。外部调用时,每个 Mixin 方法会自动先 refresh() 保证 access_token 有效,无需使用者手动处理鉴权。
与同系列的 py-wisharetec-sdk 架构、注释规范、发版流程完全对齐。
特性
- 两套独立门面:
WeComAPI(主应用域 access_token 鉴权)和WeComGroupRobotAPI(Webhook key 鉴权)完全解耦,互不共享基类。 - Mixin 聚合:
WeComAPI(WeComContactAPIMixin, WeComMediaAPIMixin, WeComMessageAPIMixin),业务方法直接暴露为顶层方法,调用形如api.user_get("zhangsan")。 - 统一响应模型:所有接口返回
WeComResponse(Pydantic,extra="allow"),成功/失败路径收口一致,网络异常兜底返回errcode=-10000。 - 响应解析辅助:
convert_to_wecom_response(httpx_response)内部自动处理 JSON 解析 / 二进制下载 / text 回退 / Exception 兜底,Mixin 代码只需一行。 - 缓存工厂:
WeComAPICacheFactory三选一(diskcache 默认 / cachetools.TTLCache / redis),TTL 策略一致,可选依赖延迟导入。 - 零配置可用:不传
cache_factory自动用 diskcache 本地磁盘;不传client自动用 httpx.Client。 - Google Style 文档:模块 / 类 / 方法 docstring 统一 Google Style,包含 Attributes / Args / Returns。
- 类型注解:PEP 604 联合类型空格(
str | None),mypy strict 模式全过。 - 质量门禁:ruff check / ruff format / mypy strict / pytest 真实网络集成测试四检合一。
目录结构
py_wecom_sdk/
├── _version.py # SDK 版本号(hatchling 动态读取)
├── provider.py # Facade 统一入口,重导出 6 个符号
├── __init__.py # 包入口
└── core/
├── __init__.py
├── _api.py # 主应用域顶层门面 WeComAPI + WeComAPICacheFactory
├── _group_robot.py # 群机器人独立门面 WeComGroupRobotAPI
├── _contact.py # 通讯录 Mixin(成员 / 部门 / 标签,9 个方法)
├── _media.py # 素材 Mixin(临时素材 / 永久图片,3 个方法)
├── _message.py # 应用消息 Mixin(通用 + 8 便捷,9 个方法)
├── _models.py # Pydantic 配置模型 + WeComResponse + 响应解析辅助
└── _utils.py # 内部工具(文件读取 / base64+md5 / multipart 文件)
安装
基础安装
pip install py-wecom-sdk
可选依赖
SDK 默认只装 diskcache(本地磁盘缓存),其他缓存后端按需安装:
# cachetools.TTLCache 进程内内存缓存
pip install py-wecom-sdk[cachetools]
# redis 远程缓存
pip install py-wecom-sdk[redis]
# 一把梭,全装
pip install py-wecom-sdk[all]
使用 uv
uv add py-wecom-sdk # 基础
uv add py-wecom-sdk[all] # 全装
快速开始
主应用域
from py_wecom_sdk import WeComAPI, WeComAPIConfig
config = WeComAPIConfig(
corpid="ww_xxx",
corpsecret="your_app_secret",
agentid=1000002,
)
# 零配置即可用 — access_token 自动缓存到 .cache/py_wecom_sdk/
with WeComAPI(config=config) as api:
resp = api.user_get("zhangsan")
if resp.ok():
print(resp.name, resp.department)
else:
print("调用失败:", resp.errmsg)
群机器人域
from py_wecom_sdk import WeComGroupRobotAPI, WeComGroupRobotAPIConfig
bot = WeComGroupRobotAPI(
config=WeComGroupRobotAPIConfig(key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
)
# 文本消息
bot.webhook_send_text("来自 py-wecom-sdk 的问候 🎉")
# 图片消息(自动算 base64 + md5)
bot.webhook_send_image("/path/to/pic.png")
# 图文消息
bot.webhook_send_news(articles=[{
"title": "测试标题",
"description": "测试描述",
"url": "https://example.com",
"picurl": "https://example.com/pic.png",
}])
详细用法
主应用域(access_token 鉴权)
WeComAPI 继承三个业务 Mixin,所有业务方法自动先调 refresh():
from py_wecom_sdk import WeComAPI, WeComAPIConfig
api = WeComAPI(config=WeComAPIConfig(corpid="...", corpsecret="..."))
# 通讯录域(WeComContactAPIMixin)
api.user_get("zhangsan")
api.user_simplelist(department_id=1)
api.department_list()
api.tag_list()
# 素材域(WeComMediaAPIMixin)
upload = api.media_upload("/path/to/face.jpg", media_type="image")
media_id = upload.media_id
# 消息域(WeComMessageAPIMixin)
api.message_send_text(content="你好", touser="zhangsan", agentid=1000002)
api.message_send_image(media_id=media_id, touser="zhangsan")
api.message_send_markdown("# Hello\n> 世界")
群机器人域(Webhook key 鉴权)
与主应用域完全独立,不需要 access_token,通过 URL query 自动附加 key:
from py_wecom_sdk import WeComGroupRobotAPI, WeComGroupRobotAPIConfig
bot = WeComGroupRobotAPI(
config=WeComGroupRobotAPIConfig(
key="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
mentioned_list=["@all"],
)
)
# 7 种便捷方法 + 通用 webhook_send
bot.webhook_send_text("hello")
bot.webhook_send_markdown("# 标题")
bot.webhook_send_image("/path/to/pic.png")
bot.webhook_send_file("/path/to/doc.pdf") # 自动上传
bot.webhook_upload_media("/path/to/audio.amr", media_type="voice")
# 通用发送(透传 payload)
bot.webhook_send({
"msgtype": "text",
"text": {"content": "hello"},
})
手动管理 access_token
# 强制刷新(忽略缓存)
api.refresh(force=True)
# 检查当前 token 是否有效
if api.check_access_token():
print("token 有效")
# 拿到原始 token 字符串
print(api.access_token)
# 手动调 gettoken
resp = api.gettoken()
print(resp.access_token) # 或 resp["access_token"]
print(resp.expires_in) # 秒
外部注入 httpx.Client
import httpx
from py_wecom_sdk import WeComAPI, WeComAPIConfig
# 自定义超时 / 代理 / header 等
client = httpx.Client(timeout=30, headers={"X-Custom": "value"})
api = WeComAPI(config=config, client=client)
# close() 不会关闭外部注入的 client,由调用方负责
api.close()
client.close()
缓存机制
access_token 默认有效期 7200 秒,WeComAPICacheFactory 统一封装三种后端:
diskcache(默认,零配置)
from py_wecom_sdk import WeComAPI, WeComAPIConfig, WeComAPICacheFactory
# 默认就是 diskcache,缓存文件落在 .cache/py_wecom_sdk/
api = WeComAPI(config=config)
# 或显式指定
api = WeComAPI(
config=config,
cache_factory=WeComAPICacheFactory(choice="diskcahce", directory=".cache/py_wecom_sdk"),
)
cachetools.TTLCache(进程内)
api = WeComAPI(
config=config,
cache_factory=WeComAPICacheFactory(choice="ttlcache", ttl=7200, maxsize=256),
)
redis(远程缓存)
api = WeComAPI(
config=config,
cache_factory=WeComAPICacheFactory(
choice="redis", host="localhost", port=6379, db=0,
),
)
三种后端的 get / set(key, value, ttl) / delete / exists 接口完全一致,TTL 透传到各自实现。延迟导入机制保证未安装可选依赖时不会崩溃。
API 速查表
WeComContactAPIMixin(通讯录)
| 方法 | HTTP | 路径 | 说明 |
|---|---|---|---|
user_get(userid) |
GET | /cgi-bin/user/get |
获取成员详情 |
user_simplelist(department_id, fetch_child) |
GET | /cgi-bin/user/simplelist |
获取部门成员(简版) |
user_list(department_id, fetch_child) |
GET | /cgi-bin/user/list |
获取部门成员详情 |
user_list_id(cursor, limit) |
POST | /cgi-bin/user/list_id |
成员 ID 列表(游标分页) |
department_list(id) |
GET | /cgi-bin/department/list |
获取部门列表 |
department_simplelist(id) |
GET | /cgi-bin/department/simplelist |
获取子部门 ID 列表 |
department_get(id) |
GET | /cgi-bin/department/get |
获取单个部门详情 |
tag_list() |
GET | /cgi-bin/tag/list |
获取标签列表 |
tag_get(tagid) |
GET | /cgi-bin/tag/get |
获取标签成员 |
WeComMediaAPIMixin(素材)
| 方法 | HTTP | 路径 | 说明 |
|---|---|---|---|
media_upload(file, media_type, filename) |
POST | /cgi-bin/media/upload |
临时素材上传(image / voice / video / file) |
media_get(media_id) |
GET | /cgi-bin/media/get |
临时素材下载(自动区分二进制 / JSON) |
media_uploadimg(file, filename) |
POST | /cgi-bin/media/uploadimg |
永久图片上传(返回 URL) |
WeComMessageAPIMixin(应用消息)
| 方法 | 说明 |
|---|---|
message_send(payload) |
通用发送(所有便捷方法最终调用) |
message_send_text(content, touser, toparty, totag, agentid) |
文本消息 |
message_send_markdown(content, ...) |
Markdown 消息 |
message_send_image(media_id, ...) |
图片消息(需先上传) |
message_send_file(media_id, ...) |
文件消息(需先上传) |
message_send_voice(media_id, ...) |
语音消息(需先上传) |
message_send_video(media_id, ...) |
视频消息(需先上传) |
message_send_news(articles, ...) |
图文消息 |
message_send_template_card(template_card, ...) |
模板卡片消息 |
所有便捷方法的 agentid 未显式传入时自动使用 config.agentid。
WeComGroupRobotAPI(群机器人)
| 方法 | 说明 |
|---|---|
webhook_send(payload) |
通用发送 |
webhook_send_text(content, mentioned_list, mentioned_mobile_list) |
文本(支持 @) |
webhook_send_markdown(content) |
Markdown |
webhook_send_markdown_v2(content) |
markdown_v2 富文本 |
webhook_send_image(image, *, base64, md5) |
图片(传文件自动算 base64 + md5) |
webhook_send_news(articles) |
图文 |
webhook_send_file(file, *, media_id, filename) |
文件(传文件自动上传) |
webhook_send_voice(file, *, media_id, filename) |
语音(传文件自动上传) |
webhook_send_template_card(template_card) |
模板卡片 |
webhook_upload_media(file, filename, media_type) |
群机器人临时素材上传 |
鉴权辅助
| 方法 | 说明 |
|---|---|
gettoken() |
调 /cgi-bin/gettoken 拿 access_token |
check_access_token() |
校验当前 token 是否有效(走 /cgi-bin/get_api_domain_ip) |
get_api_domain_ip() |
直接调 get_api_domain_ip 接口 |
refresh(force=False) |
缓存优先刷新,返回 self 支持链式 |
building_params(extra_params) |
构造 URL query,自动附带 access_token / key |
配置说明
WeComAPIConfig
| 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
corpid |
str | None |
None |
企业 ID,如 ww_abc123 |
corpsecret |
str | None |
None |
企业密钥(应用 Secret 或通讯录 Secret) |
agentid |
int | str | None |
None |
应用 ID,消息发送要用 |
base_url |
AnyHttpUrl |
https://qyapi.weixin.qq.com/ |
API 根地址,构造后自动 rstrip("/") |
WeComGroupRobotAPIConfig
| 字段 | 类型 | 默认 | 说明 |
|---|---|---|---|
base_url |
AnyHttpUrl |
https://qyapi.weixin.qq.com |
Webhook 根地址 |
key |
str |
— 必填 | Webhook key |
mentioned_list |
list[str] |
[] |
默认 @ 的 UserID |
mentioned_mobile_list |
list[str] |
[] |
默认 @ 的手机号 |
依赖
| 依赖 | 版本 | 类型 | 说明 |
|---|---|---|---|
httpx |
≥0.27.0 | 必选 | HTTP 客户端 |
pydantic |
≥2.5.0 | 必选 | 配置 + 响应模型(含 v2) |
diskcache |
≥5.6.1 | 必选 | access_token 本地磁盘缓存 |
cachetools |
≥5.3.0 | 可选 | TTLCache 进程内缓存(py-wecom-sdk[cachetools]) |
redis |
≥5.0.0 | 可选 | Redis 远程缓存(py-wecom-sdk[redis]) |
Python ≥ 3.10(PEP 604 / str | None 联合类型)。
测试
本项目测试套件跑的是真实企业微信接口(非 Mock),需要在 .env 里配置你的凭据:
# .env
WECOM_CORPID=ww_xxx
WECOM_SECRET=your_secret
WECOM_AGENTID=1000002
WECOM_GROUP_ROBOT_API_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
WECOM_TEST_USERID=Guolei
四检命令
# 1. ruff 自动修复 + 格式化
ruff check --fix --unsafe-fixes src/ tests/
ruff format src/ tests/
# 2. ruff 验证
ruff check src/ tests/
ruff format --check src/ tests/
# 3. mypy 静态检查
mypy src/
# 4. pytest 真实网络集成测试
PYTHONPATH=src python3 -m pytest tests/ -v
典型结果
ruff check src/ tests/ → All checks passed!
ruff format --check src/ → 17 files already formatted
mypy src/ → Success: no issues found in 11 source files
pytest tests/ → 26 passed, 2 skipped, 0 failed
许可证
MIT License © guolei19850528
Metadata
Release files for py-wecom-sdk 2.0.4
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| py_wecom_sdk-2.0.4.tar.gz | 28.5 kB | Without provenance | Details for py_wecom_sdk-2.0.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| py_wecom_sdk-2.0.4-py3-none-any.whl | Python 3 | none | any | Details for py_wecom_sdk-2.0.4-py3-none-any.whl |
Total release size: 54.2 kB
Release files / py_wecom_sdk-2.0.4.tar.gz
| Download URL | py_wecom_sdk-2.0.4.tar.gz |
|---|---|
| Size | 28.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
e05da1612e9c137e53c242fe4e48fd87eaa443213dd4b3e99200e0a9130dd0d3
|
|
BLAKE2b-256 checksum How to use checksums |
e7072c3f89097f9c2f9a34002d3e849160abc21b36c7a709478fd4e05f588cce
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.6
|
Release files / py_wecom_sdk-2.0.4-py3-none-any.whl
| Download URL | py_wecom_sdk-2.0.4-py3-none-any.whl |
|---|---|
| Size | 25.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
8f6642602f1a17332c96202a2707f329921b9bff3f26b0d008ad2b51c8bff55a
|
|
BLAKE2b-256 checksum How to use checksums |
96e91c6ab45411357aff7ae23f5549a1ab70cd88eebeec926df792e3dc8de7af
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.6
|
Security for py-wecom-sdk 2.0.4
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.