Metadata-Version: 2.1
Name: py-wecom-toolkit
Version: 3.0.0
Summary: 企业微信 Python 扩展包 - 支持 Webhook 与 Server 端 API
Project-URL: Homepage, https://gitee.com/guolei19850528/py_wecom_toolkit
Project-URL: Documentation, https://gitee.com/guolei19850528/py_wecom_toolkit#readme
Author-email: 郭磊 <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2024 py-wecom-toolkit
        
        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.
License-File: LICENSE
Keywords: enterprise,webhook,wechat,wecom,work
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
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
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: server
Requires-Dist: diskcache>=5.6.0; extra == 'server'
Requires-Dist: redis>=5.0.0; extra == 'server'
Description-Content-Type: text/markdown

# py-wecom-toolkit

企业微信 Python 扩展包 - 支持 Webhook 与 Server 端 API.

- **版本**: 3.0.0
- **作者**: 郭磊
- **邮箱**: 174000902@qq.com
- **项目主页**: https://gitee.com/guolei19850528/py_wecom_toolkit

## 安装

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

安装包含 Server 端支持 (diskcache / redis 缓存):

```bash
pip install py-wecom-toolkit[server]
```

## 功能特性

- 支持全部 8 种 Webhook 消息类型: text, markdown, markdown_v2, image, news, file, voice, template_card
- 基于 pydantic v2 的消息模型验证
- 基于 httpx 的异步 HTTP 客户端
- 独立的 Webhook Server 模块 (FastAPI)
- 文件上传接口
- 完整的类型注解
- **Server 端 API**: access_token 管理 (支持 memory/diskcache/redis 缓存)、接口 IP 段、回调 IP 段、应用消息发送、素材上传/下载
- 同步与异步客户端双模式支持

## 快速开始

### Webhook 消息发送

```python
import asyncio
from py_wecom_toolkit import WebhookClient

async def main():
    client = WebhookClient(key="你的webhook_key")

    # 发送文本消息
    await client.send_text("Hello, World!")

    # 发送文本消息并 @某人
    await client.send_text(
        "你好, 请查看",
        mentioned_list=["zhangsan"],
        mentioned_mobile_list=["13800001111"],
    )

    # 发送 Markdown 消息
    await client.send_markdown(
        '实时新增用户反馈<font color="warning">132例</font>'
    )

    # 发送图文消息
    await client.send_news([{
        "title": "中秋节礼品领取",
        "description": "今年中秋节公司有豪礼相送",
        "url": "https://work.weixin.qq.com",
        "picurl": "https://example.com/pic.png",
    }])

    # 发送图片
    await client.send_image("/path/to/image.png")

    # 上传文件并发送
    media_id = await client.upload_media("/path/to/file.pdf")
    await client.send_file(media_id)

    await client.close()

asyncio.run(main())
```

### Server 端 API (同步)

```python
from py_wecom_toolkit import WeComServerClient

# 关键配置请通过环境变量或配置文件读取，不要硬编码在代码中
client = WeComServerClient(
    corpid="你的CorpID",
    corpsecret="你的CorpSecret",
    agentid="你的AgentID",
)

# 获取 access_token (自动缓存)
token = client.get_access_token()
print(f"access_token: {token}")

# 获取企业微信接口 IP 段
iplist = client.get_iplist()
print(f"接口 IP 段: {iplist.ip_list}")

# 获取企业微信回调 IP 段
callback_ip = client.get_callback_ip()
print(f"回调 IP 段: {callback_ip.ip_list}")

# 发送文本应用消息
resp = client.send_text(
    content="Hello, WeCom!",
    touser="Guolei",
)
print(f"发送结果: {resp.errmsg}")

# 上传素材并发送文件消息
media = client.upload_media("/path/to/README.md", media_type="file")
resp = client.send_file(media.media_id, touser="Guolei")
print(f"发送文件结果: {resp.errmsg}")

client.close()
```

### Server 端 API (异步)

```python
import asyncio
from py_wecom_toolkit import AsyncWeComServerClient

async def main():
    client = AsyncWeComServerClient(
        corpid="你的CorpID",
        corpsecret="你的CorpSecret",
        agentid="你的AgentID",
    )

    # 获取 access_token (自动缓存)
    token = await client.async_get_access_token()
    print(f"access_token: {token}")

    # 获取接口 IP 段
    iplist = await client.async_get_iplist()
    print(f"接口 IP 段: {iplist.ip_list}")

    # 发送文本应用消息
    resp = await client.async_send_text(
        content="Hello, WeCom Async!",
        touser="Guolei",
    )
    print(f"发送结果: {resp.errmsg}")

    # 上传素材并发送文件消息
    media = await client.async_upload_media("/path/to/README.md", media_type="file")
    resp = await client.async_send_file(media.media_id, touser="Guolei")
    print(f"发送文件结果: {resp.errmsg}")

    await client.close()

asyncio.run(main())
```

### 高级用法

```python
import httpx
from py_wecom_toolkit import WebhookClient

# 使用自定义 httpx 客户端
async with httpx.AsyncClient(timeout=30.0) as http_client:
    client = WebhookClient(key="xxx", client=http_client)
    await client.send_text("使用自定义客户端")

# 使用上下文管理器
async with WebhookClient(key="xxx") as client:
    await client.send_text("自动管理连接池")
```

## API 参考

### WebhookClient

| 方法 | 说明 |
|------|------|
| `send(message)` | 发送任意类型的消息 |
| `send_text(content, ...)` | 发送文本消息 |
| `send_markdown(content)` | 发送 Markdown 消息 |
| `send_markdown_v2(content)` | 发送 Markdown V2 消息 |
| `send_image(path)` | 发送图片消息 |
| `send_news(articles)` | 发送图文消息 |
| `send_file(media_id)` | 发送文件消息 |
| `send_voice(media_id)` | 发送语音消息 |
| `send_template_card(card)` | 发送模版卡片消息 |
| `upload_media(path, type)` | 上传媒体文件 |

### WeComServerClient / AsyncWeComServerClient

| 方法 | 说明 |
|------|------|
| `get_access_token()` / `async_get_access_token()` | 获取 access_token (自动缓存) |
| `get_iplist()` / `async_get_iplist()` | 获取企业微信接口 IP 段 |
| `get_callback_ip()` / `async_get_callback_ip()` | 获取企业微信回调 IP 段 |
| `send_text(content, touser, ...)` / `async_send_text(...)` | 发送文本应用消息 |
| `send_message(request)` / `async_send_message(request)` | 发送任意类型应用消息 |
| `send_file(media_id, touser, ...)` / `async_send_file(...)` | 发送文件应用消息 |
| `upload_media(path, type)` / `async_upload_media(path, type)` | 上传临时素材 |
| `download_media(media_id)` / `async_download_media(media_id)` | 下载临时素材 |

## 示例代码

查看 `examples/server/` 目录下的完整示例代码.

## 消息类型参考

参考 [企业微信文档](https://developer.work.weixin.qq.com/document/path/91770) 获取 Webhook 消息格式说明.

参考 [企业微信服务端API](https://developer.work.weixin.qq.com/document/path/90664) 获取 Server 端 API 说明.

## License

MIT
