Skip to main content

py_wecom_sdk

Python License httpx 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

pip install py-wecom-sdk

使用 uv(推荐)

uv add py-wecom-sdk

安装可选依赖

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

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

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

🚀 快速开始

同步客户端

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: ...

异步客户端

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),你可以直接传入符合企业微信协议的字典:

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

📖 功能清单

GroupRobotAPI / GroupRobotAsyncAPI

方法 功能 官方文档
send(payload) 发送任意类型消息(原始 dict) —
send_text(content, mentioned_list, mentioned_mobile_list) 文本消息,支持 @ 指定成员 文本类型
send_markdown(content) Markdown 消息 Markdown 类型
send_markdown_v2(content) Markdown V2 消息 Markdown V2
send_image(base64, md5) 图片消息(限 2MB,JPG / PNG) 图片类型
send_news(articles) 图文消息(1-8 条) 图文类型
send_file(media_id) 文件消息(需先上传) 文件类型
send_voice(media_id) 语音消息(需先上传) 语音类型
send_template_card(card) 模板卡片(text_notice / news_notice) 模板卡片
upload_media(media, filename, media_type) 上传文件 / 语音素材,返回 media_id 文件上传接口

send_text 默认 @ 配置

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

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 非空:

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)

🛠️ 开发

环境准备

# 克隆仓库
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

代码质量

# Ruff:lint(修复) + format
uv run ruff check --fix src tests
uv run ruff format src tests

# Mypy(strict 模式)
uv run mypy src

测试

# 运行全部测试(离线,使用 respx mock)
uv run pytest

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

示例运行

# 编辑 .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

构建发布

# 构建 wheel + sdist
uv build

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

📋 路线图

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

📄 许可证

本项目基于 MIT License 开源,详见 LICENSE。

📎 相关链接

Metadata

Release files for py-wecom-sdk 0.1.0

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 0.1.0
File Size Uploaded Provenance Actions
py_wecom_sdk-0.1.0.tar.gz 17.6 kB Without provenance Details for py_wecom_sdk-0.1.0.tar.gz

Built distribution (wheel)

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

Total release size: 30.2 kB

Release files / py_wecom_sdk-0.1.0.tar.gz

Download URL py_wecom_sdk-0.1.0.tar.gz
Size 17.6 kB
Tags Source
SHA-256 checksum
How to use checksums
c742b92453dbffcb66b227b46ed89648fe51c61949cb26bb28ce9f08c5cb4335
BLAKE2b-256 checksum
How to use checksums
526680e8535498f33b2011daa72e6e3f08032101252af0864d9327c6be85d5f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / py_wecom_sdk-0.1.0-py3-none-any.whl

Download URL py_wecom_sdk-0.1.0-py3-none-any.whl
Size 12.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ace98aa55513ace3126733159ed1d98c2b6893aced98bd26f36d6642736ea1a9
BLAKE2b-256 checksum
How to use checksums
e410f5c176d90e0b1c015c72f0e7c0156aa40044a1342823d8b45e075087798a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for py-wecom-sdk 0.1.0

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