Metadata-Version: 2.4
Name: py-wecom
Version: 0.1.6
Summary: 企业微信 SDK，提供企业微信 API 的 Python 封装，支持同步和异步调用。
Author-email: Guolei <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2026 郭磊
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://gitee.com/guolei19850528/py_wecom
Project-URL: Repository, https://gitee.com/guolei19850528/py_wecom.git
Project-URL: Documentation, https://gitee.com/guolei19850528/py_wecom
Keywords: wecom,python,client,api,企业微信,异步调用,server,消息推送,文件上传,webhook,机器人
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Topic :: Communications
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0
Requires-Dist: jsonpath-ng>=1.5.3
Requires-Dist: jsonschema>=4.21.0
Requires-Dist: diskcache>=5.6.3
Requires-Dist: redis>=4.6.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Dynamic: license-file

# py-wecom

企业微信 SDK，提供企业微信 API 的 Python 封装，支持同步和异步调用。

## 功能特性

- **Webhook API**: 企业微信机器人 Webhook 接口，支持多种消息类型
- **Server API**: 企业微信服务端 API，支持消息发送、素材上传等
- **同步/异步支持**: 所有接口均提供同步和异步版本
- **类型安全**: 使用 Pydantic 进行数据验证，提供完整的类型提示
- **缓存支持**: 支持 Redis 和 diskcache 缓存 access_token
- **模板卡片**: 支持文本通知型、图文展示型等多种模板卡片样式

## 安装

```bash
pip install py-wecom
```

或使用 uv：

```bash
uv add py-wecom
```

## 快速开始

### Webhook API

```python
from py_wecom.webhook import Webhook
from py_wecom.webhook.messages import Text, TextContent
from py_wecom.webhook.utils import convert_to_send, errcode_eq_0_validator

webhook = Webhook(key="your_webhook_key")

response = webhook.send_text(
    content=Text(
        text=TextContent(
            content="Hello from py_wecom!",
            mentioned_list=["@all"]
        )
    )
)

result = convert_to_send(response)
if errcode_eq_0_validator(response):
    print(f"发送成功: {result.errmsg}")
else:
    print(f"发送失败: errcode={result.errcode}, errmsg={result.errmsg}")
```

### Server API

```python
import diskcache
from py_wecom.server import Base
from py_wecom.server.messages import Sender, Text, TextContent
from py_wecom.server.utils import convert_to_errcode_eq_0, errcode_eq_0_validator
diskcache_default=diskcache.Cache()
server = Base(corpid="your_corpid", corpsecret="your_corpsecret", cache_config={"instance": diskcache_default})
server.refresh_access_token()

sender = Sender(corpid="your_corpid", corpsecret="your_corpsecret", agentid="your_agentid", cache_config={"instance": diskcache_default})
sender.refresh_access_token()

response = sender.send_text(
    content=Text(
        text=TextContent(content="Hello from py-wecom!")
    )
)

result = convert_to_errcode_eq_0(response)
assert errcode_eq_0_validator(response), f"发送失败: {result.errmsg}"
```

## 支持的消息类型

### Webhook API

| 消息类型 | 说明 | 参考文档 |
|---------|------|---------|
| Text | 文本消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E6%96%87%E6%9C%AC%E6%B6%88%E6%81%AF) |
| Markdown | Markdown消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#markdown%E6%B6%88%E6%81%AF) |
| MarkdownV2 | MarkdownV2消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#markdownv2%E6%B6%88%E6%81%AF) |
| Image | 图片消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E5%9B%BE%E7%89%87%E6%B6%88%E6%81%AF) |
| News | 图文消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E5%9B%BE%E6%96%87%E6%B6%88%E6%81%AF) |
| File | 文件消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E6%96%87%E4%BB%B6%E6%B6%88%E6%81%AF) |
| Voice | 语音消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF) |
| TemplateCard | 模板卡片消息 | [文档](https://developer.work.weixin.qq.com/document/path/91770#%E6%A8%A1%E6%9D%BF%E5%8D%A1%E7%89%87%E6%B6%88%E6%81%AF) |

### Server API

| 消息类型 | 说明 | 参考文档 |
|---------|------|---------|
| Text | 文本消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E6%96%87%E6%9C%AC%E6%B6%88%E6%81%AF) |
| Image | 图片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E5%9B%BE%E7%89%87%E6%B6%88%E6%81%AF) |
| Voice | 语音消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E8%AF%AD%E9%9F%B3%E6%B6%88%E6%81%AF) |
| Video | 视频消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E8%A7%86%E9%A2%91%E6%B6%88%E6%81%AF) |
| File | 文件消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E6%96%87%E4%BB%B6%E6%B6%88%E6%81%AF) |
| TextCard | 文本卡片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E6%96%87%E6%9C%AC%E5%8D%A1%E7%89%87%E6%B6%88%E6%81%AF) |
| News | 图文消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E5%9B%BE%E6%96%87%E6%B6%88%E6%81%AF) |
| MpNews | 图文消息(mpnews) | [文档](https://developer.work.weixin.qq.com/document/path/90236#mpnews%E6%B6%88%E6%81%AF) |
| Markdown | Markdown消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#markdown%E6%B6%88%E6%81%AF) |
| MiniprogramNotice | 小程序通知 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E5%B0%8F%E7%A8%8B%E5%BA%8F%E9%80%9A%E7%9F%A5) |
| TemplateCard | 模板卡片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236#%E6%A8%A1%E6%9D%BF%E5%8D%A1%E7%89%87%E6%B6%88%E6%81%AF) |

## 使用示例

### 发送模板卡片消息 (Webhook)

```python
from py_wecom.webhook import Webhook
from py_wecom.webhook.messages import TemplateCard, TextNoticeTemplateCardContent
from py_wecom.webhook.utils import convert_to_send, errcode_eq_0_validator

webhook = Webhook(key="your_webhook_key")

response = webhook.send_template_card(
    content=TemplateCard(
        template_card=TextNoticeTemplateCardContent(
            title="系统告警",
            content="CPU使用率达到90%",
            emphasis_content={"title": "紧急", "description": "请及时处理"},
            card_action={"type": 1, "url": "https://example.com"}
        )
    )
)

result = convert_to_send(response)
assert errcode_eq_0_validator(response), f"发送失败: {result.errmsg}"
```

### 发送文件消息 (Webhook)

```python
from py_wecom.webhook import Webhook
from py_wecom.webhook.messages import File, FileContent
from py_wecom.webhook.utils import convert_to_upload_media, convert_to_send, errcode_eq_0_validator

webhook = Webhook(key="your_webhook_key")

with open("test.txt", "rb") as f:
    upload_response = webhook.upload_media(files={"file": ("test.txt", f)})

upload_result = convert_to_upload_media(upload_response)
assert errcode_eq_0_validator(upload_response), f"上传失败: {upload_result.errmsg}"

response = webhook.send_file(
    content=File(file=FileContent(media_id=upload_result.media_id))
)

result = convert_to_send(response)
assert errcode_eq_0_validator(response), f"发送失败: {result.errmsg}"
```

### 使用缓存 (Server API)

```python
import redis
from py_wecom.server import Base

redis_client = redis.Redis(host="localhost", port=6379, db=0)

server = Base(
    corpid="xxx",
    corpsecret="xxx",
    agentid="xxx",
    cache_config={
        "instance": redis_client,
        "key": "pywecom_access_token",
        "expire": 7100
    }
)

server.refresh_access_token()
```

## 异步支持

所有方法均提供异步版本，方法名以 `async_` 开头：

### Webhook API 异步示例

```python
import asyncio
from py_wecom.webhook import Webhook
from py_wecom.webhook.messages import Text, TextContent

async def main():
    webhook = Webhook(key="your_webhook_key")
    
    response = await webhook.async_send_text(
        content=Text(text=TextContent(content="async hello world"))
    )
    print(response.json())

asyncio.run(main())
```

### Server API 异步示例

```python
import asyncio
from py_wecom.server import Base, Sender, Text, TextContent

async def main():
    server = Base(corpid="xxx", corpsecret="xxx")
    await server.async_refresh_access_token()
    
    sender = Sender(corpid="xxx", corpsecret="xxx", agentid="xxx")
    await sender.async_refresh_access_token()
    
    response = await sender.async_send_text(
        content=Text(text=TextContent(content="Hello!"))
    )
    print(response.json())

asyncio.run(main())
```

## 项目结构

```
py_wecom/
├── src/
│   └── py_wecom/
│       ├── __init__.py
│       ├── server/           # Server API
│       │   ├── __init__.py   # Base 类，access_token 管理
│       │   ├── materials.py  # 素材上传
│       │   ├── messages.py   # 消息类型和发送
│       │   ├── responses.py  # 响应模型
│       │   └── utils.py      # 工具函数
│       └── webhook/          # Webhook API
│           ├── __init__.py   # Webhook 客户端
│           ├── messages.py   # 消息类型
│           ├── responses.py  # 响应模型
│           └── utils.py      # 工具函数
├── tests/
│   ├── webhook/              # Webhook 测试
│   ├── server/               # Server 测试
│   └── conftest.py           # 测试配置
├── pyproject.toml
├── README.md
└── LICENSE
```

## API 文档

### Webhook API

#### Webhook 类

**构造函数**: `Webhook(base_url, key, mentioned_list, mentioned_mobile_list, client_kwargs)`

| 参数 | 类型 | 说明 |
|------|------|------|
| `base_url` | `str` | 企业微信API基础URL，默认 `https://qyapi.weixin.qq.com/cgi-bin/webhook/` |
| `key` | `str` | Webhook密钥 |
| `mentioned_list` | `List[str]` | 默认@用户列表（用户ID） |
| `mentioned_mobile_list` | `List[str]` | 默认@用户列表（手机号） |
| `client_kwargs` | `dict` | HTTP客户端配置参数 |

**同步方法**:

| 方法 | 说明 | 参数 |
|------|------|------|
| `send(client, **kwargs)` | 发送消息 | `client`: HTTP客户端实例 |
| `upload_media(client, ft, **kwargs)` | 上传媒体文件 | `ft`: 文件类型(voice/file) |
| `send_text(client, content, **kwargs)` | 发送文本消息 | `content`: Text对象 |
| `send_markdown(client, content, **kwargs)` | 发送Markdown消息 | `content`: Markdown对象 |
| `send_markdown_v2(client, content, **kwargs)` | 发送MarkdownV2消息 | `content`: MarkdownV2对象 |
| `send_image(client, content, **kwargs)` | 发送图片消息 | `content`: Image对象 |
| `send_news(client, content, **kwargs)` | 发送图文消息 | `content`: News对象 |
| `send_file(client, content, **kwargs)` | 发送文件消息 | `content`: File对象 |
| `send_voice(client, content, **kwargs)` | 发送语音消息 | `content`: Voice对象 |
| `send_template_card(client, content, **kwargs)` | 发送模板卡片消息 | `content`: TemplateCard对象 |

**异步方法**:

| 方法 | 说明 |
|------|------|
| `async_send(client, **kwargs)` | 异步发送消息 |
| `async_upload_media(client, ft, **kwargs)` | 异步上传媒体文件 |
| `async_send_text(client, content, **kwargs)` | 异步发送文本消息 |
| `async_send_markdown(client, content, **kwargs)` | 异步发送Markdown消息 |
| `async_send_markdown_v2(client, content, **kwargs)` | 异步发送MarkdownV2消息 |
| `async_send_image(client, content, **kwargs)` | 异步发送图片消息 |
| `async_send_news(client, content, **kwargs)` | 异步发送图文消息 |
| `async_send_file(client, content, **kwargs)` | 异步发送文件消息 |
| `async_send_voice(client, content, **kwargs)` | 异步发送语音消息 |
| `async_send_template_card(client, content, **kwargs)` | 异步发送模板卡片消息 |

#### Webhook 工具函数

| 函数 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `convert_to_send(response)` | 转换为Send响应模型 | `response`: httpx.Response或dict | Send对象 |
| `convert_to_upload_media(response)` | 转换为UploadMedia响应模型 | `response`: httpx.Response或dict | UploadMedia对象 |
| `errcode_eq_0_validator(response, schema)` | 校验errcode是否为0 | `response`: httpx.Response或dict | bool |
| `image_to_base64_and_md5(image_path)` | 图片转Base64和MD5 | `image_path`: 图片路径 | Tuple[str, str] |
| `json_find_first(expression, data)` | JSONPath查找 | `expression`: JSONPath表达式 | Any |

#### Webhook 响应模型

**Send** - 消息发送响应

| 字段 | 类型 | 说明 |
|------|------|------|
| `errcode` | `int` | 错误码，0表示成功 |
| `errmsg` | `str` | 错误信息 |

**UploadMedia** - 媒体文件上传响应

| 字段 | 类型 | 说明 |
|------|------|------|
| `errcode` | `int` | 错误码，0表示成功 |
| `media_id` | `str` | 媒体文件ID |
| `type` | `str` | 文件类型 |
| `created_at` | `int` | 创建时间戳 |

### Server API

#### Base 类

**构造函数**: `Base(base_url, corpid, corpsecret, agentid, cache_config, client_kwargs)`

| 参数 | 类型 | 说明 |
|------|------|------|
| `base_url` | `str` | API基础URL，默认 `https://qyapi.weixin.qq.com` |
| `corpid` | `str` | 企业ID |
| `corpsecret` | `str` | 应用密钥 |
| `agentid` | `str/int` | 企业应用ID |
| `cache_config` | `dict` | 缓存配置 |
| `client_kwargs` | `dict` | HTTP客户端配置 |

**方法**:

| 方法 | 说明 | 参考文档 |
|------|------|---------|
| `gettoken(client, **kwargs)` | 获取access_token | [文档](https://developer.work.weixin.qq.com/document/path/91039) |
| `refresh_access_token()` | 刷新access_token | [文档](https://developer.work.weixin.qq.com/document/path/91039) |
| `get_api_domain_ip(client, **kwargs)` | 获取API域名IP | [文档](https://developer.work.weixin.qq.com/document/path/92520) |
| `getcallbackip(client, **kwargs)` | 获取回调IP | [文档](https://developer.work.weixin.qq.com/document/path/92521) |
| `async_gettoken(client, **kwargs)` | 异步获取access_token | [文档](https://developer.work.weixin.qq.com/document/path/91039) |
| `async_refresh_access_token()` | 异步刷新access_token | [文档](https://developer.work.weixin.qq.com/document/path/91039) |

#### Sender 类

**继承**: `Base`

**同步方法**:

| 方法 | 说明 | 参考文档 |
|------|------|---------|
| `send_text(client, content, **kwargs)` | 发送文本消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_markdown(client, content, **kwargs)` | 发送Markdown消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_image(client, content, **kwargs)` | 发送图片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_voice(client, content, **kwargs)` | 发送语音消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_video(client, content, **kwargs)` | 发送视频消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_file(client, content, **kwargs)` | 发送文件消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_textcard(client, content, **kwargs)` | 发送文本卡片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_news(client, content, **kwargs)` | 发送图文消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_mpnews(client, content, **kwargs)` | 发送mpnews消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_miniprogram_notice(client, content, **kwargs)` | 发送小程序通知 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |
| `send_template_card(client, content, **kwargs)` | 发送模板卡片消息 | [文档](https://developer.work.weixin.qq.com/document/path/90236) |

**异步方法**: 所有同步方法均有对应的异步版本，方法名以 `async_` 开头

#### Uploader 类

**继承**: `Base`

**同步方法**:

| 方法 | 说明 | 参考文档 |
|------|------|---------|
| `upload(client, ft, **kwargs)` | 上传临时素材 | [文档](https://developer.work.weixin.qq.com/document/path/90253) |
| `uploadimg(client, **kwargs)` | 上传图片素材 | [文档](https://developer.work.weixin.qq.com/document/path/90256) |

**异步方法**:

| 方法 | 说明 |
|------|------|
| `async_upload(client, ft, **kwargs)` | 异步上传临时素材 |
| `async_uploadimg(client, **kwargs)` | 异步上传图片素材 |

#### Server 工具函数

| 函数 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `convert_to_errcode_eq_0(response)` | 转换为ERRCODE_EQ_0响应模型 | `response`: httpx.Response或dict | ERRCODE_EQ_0对象 |
| `errcode_eq_0_validator(response, schema)` | 校验errcode是否为0 | `response`: httpx.Response或dict | bool |
| `json_find_first(expression, data)` | JSONPath查找 | `expression`: JSONPath表达式 | Any |

## 参考文档

- [企业微信开发者文档](https://developer.work.weixin.qq.com/document/path/90238)
- [企业微信机器人文档](https://developer.work.weixin.qq.com/document/path/91770)
- [企业微信Server API文档](https://developer.work.weixin.qq.com/document/path/90664)

## 许可证

MIT License

## 作者

Guolei <174000902@qq.com>
