weping 0.4.1__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.
wechat_cli.py ADDED
@@ -0,0 +1,238 @@
1
+ import argparse
2
+ import os
3
+ import tempfile
4
+ import base64
5
+ import hashlib
6
+ import io
7
+ import json
8
+ import secrets
9
+ import sys
10
+ import time
11
+ import uuid
12
+ from pathlib import Path
13
+ from urllib.parse import urlencode, urlparse
14
+
15
+ import requests
16
+ from filelock import FileLock, Timeout as LockTimeout
17
+
18
+ __version__ = "0.4.1"
19
+
20
+ ROOT = (Path(os.environ["LOCALAPPDATA"]) / "WeixinTaskNotify" if os.name == "nt"
21
+ else Path.home() / ".local" / "share" / "weixin-notify")
22
+ BASE = "https://ilinkai.weixin.qq.com"
23
+ STATE = ROOT / "account.json"
24
+
25
+ def call(base, endpoint, data=None, token=None, params=None):
26
+ url = urlparse(base)
27
+ if url.scheme != "https" or not (url.hostname or "").endswith(".weixin.qq.com"):
28
+ raise ValueError("Unexpected iLink host")
29
+ headers = {"iLink-App-Id": "bot", "iLink-App-ClientVersion": str(0x02040a)}
30
+ if data is not None:
31
+ headers.update(AuthorizationType="ilink_bot_token")
32
+ headers["X-WECHAT-UIN"] = base64.b64encode(str(secrets.randbits(32)).encode()).decode()
33
+ if token:
34
+ headers["Authorization"] = "Bearer " + token
35
+ r = requests.request("GET" if data is None else "POST", base.rstrip("/") + "/ilink/bot/" + endpoint,
36
+ json=data, headers=headers, params=params, timeout=42, allow_redirects=False)
37
+ if r.status_code != 200:
38
+ raise RuntimeError(f"{endpoint}: HTTP {r.status_code}")
39
+ reply = r.json()
40
+ if reply.get("ret", 0) or reply.get("errcode", 0):
41
+ raise RuntimeError(f"{endpoint}: ret={reply.get('ret')} errcode={reply.get('errcode')}")
42
+ return reply
43
+
44
+ def save(state):
45
+ with tempfile.NamedTemporaryFile(mode="w", dir=ROOT, delete=False, encoding="utf8") as f:
46
+ json.dump(state, f)
47
+ Path(f.name).replace(STATE)
48
+
49
+ def login():
50
+
51
+ import qrcode
52
+ qr = call(BASE, "get_bot_qrcode", {"local_token_list": []}, params={"bot_type": "3"})
53
+ qrcode.make(qr["qrcode_img_content"]).save(ROOT / "login.png")
54
+ print("Scan with WeChat:", ROOT / "login.png", flush=True)
55
+ terminal_qr = qrcode.QRCode(border=2)
56
+ terminal_qr.add_data(qr["qrcode_img_content"])
57
+ terminal_qr.print_ascii(tty=False, invert=True)
58
+ base = BASE
59
+ params = {"qrcode": qr["qrcode"]}
60
+ while True:
61
+ try:
62
+ reply = call(base, "get_qrcode_status", params=params)
63
+ except requests.Timeout:
64
+ continue
65
+ status = reply["status"]
66
+ if status == "confirmed":
67
+ state = {"token": reply["bot_token"], "base": reply.get("baseurl") or BASE,
68
+ "owner": reply["ilink_user_id"]}
69
+ if not state["owner"]:
70
+ raise RuntimeError("Missing scanner ID")
71
+ return state
72
+ if status == "scaned_but_redirect":
73
+ base = "https://" + reply["redirect_host"]
74
+ elif status == "need_verifycode":
75
+ print("Enter the pairing code shown by WeChat", flush=True)
76
+ params["verify_code"] = input("Code: ").strip()
77
+ elif status not in {"wait", "scaned"}:
78
+ raise RuntimeError("Login status: " + status)
79
+ time.sleep(1)
80
+
81
+ def api(state, name, **payload):
82
+ payload["base_info"] = {"channel_version": "2.4.10"}
83
+ return call(state["base"], name, payload, state["token"])
84
+
85
+ def send(state, text):
86
+ send_item(state, {"type": 1, "text_item": {"text": text}})
87
+
88
+
89
+ def send_item(state, item):
90
+ api(state, "sendmessage", msg={"from_user_id": "", "to_user_id": state["owner"],
91
+ "client_id": uuid.uuid4().hex, "message_type": 2, "message_state": 2,
92
+ "context_token": state["context"], "item_list": [item]})
93
+
94
+
95
+ def send_image(state, path):
96
+ from PIL import Image
97
+ from cryptography.hazmat.primitives import padding
98
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
99
+
100
+ raw = path.read_bytes()
101
+ with Image.open(io.BytesIO(raw)) as image:
102
+ if image.format not in {"PNG", "JPEG"}:
103
+ raise ValueError("Choose a PNG or JPEG image")
104
+ image.verify()
105
+
106
+ key = secrets.token_bytes(16)
107
+ padder = padding.PKCS7(128).padder()
108
+ padded = padder.update(raw) + padder.finalize()
109
+ encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor()
110
+ encrypted = encryptor.update(padded) + encryptor.finalize()
111
+ filekey = secrets.token_hex(16)
112
+ upload = api(state, "getuploadurl", filekey=filekey, media_type=1,
113
+ to_user_id=state["owner"], rawsize=len(raw), rawfilemd5=hashlib.md5(raw).hexdigest(),
114
+ filesize=len(encrypted), no_need_thumb=True, aeskey=key.hex())
115
+ url = (upload.get("upload_full_url") or "").strip()
116
+ if not url:
117
+ if not upload.get("upload_param"):
118
+ raise RuntimeError("getuploadurl returned no upload URL")
119
+ url = "https://novac2c.cdn.weixin.qq.com/c2c/upload?" + urlencode({
120
+ "encrypted_query_param": upload["upload_param"], "filekey": filekey})
121
+ if urlparse(url).scheme != "https":
122
+ raise ValueError("Expected HTTPS CDN upload URL")
123
+ response = requests.post(url, data=encrypted, headers={"Content-Type": "application/octet-stream"},
124
+ timeout=42, allow_redirects=False)
125
+ if response.status_code != 200:
126
+ raise RuntimeError(f"Image upload: HTTP {response.status_code}")
127
+ download = response.headers.get("x-encrypted-param")
128
+ if not download:
129
+ raise RuntimeError("Image upload returned no download parameter")
130
+ media = {"encrypt_query_param": download, "encrypt_type": 1,
131
+ "aes_key": base64.b64encode(key.hex().encode("ascii")).decode("ascii")}
132
+ send_item(state, {"type": 2, "image_item": {"media": media, "mid_size": len(encrypted)}})
133
+
134
+
135
+ def pairing_state():
136
+ try:
137
+ state = json.loads(STATE.read_text(encoding="utf8"))
138
+ except FileNotFoundError:
139
+ return {}, "logged_out"
140
+ except ValueError:
141
+ return {}, "invalid"
142
+ if not isinstance(state, dict) or not all(isinstance(state.get(k), str) and state[k]
143
+ for k in ("owner", "base", "token")):
144
+ return {}, "invalid"
145
+ return state, "ready" if isinstance(state.get("context"), str) and state["context"] else "pending"
146
+
147
+
148
+ def status_message(status):
149
+ return {"ready": "Configured locally", "logged_out": "Logged out. Run: wechat login",
150
+ "pending": "Pairing incomplete. Resume with: wechat login",
151
+ "invalid": "Invalid local pairing. Run: wechat logout, then wechat login"}[status]
152
+
153
+
154
+ def pair_host():
155
+ state, status = pairing_state()
156
+ if status == "ready":
157
+ print("Already configured")
158
+ return 0
159
+ if status == "invalid":
160
+ raise ValueError(status_message(status))
161
+ if status == "logged_out":
162
+ try:
163
+ state = login()
164
+ save(state)
165
+ finally:
166
+ (ROOT / "login.png").unlink(missing_ok=True)
167
+ print("Send a private message to the bot from the WeChat account that scanned the code.", flush=True)
168
+ cursor = ""
169
+ while True:
170
+ try:
171
+ reply = api(state, "getupdates", get_updates_buf=cursor)
172
+ except requests.Timeout:
173
+ continue
174
+ cursor = reply.get("get_updates_buf", cursor)
175
+ for msg in reply.get("msgs", []):
176
+ if msg.get("from_user_id") == state["owner"] and msg.get("context_token"):
177
+ state["context"] = msg["context_token"]
178
+ save(state)
179
+ print("Configured")
180
+ return 0
181
+
182
+
183
+ def main():
184
+ parser = argparse.ArgumentParser(description="Send a task notification to your paired WeChat.")
185
+ parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
186
+ commands = parser.add_subparsers(dest="command", required=True)
187
+ commands.add_parser("login", aliases=["setup"], help="Pair this host or resume pairing")
188
+ commands.add_parser("logout", help="Remove the pairing from this host")
189
+ status = commands.add_parser("status", help="Check local pairing state")
190
+ status.add_argument("--json", action="store_true", help="Print machine-readable status")
191
+ commands.add_parser("test", help="Send one test message to the paired WeChat account")
192
+ send_parser = commands.add_parser("send", help="Send text or a local image")
193
+ content = send_parser.add_mutually_exclusive_group(required=True)
194
+ content.add_argument("message", nargs="?")
195
+ content.add_argument("--image", type=Path, metavar="PATH", help="Send a PNG or JPEG image")
196
+ args = parser.parse_args()
197
+ try:
198
+ os.umask(0o077)
199
+ if args.command in {"login", "setup", "logout"}:
200
+ if args.command == "logout" and not ROOT.exists():
201
+ print("Logged out locally")
202
+ return 0
203
+ ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
204
+ with FileLock(str(ROOT / ".pairing.lock"), timeout=0):
205
+ if args.command == "logout":
206
+ STATE.unlink(missing_ok=True)
207
+ (ROOT / "login.png").unlink(missing_ok=True)
208
+ print("Logged out locally")
209
+ return 0
210
+ return pair_host()
211
+ state, status = pairing_state()
212
+ ready = status == "ready"
213
+ if args.command == "status":
214
+ if args.json:
215
+ print(json.dumps({"status": status, "ready": ready}))
216
+ else:
217
+ print(status_message(status))
218
+ return 0 if ready else 1
219
+ if not ready:
220
+ parser.exit(1, status_message(status) + "\n")
221
+ if args.command == "test":
222
+ send(state, "微信任务通知测试消息")
223
+ elif args.image is not None:
224
+ send_image(state, args.image)
225
+ else:
226
+ if not args.message.strip():
227
+ parser.error("Message is empty")
228
+ send(state, args.message)
229
+ print("Accepted by WeChat")
230
+ return 0
231
+ except LockTimeout:
232
+ parser.exit(1, "Another login or logout is already running on this host.\n")
233
+ except (KeyboardInterrupt, EOFError):
234
+ parser.exit(130, "Pairing or command interrupted.\n")
235
+ except requests.RequestException as exc:
236
+ parser.exit(1, f"WeChat network error: {type(exc).__name__}\n")
237
+ except (RuntimeError, ValueError, KeyError, OSError) as exc:
238
+ parser.exit(1, f"WeChat error: {exc}\n")
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: weping
3
+ Version: 0.4.1
4
+ Summary: Send text and image task notifications to your paired WeChat account
5
+ Project-URL: Repository, https://github.com/YRYangang/weping
6
+ Requires-Python: >=3.8
7
+ Description-Content-Type: text/markdown
8
+ Requires-Dist: requests<3,>=2.25
9
+ Requires-Dist: qrcode[pil]<9,>=7
10
+ Requires-Dist: cryptography>=41
11
+ Requires-Dist: filelock>=3.12
12
+
13
+ # WePing
14
+
15
+ ![WePing 使用示意图:从终端发送 loss.png,在微信里查看训练曲线。](https://raw.githubusercontent.com/YRYangang/weping/main/docs/weping.png)
16
+
17
+ 在训练脚本或批处理任务结束时,运行一条命令,把文字结果或 PNG、JPEG 图片发到自己的微信。首次扫码绑定后,每次发送都可以独立运行。
18
+
19
+ **Python 3.8+** · **Windows / macOS / Linux** · [下载发行包](https://github.com/YRYangang/weping/releases/latest) · [部署到远端机器](https://github.com/YRYangang/weping/blob/main/WECHAT.md)
20
+
21
+ ## 安装
22
+
23
+ ```sh
24
+ python -m pip install https://github.com/YRYangang/weping/releases/download/v0.4.1/weping-0.4.1-py3-none-any.whl
25
+ ```
26
+
27
+ 从旧包迁移时,先在原 Python 环境运行 `python -m pip uninstall wechat-task-notify`,再安装 WePing。通过 pipx 安装的用户先运行 `pipx uninstall wechat-task-notify`,再用 `pipx install` 安装上方链接。绑定保存在用户目录,迁移后可直接运行 `wechat status` 检查。
28
+
29
+ ## 第一次发送
30
+
31
+ 在运行任务的机器上执行 `wechat login`,用手机微信扫码,再给机器人发一条私聊。终端显示 `Configured` 后,可以运行:
32
+
33
+ ```sh
34
+ wechat test
35
+ wechat send "exp42 训练完成,验证集准确率 87.3%"
36
+ wechat send --image "runs/exp42/loss.png"
37
+ ```
38
+
39
+ `wechat test` 会发送一条测试消息。终端显示 `Accepted by WeChat` 表示微信接口已接受请求。打开手机上的会话即可确认送达。
40
+
41
+ ## 接入脚本
42
+
43
+ ```python
44
+ import subprocess
45
+
46
+ subprocess.run(["wechat", "send", "--image", "runs/exp42/loss.png"], check=True)
47
+ ```
48
+
49
+ 脚本可以用 `wechat status --json` 读取本地绑定状态。换账号时运行 `wechat logout`,再重新登录。所有命令和参数可用 `wechat --help` 查看。
@@ -0,0 +1,6 @@
1
+ wechat_cli.py,sha256=QTfhsXldUKDaygjZ0BzJ7SAyo9e7MGwq5i-y4L8vcsU,10498
2
+ weping-0.4.1.dist-info/METADATA,sha256=Zm2o29wD96tUi4yKY0ZSXCWKRQ5ZMzCRY3Lv7nPYkX0,2219
3
+ weping-0.4.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ weping-0.4.1.dist-info/entry_points.txt,sha256=E_dCrwZ8rJh_K31g7xTPTqoB46tOedCFM8tSi-IZReU,43
5
+ weping-0.4.1.dist-info/top_level.txt,sha256=gHAxnsPZpVBjn2eM5jbzmUFRKUTi4RrTf3gz-E3KnRk,11
6
+ weping-0.4.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ wechat = wechat_cli:main
@@ -0,0 +1 @@
1
+ wechat_cli