wechatapilabs 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""WeChatAPI Labs 接口的 Python SDK。文档:https://wechatapilabs.com/zh/docs/"""
|
|
2
|
+
from .client import WeChatAPI, WeChatAPIError, DEFAULT_BASE_URL
|
|
3
|
+
from .webhook import verify_webhook
|
|
4
|
+
|
|
5
|
+
__all__ = ["WeChatAPI", "WeChatAPIError", "DEFAULT_BASE_URL", "verify_webhook"]
|
|
6
|
+
__version__ = "0.1.0"
|
wechatapilabs/client.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Any, Dict, Iterator, List, Optional
|
|
3
|
+
|
|
4
|
+
import requests
|
|
5
|
+
|
|
6
|
+
DEFAULT_BASE_URL = "https://api.wechatapilabs.com"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class WeChatAPIError(Exception):
|
|
10
|
+
"""接口返回非 0 的 code 或 HTTP 错误时抛出。"""
|
|
11
|
+
|
|
12
|
+
def __init__(self, message: str, code: Optional[int] = None, request_id: Optional[str] = None,
|
|
13
|
+
status: Optional[int] = None, retry_after: Optional[float] = None, data: Any = None):
|
|
14
|
+
super().__init__(message)
|
|
15
|
+
self.code = code
|
|
16
|
+
self.request_id = request_id
|
|
17
|
+
self.status = status
|
|
18
|
+
self.retry_after = retry_after
|
|
19
|
+
self.data = data
|
|
20
|
+
|
|
21
|
+
def __str__(self) -> str:
|
|
22
|
+
return f"[{self.code}] {self.args[0]} (request_id={self.request_id})"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _clean(d: Dict[str, Any]) -> Dict[str, Any]:
|
|
26
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _Group:
|
|
30
|
+
def __init__(self, c: "WeChatAPI"):
|
|
31
|
+
self._c = c
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class Account(_Group):
|
|
35
|
+
def login_qrcode(self, type: str, callback_url: Optional[str] = None):
|
|
36
|
+
return self._c.request("POST", "/v1/account/login_qrcode", _clean({"type": type, "callback_url": callback_url}))
|
|
37
|
+
|
|
38
|
+
def status(self, account_id: str):
|
|
39
|
+
return self._c.request("GET", "/v1/account/status", {"account_id": account_id})
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Message(_Group):
|
|
43
|
+
def send_text(self, account_id: str, to: str, content: str, at: Optional[List[str]] = None):
|
|
44
|
+
return self._c.request("POST", "/v1/message/send_text",
|
|
45
|
+
_clean({"account_id": account_id, "to": to, "content": content, "at": at}))
|
|
46
|
+
|
|
47
|
+
def send_image(self, account_id: str, to: str, image_url: Optional[str] = None, image_base64: Optional[str] = None):
|
|
48
|
+
if not (image_url or image_base64):
|
|
49
|
+
raise ValueError("image_url 和 image_base64 必须填一个")
|
|
50
|
+
return self._c.request("POST", "/v1/message/send_image", _clean(
|
|
51
|
+
{"account_id": account_id, "to": to, "image_url": image_url, "image_base64": image_base64}))
|
|
52
|
+
|
|
53
|
+
def send_file(self, account_id: str, to: str, file_url: str, file_name: str):
|
|
54
|
+
return self._c.request("POST", "/v1/message/send_file",
|
|
55
|
+
{"account_id": account_id, "to": to, "file_url": file_url, "file_name": file_name})
|
|
56
|
+
|
|
57
|
+
def send_link(self, account_id: str, to: str, title: str, url: str, desc: Optional[str] = None,
|
|
58
|
+
thumb_url: Optional[str] = None):
|
|
59
|
+
return self._c.request("POST", "/v1/message/send_link", _clean(
|
|
60
|
+
{"account_id": account_id, "to": to, "title": title, "url": url, "desc": desc, "thumb_url": thumb_url}))
|
|
61
|
+
|
|
62
|
+
def revoke(self, account_id: str, msg_id: str):
|
|
63
|
+
return self._c.request("POST", "/v1/message/revoke", {"account_id": account_id, "msg_id": msg_id})
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Contact(_Group):
|
|
67
|
+
def friends(self, account_id: str, cursor: Optional[str] = None, limit: Optional[int] = None):
|
|
68
|
+
return self._c.request("GET", "/v1/contact/friends",
|
|
69
|
+
_clean({"account_id": account_id, "cursor": cursor, "limit": limit}))
|
|
70
|
+
|
|
71
|
+
def iter_friends(self, account_id: str, limit: int = 100) -> Iterator[Dict[str, Any]]:
|
|
72
|
+
cursor = None
|
|
73
|
+
while True:
|
|
74
|
+
page = self.friends(account_id, cursor=cursor, limit=limit)
|
|
75
|
+
for item in page.get("items") or []:
|
|
76
|
+
yield item
|
|
77
|
+
cursor = page.get("next_cursor")
|
|
78
|
+
if not cursor:
|
|
79
|
+
return
|
|
80
|
+
|
|
81
|
+
def accept(self, account_id: str, ticket: str, remark: Optional[str] = None):
|
|
82
|
+
return self._c.request("POST", "/v1/contact/accept",
|
|
83
|
+
_clean({"account_id": account_id, "ticket": ticket, "remark": remark}))
|
|
84
|
+
|
|
85
|
+
def remark(self, account_id: str, wxid: str, remark: Optional[str] = None, tags: Optional[List[str]] = None):
|
|
86
|
+
return self._c.request("POST", "/v1/contact/remark",
|
|
87
|
+
_clean({"account_id": account_id, "wxid": wxid, "remark": remark, "tags": tags}))
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Group(_Group):
|
|
91
|
+
def create(self, account_id: str, members: List[str], name: Optional[str] = None):
|
|
92
|
+
return self._c.request("POST", "/v1/group/create", _clean({"account_id": account_id, "members": members, "name": name}))
|
|
93
|
+
|
|
94
|
+
def invite(self, account_id: str, group_id: str, members: List[str]):
|
|
95
|
+
return self._c.request("POST", "/v1/group/invite", {"account_id": account_id, "group_id": group_id, "members": members})
|
|
96
|
+
|
|
97
|
+
def remove(self, account_id: str, group_id: str, members: List[str]):
|
|
98
|
+
return self._c.request("POST", "/v1/group/remove", {"account_id": account_id, "group_id": group_id, "members": members})
|
|
99
|
+
|
|
100
|
+
def notice(self, account_id: str, group_id: str, content: str):
|
|
101
|
+
return self._c.request("POST", "/v1/group/notice", {"account_id": account_id, "group_id": group_id, "content": content})
|
|
102
|
+
|
|
103
|
+
def members(self, account_id: str, group_id: str):
|
|
104
|
+
return self._c.request("GET", "/v1/group/members", {"account_id": account_id, "group_id": group_id})
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Moment(_Group):
|
|
108
|
+
def post(self, account_id: str, content: Optional[str] = None, images: Optional[List[str]] = None,
|
|
109
|
+
visible_tags: Optional[List[str]] = None):
|
|
110
|
+
return self._c.request("POST", "/v1/moment/post", _clean(
|
|
111
|
+
{"account_id": account_id, "content": content, "images": images, "visible_tags": visible_tags}))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class WeCom(_Group):
|
|
115
|
+
def group_send(self, account_id: str, group_id: str, type: str, payload: Dict[str, Any],
|
|
116
|
+
at: Optional[List[str]] = None):
|
|
117
|
+
return self._c.request("POST", "/v1/wecom/group/send", _clean(
|
|
118
|
+
{"account_id": account_id, "group_id": group_id, "type": type, "payload": payload, "at": at}))
|
|
119
|
+
|
|
120
|
+
def customers(self, account_id: str, cursor: Optional[str] = None, limit: Optional[int] = None):
|
|
121
|
+
return self._c.request("GET", "/v1/wecom/customers",
|
|
122
|
+
_clean({"account_id": account_id, "cursor": cursor, "limit": limit}))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class WeChatAPI:
|
|
128
|
+
"""https://api.wechatapilabs.com 的客户端,方法返回响应里的 `data` 字段。"""
|
|
129
|
+
|
|
130
|
+
def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, timeout: float = 10,
|
|
131
|
+
max_retries: int = 2, session: Optional[requests.Session] = None):
|
|
132
|
+
if not api_key:
|
|
133
|
+
raise ValueError("缺少 api_key")
|
|
134
|
+
self.base_url = base_url.rstrip("/")
|
|
135
|
+
self.timeout = timeout
|
|
136
|
+
self.max_retries = max_retries
|
|
137
|
+
self.session = session or requests.Session()
|
|
138
|
+
self.session.headers.update({"Authorization": f"Bearer {api_key}", "Accept": "application/json"})
|
|
139
|
+
self.account = Account(self)
|
|
140
|
+
self.message = Message(self)
|
|
141
|
+
self.contact = Contact(self)
|
|
142
|
+
self.group = Group(self)
|
|
143
|
+
self.moment = Moment(self)
|
|
144
|
+
self.wecom = WeCom(self)
|
|
145
|
+
|
|
146
|
+
def request(self, method: str, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
|
|
147
|
+
url = self.base_url + path
|
|
148
|
+
params = params or {}
|
|
149
|
+
attempt = 0
|
|
150
|
+
while True:
|
|
151
|
+
if method == "GET":
|
|
152
|
+
resp = self.session.get(url, params=params, timeout=self.timeout)
|
|
153
|
+
else:
|
|
154
|
+
resp = self.session.request(method, url, json=params, timeout=self.timeout)
|
|
155
|
+
try:
|
|
156
|
+
body = resp.json()
|
|
157
|
+
except ValueError:
|
|
158
|
+
body = None
|
|
159
|
+
code = body.get("code") if isinstance(body, dict) else None
|
|
160
|
+
if resp.ok and code == 0:
|
|
161
|
+
return body.get("data")
|
|
162
|
+
|
|
163
|
+
data = body.get("data") if isinstance(body, dict) else None
|
|
164
|
+
retry_after = None
|
|
165
|
+
if isinstance(data, dict) and data.get("retry_after") is not None:
|
|
166
|
+
retry_after = float(data["retry_after"])
|
|
167
|
+
elif resp.headers.get("Retry-After"):
|
|
168
|
+
try:
|
|
169
|
+
retry_after = float(resp.headers["Retry-After"])
|
|
170
|
+
except ValueError:
|
|
171
|
+
pass
|
|
172
|
+
if (code == 45009 or resp.status_code >= 500) and attempt < self.max_retries:
|
|
173
|
+
time.sleep(retry_after if retry_after is not None else 2 ** attempt)
|
|
174
|
+
attempt += 1
|
|
175
|
+
continue
|
|
176
|
+
raise WeChatAPIError(
|
|
177
|
+
(body or {}).get("message") or f"HTTP {resp.status_code}", code=code,
|
|
178
|
+
request_id=(body or {}).get("request_id"), status=resp.status_code,
|
|
179
|
+
retry_after=retry_after, data=data)
|
wechatapilabs/webhook.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
from typing import Optional, Union
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def verify_webhook(raw_body: Union[bytes, str], signature: Optional[str], secret: str) -> bool:
|
|
7
|
+
"""校验回调请求头 X-Signature:用回调密钥对原始请求体做 HMAC-SHA256 的十六进制结果。"""
|
|
8
|
+
if not signature or not secret:
|
|
9
|
+
return False
|
|
10
|
+
if isinstance(raw_body, str):
|
|
11
|
+
raw_body = raw_body.encode("utf-8")
|
|
12
|
+
expected = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
|
|
13
|
+
return hmac.compare_digest(expected, signature.strip().lower())
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: wechatapilabs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: WeChatAPI Labs 接口的 Python SDK:微信和企业微信收发消息、好友、群管理和回调校验。
|
|
5
|
+
Project-URL: Homepage, https://wechatapilabs.com/zh/docs/
|
|
6
|
+
Project-URL: Source, https://github.com/wechatapilabs/wechatapi-python
|
|
7
|
+
Project-URL: Issues, https://github.com/wechatapilabs/wechatapi-python/issues
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: chatbot,webhook,wechat,wechat-api,wechat-bot,wecom
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Communications :: Chat
|
|
14
|
+
Requires-Python: >=3.8
|
|
15
|
+
Requires-Dist: requests>=2.25
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
18
|
+
# wechatapi-python
|
|
19
|
+
|
|
20
|
+
[WeChatAPI Labs](https://wechatapilabs.com/zh/) 接口的 Python SDK。用代码收发微信和企业微信消息、管理好友和群、校验回调签名。
|
|
21
|
+
|
|
22
|
+
[接口文档](https://wechatapilabs.com/zh/docs/) · [English docs](https://wechatapilabs.com/docs/)
|
|
23
|
+
|
|
24
|
+
## 安装
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install wechatapilabs
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
需要 Python 3.8 或更高版本,唯一依赖是 `requests`。
|
|
31
|
+
|
|
32
|
+
## 快速开始
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
import os
|
|
36
|
+
from wechatapilabs import WeChatAPI
|
|
37
|
+
|
|
38
|
+
client = WeChatAPI(os.environ["WECHATAPI_KEY"])
|
|
39
|
+
|
|
40
|
+
client.message.send_text(
|
|
41
|
+
account_id="acc_123",
|
|
42
|
+
to="123456@chatroom", # 好友 ID 或群 ID
|
|
43
|
+
content="今日报表已生成",
|
|
44
|
+
at=["wxid_alice"], # 可选,群里 @ 成员
|
|
45
|
+
)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
API Key 和测试账号请在[联系我们](https://wechatapilabs.com/zh/contact/)申请。每个方法都和[接口文档](https://wechatapilabs.com/zh/docs/)里的接口一一对应。
|
|
49
|
+
|
|
50
|
+
## 方法列表(公开接口)
|
|
51
|
+
|
|
52
|
+
| 方法 | 接口 |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `account.login_qrcode(type)` / `account.status(account_id)` | `/v1/account/*` |
|
|
55
|
+
| `message.send_text / send_image / send_file / send_link / revoke` | `/v1/message/*` |
|
|
56
|
+
| `contact.friends / iter_friends / accept / remark` | `/v1/contact/*` |
|
|
57
|
+
| `group.create / invite / remove / notice / members` | `/v1/group/*` |
|
|
58
|
+
| `moment.post(...)` | `/v1/moment/post` |
|
|
59
|
+
| `wecom.group_send / customers` | `/v1/wecom/*` |
|
|
60
|
+
| `request(method, path, params)` | 直接调用任意接口 |
|
|
61
|
+
|
|
62
|
+
> **说明:** 上表是已公开的 18 个常用接口,SDK 已全部封装。完整版 API 还包括更多接口,以及详细的参数、返回字段和回调说明。如需获取,请到官网[联系我们](https://wechatapilabs.com/zh/contact/)。
|
|
63
|
+
|
|
64
|
+
### 完整版 API 还覆盖这些能力
|
|
65
|
+
|
|
66
|
+
| 能力 | 内容 |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| 更多消息类型 | 除文本、图片、文件、链接卡片外,还支持语音、视频、小程序卡片的发送和接收 |
|
|
69
|
+
| 好友管理 | 搜索并添加好友、自动通过好友申请、获取好友资料 |
|
|
70
|
+
| 群管理 | 修改群名,以及入群、退群事件回调 |
|
|
71
|
+
| 朋友圈 | 获取好友朋友圈、点赞与评论 |
|
|
72
|
+
| 企业微信客户管理 | 添加客户、打标签、修改备注,与 CRM / SCRM 系统打通 |
|
|
73
|
+
| 企业微信外部群管理 | 创建外部群、邀请客户进群、修改群公告、移出成员 |
|
|
74
|
+
| 客户朋友圈 | 发布企业微信客户朋友圈 |
|
|
75
|
+
| 多成员托管 | 一个控制台管理多个账号,按成员分配回调地址和权限 |
|
|
76
|
+
| 其他 | 绝大部分功能都是存在的 |
|
|
77
|
+
|
|
78
|
+
已有的接口都可以通过 `request(method, path, params)` 直接调用,不需要等 SDK 更新。有列表里没有的需求,大部分都是存在的,欢迎[联系我们](https://wechatapilabs.com/zh/contact/)。
|
|
79
|
+
|
|
80
|
+
方法返回响应里的 `data` 字段。`code` 非 0 时抛出 `WeChatAPIError`,带 `.code`、`.request_id` 和 `.retry_after`。遇到限流(`45009`)和 5xx 会自动重试,默认最多 2 次(`max_retries`)。
|
|
81
|
+
|
|
82
|
+
## 回调
|
|
83
|
+
|
|
84
|
+
事件以 JSON POST 到你的回调地址,请求头 `X-Signature` 是用回调密钥对原始请求体做 HMAC-SHA256 的十六进制结果。请对原始字节校验,5 秒内返回 200,再处理业务。
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from wechatapilabs import verify_webhook
|
|
88
|
+
|
|
89
|
+
if not verify_webhook(request.get_data(), request.headers.get("X-Signature"), SECRET):
|
|
90
|
+
abort(401)
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
完整的 Flask 示例见 [examples/flask_webhook.py](examples/flask_webhook.py)。要接入大模型,请看 [wechat-ai-bot-template](https://github.com/wechatapilabs/wechat-ai-bot-template)。
|
|
94
|
+
|
|
95
|
+
## 错误处理
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
from wechatapilabs import WeChatAPIError
|
|
99
|
+
|
|
100
|
+
try:
|
|
101
|
+
client.message.send_text("acc_123", "wxid_bob", "你好")
|
|
102
|
+
except WeChatAPIError as e:
|
|
103
|
+
if e.code == 42001: # 账号离线
|
|
104
|
+
...
|
|
105
|
+
elif e.code == 46001: # 触发风控:暂停主动操作 24 小时
|
|
106
|
+
...
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
完整错误码见[接口文档](https://wechatapilabs.com/zh/docs/#errors)。
|
|
110
|
+
|
|
111
|
+
## 测试
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
python -m unittest discover -s tests -t .
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## 合规使用
|
|
118
|
+
|
|
119
|
+
请只发送对方预期会收到的消息,比如客服回复、通知和用户主动加入的群。批量发送骚扰消息违反微信的使用规范,会导致账号被限制。详见[安全与合规](https://wechatapilabs.com/zh/security/)。
|
|
120
|
+
|
|
121
|
+
## 许可证
|
|
122
|
+
|
|
123
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
wechatapilabs/__init__.py,sha256=miMbJzV05kpetFVufW_PTayVmoZeo9yd94nJ_sOcUFk,291
|
|
2
|
+
wechatapilabs/client.py,sha256=__3QHs6WZa33jgKOY_byZuItwXRTBV2x4qGt-0csk6Y,8386
|
|
3
|
+
wechatapilabs/webhook.py,sha256=fECTsK-njrm2YHmd-NgTJL2qI839MjgSErsVZOxkbGs,569
|
|
4
|
+
wechatapilabs-0.1.0.dist-info/METADATA,sha256=EoEd5XU20Qewn9SeYa1isyJ-7tOzMWzJE_9LyQ80bp0,5042
|
|
5
|
+
wechatapilabs-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
wechatapilabs-0.1.0.dist-info/licenses/LICENSE,sha256=_gTD8gO7osRleCBBeE-vzyeqNXxZsL6jLPm1U1YduQE,1071
|
|
7
|
+
wechatapilabs-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WeChatAPI Labs
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|