Skip to main content

py-wecom-sdk

企业微信(WeCom)开放接口 Python SDK — 基于 httpx + pydantic v2,采用 Mixin 聚合架构。


特性

  • 🔑 自动 access_token 刷新 — SDK 内部缓存 access_token,过期自动 gettoken() 重新获取,所有 Mixin 方法入口先 refresh()
  • 💾 可选缓存后端 — 默认 diskcache 本地文件缓存;可选 cachetools.TTLCache 或 redis 分布式缓存
  • 🧩 Mixin 聚合架构 — WeComAPI 类继承 3 个业务 Mixin,一行实例化即拥有通讯录 / 素材 / 消息全部能力
  • 📦 双门面独立 — WeComAPI(access_token 鉴权,主应用域)与 WeComGroupRobotAPI(Webhook key 鉴权,群机器人域)完全独立
  • 🧠 统一响应模型 — WeComResponse + extra="allow" 自动接收企业微信额外字段,提供 ok() 统一断言
  • 🧪 真实网络集成测试 — pytest + .env,19 passed / 1 skipped,真实请求返回 JSON 直接打印

安装

# 基础安装(只含 diskcache)
pip install py-wecom-sdk

# 带 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[all]

快速开始

主应用域(access_token 鉴权)

from py_wecom_sdk.provider import WeComAPI, WeComAPIConfig

# 最简 — corpsecret + corpid + agentid
api = WeComAPI(config=WeComAPIConfig(
    corpid="wwXXXXXXXXXXXXXXXX",
    corpsecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    agentid=1000002,
))
api.refresh()  # 首次调用自动登录(内部缓存 access_token)

# 自定义 base_url
api = WeComAPI(config=WeComAPIConfig(
    corpid="wwXXXXXXXXXXXXXXXX",
    corpsecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    agentid=1000002,
    base_url="https://qyapi.weixin.qq.com/",
))

# ===== 通讯录模块(成员 / 部门 / 标签)=====
# 获取成员
resp = api.user_get("Guolei")
if resp.ok():
    print(resp.name, resp.department)

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

# ===== 素材模块(临时素材 / 永久图片)=====
upload = api.media_upload("chart.png", media_type="image")
print(upload.media_id)

# 永久图片(返回 url,可用于 Markdown)
permanent = api.media_uploadimg("banner.png")
print(permanent.url)

# ===== 应用消息 =====
api.message_send_text(content="Hello py_wecom_sdk!", touser="Guolei")

# 组合:先拿 media_id,再发图片消息
upload = api.media_upload("photo.png", media_type="image")
api.message_send_image(media_id=upload.media_id, touser="Guolei")

with api:  # 上下文管理器自动 close httpx.Client
    api.message_send_markdown(content="## Title\n**Markdown**", touser="Guolei")

群机器人域(Webhook key 鉴权,完全独立)

from py_wecom_sdk.provider import WeComGroupRobotAPI, WeComGroupRobotAPIConfig

robot = WeComGroupRobotAPI(config=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": "py_wecom_sdk",
    "url": "https://gitee.com/guolei19850528/py_wecom_sdk",
}])

# 上传群机器人素材 → 发送文件
uploaded = robot.webhook_upload_media("report.txt", media_type="file")
robot.webhook_send_file(media_id=uploaded.media_id)

响应模型

所有 API 返回 WeComResponse(Pydantic BaseModel,extra="allow"):

属性 / 方法 类型 说明
resp.ok() bool 是否成功。判定规则:int(resp.errcode) == 0
resp.errcode int | str | None 企业微信错误码
resp.errmsg str | None 企业微信错误信息
resp.model_extra dict | None 额外字段(企业微信返回的 access_token / media_id / userlist / department 等)
resp.<extra_key> 任意 extra 字段可直接访问,如 resp.media_id / resp.name / resp.url
# 正常业务响应
resp = api.user_get("Guolei")
resp.ok()           # True
resp.errcode        # 0
resp.name           # 郭磊(extra 字段直接访问)
resp.department     # [60]

# 业务异常(参数错误 / 权限不足等)
resp = api.user_get("not_exist")
resp.ok()           # False
resp.errcode        # 4003
resp.errmsg         # "userid not found"

# 网络异常(SDK 内部 try/except 不抛异常)
resp = api.user_get("x")
resp.ok()           # False
resp.errcode        # -1000
resp.errmsg         # "ConnectError: ..."

项目结构

py_wecom_sdk/
├── src/py_wecom_sdk/
│   ├── __init__.py
│   ├── _version.py                   # 版本号(hatchling 动态读取)
│   ├── provider.py                   # Facade 统一入口(WeComAPI / WeComAPICacheFactory / WeComAPIConfig / ...)
│   └── core/
│       ├── __init__.py
│       ├── _api.py                   # 核心:WeComAPI + WeComAPICacheFactory + 延迟导入辅助 + gettoken/refresh/check_access_token
│       ├── _group_robot.py            # 群机器人独立门面:WeComGroupRobotAPI + WeComGroupRobotAPIConfig
│       ├── _contact.py               # WeComContactAPIMixin(成员/部门/标签)— 9 方法
│       ├── _media.py                 # WeComMediaAPIMixin(临时素材上传下载/永久图片)— 3 方法
│       ├── _message.py               # WeComMessageAPIMixin(通用发送 + 8 便捷方法)— 9 方法
│       ├── _models.py                # 数据模型:WeComAPIConfig / WeComGroupRobotAPIConfig / WeComResponse
│       └── _utils.py                 # 通用工具:read_file_bytes / compute_base64_md5 / building_multipart_file
├── tests/
│   ├── conftest.py                   # pytest fixture(.env → wecom_api / wecom_group_robot session 级实例)
│   ├── test_wecom_contact.py         # 通讯录集成测试
│   ├── test_wecom_media.py           # 素材集成测试
│   ├── test_wecom_message.py         # 应用消息集成测试
│   └── test_wecom_group_robot.py     # 群机器人集成测试
├── pyproject.toml                    # hatchling + ruff + pytest + optional-dependencies
├── .env.example                      # 集成测试凭证模板
└── LICENSE

API 速查表

WeComAPI — 鉴权生命周期

方法 说明
gettoken() 手动调用 GET /cgi-bin/gettoken 获取 access_token
get_api_domain_ip() 调用 GET /cgi-bin/get_api_domain_ip
check_access_token() token 有效性校验(内部调用 get_api_domain_ip)
refresh(force=False) 缓存优先刷新 Mixin 共用,所有 Mixin 方法入口自动调用
close() 关闭 httpx.Client(注入的不关闭)
__enter__ / __exit__ 上下文管理器

WeComContactAPIMixin — 通讯录(9 方法)

分类 方法 HTTP 路径
成员 user_get(userid) GET /cgi-bin/user/get
成员 user_simplelist(department_id, fetch_child=1) GET /cgi-bin/user/simplelist
成员 user_list(department_id, fetch_child=0) GET /cgi-bin/user/list
成员 user_list_id(cursor="", limit=10000) POST /cgi-bin/user/list_id
部门 department_list(id=0) GET /cgi-bin/department/list
部门 department_simplelist(id=1) GET /cgi-bin/department/simplelist
部门 department_get(id) GET /cgi-bin/department/get
标签 tag_list() GET /cgi-bin/tag/list
标签 tag_get(tagid) GET /cgi-bin/tag/get

WeComMediaAPIMixin — 素材(3 方法)

分类 方法 HTTP 路径
临时素材 media_upload(file, media_type, filename=None) POST /cgi-bin/media/upload
临时素材 media_get(media_id) GET /cgi-bin/media/get
永久图片 media_uploadimg(file, filename=None) POST /cgi-bin/media/uploadimg

WeComMessageAPIMixin — 应用消息(9 方法)

分类 方法 msgtype HTTP 路径
底层 message_send(payload) 任意 POST /cgi-bin/message/send
便捷 message_send_text(content, ...) text POST 同上
便捷 message_send_markdown(content, ...) markdown POST 同上
便捷 message_send_image(media_id, ...) image POST 同上
便捷 message_send_voice(media_id, ...) voice POST 同上
便捷 message_send_video(media_id, ...) video POST 同上
便捷 message_send_file(media_id, ...) file POST 同上
便捷 message_send_news(articles, ...) news POST 同上
便捷 message_send_template_card(template_card, ...) template_card POST 同上

WeComGroupRobotAPI — 群机器人 Webhook(独立门面,11 方法)

分类 方法 说明
底层 webhook_send(payload) URL query 带 key 鉴权
便捷 webhook_send_text(content, mentioned_list=None, mentioned_mobile_list=None) 支持 @
便捷 webhook_send_markdown(content) Markdown
便捷 webhook_send_markdown_v2(content) 增强版 Markdown
便捷 webhook_send_image(image=None, *, base64=None, md5=None) bytes 内部自动算 base64+md5
便捷 webhook_send_news(articles) 1~8 条
便捷 webhook_send_file(file=None, *, media_id=None) 传文件内部自动 upload_media
便捷 webhook_send_voice(file=None, *, media_id=None) 同上
便捷 webhook_send_template_card(template_card) 模板卡片
素材 webhook_upload_media(file, filename=None, media_type="file") file / voice 上传

缓存机制

SDK 自动缓存 access_token(默认 6900 秒,官方 7200 秒提前 300 秒过期),避免每次请求都 gettoken()。

from py_wecom_sdk.provider import WeComAPI, WeComAPIConfig, WeComAPICacheFactory

# 默认:diskcache 本地文件缓存
api = WeComAPI(config=WeComAPIConfig(
    corpid="ww_xxx", corpsecret="yyy", agentid=1000002,
))
# → 自动使用 .cache/py_wecom_sdk 目录

# 切换 TTLCache(需要 pip install py-wecom-sdk[cachetools])
api = WeComAPI(
    config=WeComAPIConfig(...),
    cache_factory=WeComAPICacheFactory(choice="ttlcache", ttl=6900, maxsize=128),
)

# 切换 Redis(需要 pip install py-wecom-sdk[redis])
api = WeComAPI(
    config=WeComAPIConfig(...),
    cache_factory=WeComAPICacheFactory(
        choice="redis", host="localhost", port=6379, db=0,
    ),
)

# 自定义缓存 — 实现 get(key, default) / set(key, value, ttl) 即可
class MyCache:
    def get(self, key, default=None): ...
    def set(self, key, value, ttl=None): ...

api = WeComAPI(config=..., cache_factory=MyCache())

延迟导入兜底:未安装 cachetools 或 redis 时,WeComAPICacheFactory 运行时使用 _is_ttlcache() / _is_redis() 辅助函数检测,不会 import 崩溃。

WeComAPICacheFactory 参数:

参数 类型 默认值 说明
choice "ttlcache" / "diskcahce" / "redis" "diskcahce" 缓存后端选择(注意历史拼写保留 diskcahce)
ttl int 6900 TTL 秒数(ttlcache / redis 生效)
maxsize int 128 缓存最大条目数(仅 ttlcache 生效)
**kwargs - - 透传给所选后端构造器(diskcache 的 directory / Redis 的 host, port, db 等)

配置说明

WeComAPIConfig

字段 默认值 说明
corpid 必填 企业 ID,如 ww_abc123
corpsecret 必填 企业密钥(应用 Secret 或通讯录 Secret)
agentid None 应用 ID,如 1000002
base_url https://qyapi.weixin.qq.com/ API 基础 URL,自动 rstrip("/")

WeComGroupRobotAPIConfig

字段 默认值 说明
key 必填 Webhook key
base_url https://qyapi.weixin.qq.com Webhook 基础 URL
mentioned_list [] 默认 @ 的成员 UserID
mentioned_mobile_list [] 默认 @ 的手机号

运行测试

# 1. 复制并填写 .env
cp .env.example .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. 全部(真实网络)
uv run pytest tests/ -v -s

# 3. 指定模块
uv run pytest tests/test_wecom_contact.py -v -s

# 4. 强制刷新缓存 + 重新 gettoken
uv run pytest tests/ -v -s --cache-clear

测试结果:

======================== 19 passed, 1 skipped in ~10s ========================

所有测试带 -s 输出,可看到每个接口的真实 JSON 返回。


依赖

依赖 版本 类型 说明
httpx >=0.28.1 核心 HTTP 客户端
pydantic >=2.14.3 核心 数据模型 / 校验
diskcache >=5.6.1 核心 默认 access_token 缓存后端
cachetools >=5.3.0 可选 [cachetools] TTLCache 进程内缓存
redis >=5.0.0 可选 [redis] Redis 分布式缓存
python-dotenv >=1.2 开发 测试 .env 加载
pytest >=8 开发 测试框架

架构设计

┌─────────────────────────────────────────────────────┐
│                  WeComAPI(门面类)                     │
│  ┌───────────────────────────────────────────────┐  │
│  │ 继承链(Mixin 聚合)                             │  │
│  │   WeComContactAPIMixin                9 方法           │  │
│  │   WeComMediaAPIMixin                   3 方法           │  │
│  │   WeComMessageAPIMixin                 9 方法           │  │
│  └───────────────────────────────────────────────┘  │
│  + gettoken() / refresh() / check_access_token()     │
│  + close() / __enter__ / __exit__                    │
│  + _building_params()                                │
└───────────────┬─────────────────────────────────────┘
                │ 使用
        ┌───────▼────────┐     ┌──────────────────┐
        │ WeComAPICache  │     │ httpx.Client      │
        │ Factory        │     │ (连接池)           │
        │ diskcache 默认  │     └──────────────────┘
        │ + 可选 TTL/Redis│
        └────────────────┘
                │ 所有方法 → WeComResponse (Pydantic, extra="allow")

┌─────────────────────────────────────────────────────┐
│             WeComGroupRobotAPI(独立门面)               │
│  + webhook_send / webhook_send_text / ... /           │
│    webhook_upload_media                               │
└─────────────────────────────────────────────────────┘

为什么用 Mixin?

  • 单一职责:每个 Mixin 只管一个业务域,方便单独扩展 / 测试
  • 实例化简单:用户只需 WeComAPI(config=...) 一行,自动拥有全部能力
  • 依赖注入友好:所有 Mixin 共享同一个 httpx.Client + WeComAPICacheFactory,连接池和缓存统一

许可证

MIT © guolei

Metadata

Release files for py-wecom-sdk 2.0.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-wecom-sdk 2.0.2
File Size Uploaded Provenance Actions
py_wecom_sdk-2.0.2.tar.gz 25.3 kB Without provenance Details for py_wecom_sdk-2.0.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for py-wecom-sdk 2.0.2
File Interpreter ABI Platform Actions
py_wecom_sdk-2.0.2-py3-none-any.whl Python 3 none any Details for py_wecom_sdk-2.0.2-py3-none-any.whl

Total release size: 46.5 kB

Release files / py_wecom_sdk-2.0.2.tar.gz

Download URL py_wecom_sdk-2.0.2.tar.gz
Size 25.3 kB
Tags Source
SHA-256 checksum
How to use checksums
aebd7a0d5ccc9edb7cffd56c3515902ba47c2b98969ad9ac83e8567581394460
BLAKE2b-256 checksum
How to use checksums
d5c2d6ba03b2ef3a846d22c1d874139efe939d1d57cad9002fa98d30ec347adf
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.2-py3-none-any.whl

Download URL py_wecom_sdk-2.0.2-py3-none-any.whl
Size 21.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
170db5989e7439069d9be9fb73c24ce8978d338deaf88aabe9ca299f99592aec
BLAKE2b-256 checksum
How to use checksums
3eab9eaad1c98c683756c81170284cf1fcecc8ac628b522fc295db014906bedc
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.2

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page