Metadata-Version: 2.1
Name: py_wecom_toolkit
Version: 4.2.1
Summary: 企业微信 API 工具包
Project-URL: HomePage, https://gitee.com/guolei19850528/py_wecom_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_wecom_toolkit
Author-email: 郭磊 <174000902@qq.com>
License: MIT
License-File: LICENSE
Keywords: 企业微信,企业微信API,企业微信工具
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Communications :: Chat
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: diskcache>=5.6.0
Requires-Dist: httpx<1.0,>=0.24.0
Requires-Dist: pydantic<3.0,>=2.0.0
Requires-Dist: redis>=5.0.0
Provides-Extra: all
Requires-Dist: py-wecom-toolkit[dev,docs,test]; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pre-commit>=3.7.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
Requires-Dist: ruff>=0.8.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'test'
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
Requires-Dist: pytest>=8.0.0; extra == 'test'
Requires-Dist: python-dotenv>=1.0.0; extra == 'test'
Requires-Dist: respx>=0.21.0; extra == 'test'
Description-Content-Type: text/markdown

# py_wecom_toolkit

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

[中文](README.md) | [English](README.en.md)

`py_wecom_toolkit` 是一个企业微信（WeCom）API 工具包，提供同步和异步客户端，支持企业应用 API 及群机器人 Webhook。

## 功能

- **企业应用 API**：获取并缓存 `access_token`，发送应用消息，上传和下载素材。
- **Webhook**：发送文本、Markdown、Markdown V2、图片、图文、文件、语音和模板卡片消息，并上传媒体文件。
- **同步与异步客户端**：均支持上下文管理器以自动关闭 HTTP 连接。
- **类型模型**：基于 Pydantic 定义请求和响应模型。

## 安装

```bash
pip install py_wecom_toolkit
```

使用 uv：

```bash
uv add py_wecom_toolkit
```

需要开发与测试工具时，从仓库安装：

```bash
uv sync --extra dev --extra test
```

## 包结构

```text
src/py_wecom_toolkit/
├── __init__.py
├── py.typed
├── server/
│   ├── __init__.py
│   ├── _caches.py
│   ├── _clients.py
│   ├── _models.py
│   ├── materials/
│   │   ├── __init__.py
│   │   ├── _clients.py
│   │   └── _models.py
│   └── messages/
│       ├── __init__.py
│       ├── _clients.py
│       └── _msgtypes.py
└── webhook/
    ├── __init__.py
    ├── _clients.py
    ├── _models.py
    └── _msgtypes.py

examples/
├── server/
│   ├── access_token.py
│   ├── material.py
│   ├── message.py
│   └── .env.example
└── webhook/
    ├── text.py
    ├── markdown.py
    ├── markdown_v2.py
    ├── image.py
    ├── news.py
    ├── file.py
    ├── voice.py
    ├── template_card.py
    ├── upload_media.py
    └── .env.example

tests/
├── server/
│   ├── conftest.py
│   ├── test_sync_*.py
│   ├── test_async_*.py
│   └── .env.example
└── webhook/
    ├── conftest.py
    ├── test_sync_*.py
    ├── test_async_*.py
    └── .env.example
```

包根导出 `server` 和 `webhook` 两个模块。各模块对外公开的名称带有 `Server`、`ServerMessage`、`ServerMaterial` 或 `Webhook` 前缀，避免名称冲突；`_` 开头的文件是内部实现模块。

## 使用

### 企业应用 API

应用客户端默认使用 diskcache 缓存 `access_token`，也可通过 `cache` 参数传入自定义缓存。

```python
from py_wecom_toolkit.server import ServerClient

with ServerClient(corpid="YOUR_CORPID", corpsecret="YOUR_CORPSECRET") as client:
    response = client.get_access_token()
    if response.ok:
        print(response.access_token)
```

发送应用文本消息：

```python
from py_wecom_toolkit.server.messages import (
    ServerMessageClient,
    ServerMessageTextMessage,
)

message = ServerMessageTextMessage(
    touser="USER_ID",
    agentid=1000001,
    text={"content": "Hello, WeCom!"},
)
with ServerMessageClient(
    corpid="YOUR_CORPID",
    corpsecret="YOUR_CORPSECRET",
    agentid=1000001,
) as client:
    response = client.send(message)
    print(response.ok, response.errmsg)
```

对应的异步客户端为 `ServerAsyncClient` 和 `ServerMessageAsyncClient`，可分别从 `py_wecom_toolkit.server` 和 `py_wecom_toolkit.server.messages` 导入。

应用消息模型包括文本、图片、语音、视频、文件、文本卡片、图文和 Markdown。素材客户端 `ServerMaterialClient` / `ServerMaterialAsyncClient` 提供临时素材上传、图片上传和素材下载。

### 群机器人 Webhook

Webhook 使用群机器人 URL 中的 key，不需要企业 ID 或应用凭证：

```python
from py_wecom_toolkit.webhook import WebhookClient

with WebhookClient(key="YOUR_WEBHOOK_KEY") as client:
    response = client.send_text("Hello, WeCom!")
    print(response.ok, response.errmsg)
```

异步用法：

```python
import asyncio

from py_wecom_toolkit.webhook import WebhookAsyncClient


async def main() -> None:
    async with WebhookAsyncClient(key="YOUR_WEBHOOK_KEY") as client:
        response = await client.send_markdown("**Hello, WeCom!**")
        print(response.ok, response.errmsg)


asyncio.run(main())
```

Webhook 客户端还提供 `send_markdown_v2`、`send_image`、`send_news`、`send_file`、`send_voice`、`send_template_card` 和 `upload_media` 方法。

## 配置示例与测试

示例脚本读取环境变量；仓库提供 [examples/server/.env.example](examples/server/.env.example) 和 [examples/webhook/.env.example](examples/webhook/.env.example) 作为配置模板。将所需变量设置在仓库根目录的 `.env` 中，或在运行脚本前导出环境变量。

测试配置分别位于 [tests/server/.env.example](tests/server/.env.example) 和 [tests/webhook/.env.example](tests/webhook/.env.example)。复制到对应测试目录的 `.env` 并填入有效凭证。server 配置包含 `CORPID`、`CORPSECRET`、`AGENTID`、`TOUSER` 和 `INVALID_AGENTID`；Webhook 使用 `KEY`。

**注意：测试会向真实企业微信 API 发起网络请求，并可能发送消息、上传文件。** 图片素材测试还要求本机存在 `/tmp/wecom_date_image.jpg`。

```bash
pytest
```

测试配置在缺少必需环境变量时会跳过相应测试。pytest 默认配置会输出终端、HTML 和 XML 覆盖率报告。

## 开发

```bash
ruff check .
ruff format --check .
python -m compileall -q src examples tests
```

项目支持 Python 3.9 及以上版本。核心依赖包括 httpx、Pydantic、diskcache 和 redis；开发、测试、文档工具可通过 `pyproject.toml` 中的可选依赖组安装。

## 许可证

本项目基于 [MIT 许可证](LICENSE) 开源。
