dsh-plugin-chuhai 0.3.4 → 0.3.6
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.
- package/CHANGELOG.md +11 -0
- package/README.md +1 -1
- package/books/ai-global-media/BOOK.md +6 -5
- package/books/ai-global-media/expert/SOURCE.json +43 -41
- package/books/ai-global-media/expert/agents/ilang-wechat-awesome.md +267 -267
- package/books/ai-global-media/expert/skills/remote-dispatch/SKILL.md +101 -101
- package/books/ai-global-media/expert/skills/remote-dispatch/references/gateway-api.md +58 -58
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/dispatch.py +299 -299
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.ps1 +74 -74
- package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.sh +94 -94
- package/books/ai-global-media/expert/skills/wechat-article/SKILL.md +80 -80
- package/books/ai-global-media/expert/skills/wechat-article/references/algorithm-and-rhythm.md +54 -54
- package/books/ai-global-media/expert/skills/wechat-article/references/compliance.md +68 -68
- package/books/ai-global-media/expert/skills/wechat-article/references/cover-prompt.md +19 -19
- package/books/ai-global-media/expert/skills/wechat-article/references/deai.md +64 -64
- package/books/ai-global-media/expert/skills/wechat-article/references/genes.md +168 -168
- package/books/ai-global-media/expert/skills/wechat-article/references/other-platforms.md +47 -47
- package/books/ai-global-media/expert/skills/wechat-article/references/self-check.md +32 -32
- package/books/ai-global-media/expert/skills/wechat-article/references/structures-and-titles.md +77 -77
- package/books/ai-global-media/expert/skills/wechat-article/references/wechat-format-and-api.md +61 -61
- package/books/ai-global-media/expert/skills/wechat-draft-push/SKILL.md +129 -129
- package/books/ai-global-media/expert/skills/wechat-draft-push/references/api-notes.md +168 -168
- package/books/ai-global-media/expert/skills/wechat-draft-push/references/html-rules.md +62 -62
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/cards.html +75 -75
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/newspic_cards.py +345 -345
- package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/wechat_draft.py +1023 -1023
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/SKILL.md +125 -92
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/apify-wechat.md +90 -0
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/method.md +49 -49
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/wxrank-api.md +51 -51
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/apify_wechat.py +577 -0
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/hot_sources.py +553 -553
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/sources.json +716 -714
- package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/wxrank_topics.py +466 -466
- package/books/baowen/BOOK.md +83 -0
- package/lib/index.js +7 -1
- package/package.json +1 -1
- package/skills/zimeiti-chuhai.md +1 -1
|
@@ -1,1023 +1,1023 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""公众号推草稿箱,外加一个只在人说「发」之后才跑的发布命令(没有删草稿命令)。
|
|
4
|
-
|
|
5
|
-
用法:
|
|
6
|
-
python wechat_draft.py check 读配置、拿 access_token、打印 ok,不推任何东西
|
|
7
|
-
python wechat_draft.py render --md 文章.md [--out 文章.html] 只把 Markdown 转成微信 HTML 并校验,不联网;顺带写一个 390 宽的预览页 *.preview.html
|
|
8
|
-
python wechat_draft.py push --md 文章.md --title "标题" --cover 封面.jpg [--digest "摘要"] [--author "作者"] [--dry-run]
|
|
9
|
-
传图、传封面、推草稿箱、回读核对、落盘结果
|
|
10
|
-
python wechat_draft.py push-newspic --title "标题" --text 配文.txt --images 1.png,2.png [--images-dir cards] [--comment open|fans|off] [--dry-run]
|
|
11
|
-
图片消息(公众号里的「贴图」):一组图加一段纯文本配文,第一张是封面;
|
|
12
|
-
图先传成永久素材再 draft/add,回读标题,落盘结果。卡片图用 newspic_cards.py 出
|
|
13
|
-
python wechat_draft.py verify --media-id XXXX 回读一篇草稿,核对中文、图片数、字数
|
|
14
|
-
python wechat_draft.py publish --media-id XXXX --reviewed 人在后台看过草稿、说了「发」之后才跑:
|
|
15
|
-
回读确认草稿存在并打印标题,提交发布,轮询状态,落盘结果
|
|
16
|
-
没有 --reviewed 直接拒绝。只有微信认证企业号能用发布接口。
|
|
17
|
-
|
|
18
|
-
凭据(二选一,永远不要贴进对话):
|
|
19
|
-
环境变量 WECHAT_MP_APPID / WECHAT_MP_SECRET
|
|
20
|
-
或配置文件 ~/.wechat-mp.env(可用 WECHAT_MP_ENV 指定路径),内容两行:
|
|
21
|
-
APPID=wx...
|
|
22
|
-
SECRET=...
|
|
23
|
-
|
|
24
|
-
只依赖 Python 3.8+ 标准库。装了 Pillow 时正文图超过 1MB 会自动压到 1MB 以内,没装就报错让你自己压。
|
|
25
|
-
"""
|
|
26
|
-
import argparse
|
|
27
|
-
import datetime as _dt
|
|
28
|
-
import io
|
|
29
|
-
import json
|
|
30
|
-
import mimetypes
|
|
31
|
-
import os
|
|
32
|
-
import re
|
|
33
|
-
import sys
|
|
34
|
-
import time
|
|
35
|
-
import urllib.parse
|
|
36
|
-
import urllib.request
|
|
37
|
-
import uuid
|
|
38
|
-
import http.client
|
|
39
|
-
import socket
|
|
40
|
-
import ssl
|
|
41
|
-
from html import escape
|
|
42
|
-
|
|
43
|
-
# 强制 IPv4(老板 2026-10-12 定):公众号 IP 白名单按 IPv4 核,机器走 IPv6 出去会报 40164 而且 errmsg 里是个 v6 地址,填不进去。
|
|
44
|
-
_getaddrinfo_orig = socket.getaddrinfo
|
|
45
|
-
def _getaddrinfo_v4_first(*args, **kwargs):
|
|
46
|
-
res = _getaddrinfo_orig(*args, **kwargs)
|
|
47
|
-
v4 = [r for r in res if r[0] == socket.AF_INET]
|
|
48
|
-
return v4 or res
|
|
49
|
-
socket.getaddrinfo = _getaddrinfo_v4_first
|
|
50
|
-
|
|
51
|
-
try:
|
|
52
|
-
sys.stdout.reconfigure(encoding="utf-8")
|
|
53
|
-
sys.stderr.reconfigure(encoding="utf-8")
|
|
54
|
-
except Exception:
|
|
55
|
-
pass
|
|
56
|
-
|
|
57
|
-
BASE = "https://api.weixin.qq.com"
|
|
58
|
-
UA = "wechat-draft-push/2.3"
|
|
59
|
-
CITATIONS = [] # 正文里的外链 → 文末「参考链接」[n]
|
|
60
|
-
NO_CITE = False # --no-cite:外链只留文字不留引用
|
|
61
|
-
TUNNEL = None # (host, port),本机→远程机的 ssh -L 隧道口,走它去 api.weixin.qq.com
|
|
62
|
-
BODY_IMG_LIMIT = 1024 * 1024 # uploadimg:jpg/png,1MB 以内
|
|
63
|
-
COVER_LIMIT = 10 * 1024 * 1024 # add_material type=image:10MB 以内
|
|
64
|
-
TITLE_MAX, AUTHOR_MAX, DIGEST_MAX = 32, 16, 120
|
|
65
|
-
CONTENT_MAX_CHARS, CONTENT_MAX_BYTES = 20000, 1024 * 1024
|
|
66
|
-
NEWSPIC_MAX_IMAGES = 20 # 图片消息:官方写的上限 20 张,第一张是封面
|
|
67
|
-
NEWSPIC_TEXT_MAX_BYTES = None # 官方文档没写配文长度,不硬编码;真撞到限制再把实测值填这里
|
|
68
|
-
NO_REPLY_PREFIXES = ("网络请求失败", "隧道请求失败", "返回的不是 JSON") # http_json(fatal=False) 自己造的三种「没收到回复」
|
|
69
|
-
|
|
70
|
-
# 发布状态(freepublish/get 的 publish_status)
|
|
71
|
-
PUBLISH_POLL_TIMES = 6 # 最多查 6 次
|
|
72
|
-
PUBLISH_POLL_INTERVAL = 5 # 每次隔 5 秒
|
|
73
|
-
PUBLISH_STATUS = {
|
|
74
|
-
0: "发布成功",
|
|
75
|
-
1: "发布中",
|
|
76
|
-
2: "原创失败",
|
|
77
|
-
3: "常规失败",
|
|
78
|
-
4: "平台审核不通过",
|
|
79
|
-
5: "成功后用户删除",
|
|
80
|
-
6: "成功后系统封禁",
|
|
81
|
-
}
|
|
82
|
-
PUBLISH_PERMISSION_NOTE = ("只有微信认证企业号能用发布接口,个人主体账号 2025 年 7 月起被回收。"
|
|
83
|
-
"草稿还在草稿箱里没动,去公众号后台点发布。")
|
|
84
|
-
NO_PERMISSION_CODES = {48001}
|
|
85
|
-
NO_PERMISSION_RE = re.compile(r"unauthorized|not authorized|no permission", re.I)
|
|
86
|
-
|
|
87
|
-
# 排版常量(内联样式,微信只认这个)
|
|
88
|
-
FONT = "font-size:15px;color:#333;line-height:1.8;letter-spacing:0.5px;"
|
|
89
|
-
P = '<p style="%smargin:0;">' % FONT
|
|
90
|
-
H = '<p style="font-size:17px;font-weight:bold;color:#111;line-height:1.8;letter-spacing:0.5px;margin:0;">'
|
|
91
|
-
BR = "<p><br/></p>"
|
|
92
|
-
CAPTION = '<p style="font-size:12px;color:#999;text-align:center;letter-spacing:0.5px;margin:0;">'
|
|
93
|
-
HR = '<p style="text-align:center;color:#ccc;margin:0;">────────</p>'
|
|
94
|
-
CODE_LINE = '<p style="font-family:Menlo,Consolas,monospace;font-size:13px;color:#e5e7eb;line-height:1.6;margin:0;word-break:break-all;">'
|
|
95
|
-
INLINE_CODE = '<span style="font-family:Menlo,Consolas,monospace;background-color:#f3f4f6;padding:1px 4px;border-radius:3px;font-size:14px;">'
|
|
96
|
-
CARD_HEAD = '<p style="font-size:15px;font-weight:bold;color:#111;line-height:1.8;letter-spacing:0.5px;margin:0;">'
|
|
97
|
-
CARD = '<section style="padding:12px 15px;background-color:%s;border-left:4px solid %s;margin:0;">%s</section>'
|
|
98
|
-
# GFM 提示块 > [!NOTE] 之类 → 四色信息卡,颜色沿用 html-rules.md 的调色板:蓝 正常信息、绿 推荐、橙 提醒、红 避坑
|
|
99
|
-
CALLOUTS = {
|
|
100
|
-
"NOTE": ("说明", "#1a73e8", "#f0f7ff"),
|
|
101
|
-
"IMPORTANT": ("重点", "#1a73e8", "#f0f7ff"),
|
|
102
|
-
"TIP": ("推荐", "#2e7d32", "#f1f8f2"),
|
|
103
|
-
"WARNING": ("注意", "#ff8f00", "#fff8e1"),
|
|
104
|
-
"CAUTION": ("避坑", "#c62828", "#fef2f2"),
|
|
105
|
-
}
|
|
106
|
-
CALLOUT_RE = re.compile(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$", re.I)
|
|
107
|
-
|
|
108
|
-
MARKER_RE = re.compile(r"\[(📝|💬|🖼|📊)[^\]]*\]")
|
|
109
|
-
DASH_RE = re.compile("[—–]")
|
|
110
|
-
IMG_LINE_RE = re.compile(r"^!\[([^\]]*)\]\(([^)]+)\)\s*$")
|
|
111
|
-
INLINE_IMG_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
|
112
|
-
LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
|
|
113
|
-
TABLE_SEP_RE = re.compile(r"^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$")
|
|
114
|
-
FORBIDDEN_HTML = [
|
|
115
|
-
(re.compile(r"<table[\s>]", re.I), "table 标签微信不渲染"),
|
|
116
|
-
(re.compile(r"</?div[\s>]", re.I), "div 会被改写,用 section"),
|
|
117
|
-
(re.compile(r"<style[\s>]", re.I), "style 标签会被过滤"),
|
|
118
|
-
(re.compile(r"<script[\s>]", re.I), "script 会被过滤"),
|
|
119
|
-
(re.compile(r"\sclass\s*=", re.I), "class 属性会被剥离"),
|
|
120
|
-
(re.compile(r"\sid\s*=", re.I), "id 属性会被剥离"),
|
|
121
|
-
(re.compile(r"position\s*:\s*(fixed|absolute|sticky)", re.I), "position fixed/absolute 不支持"),
|
|
122
|
-
]
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
def die(msg, code=1):
|
|
126
|
-
print("错误:" + msg)
|
|
127
|
-
sys.exit(code)
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
def cjk_count(text):
|
|
131
|
-
return sum(1 for c in text if "一" <= c <= "鿿")
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
# ---------- 凭据 ----------
|
|
135
|
-
def load_tunnel():
|
|
136
|
-
"""TUNNEL=127.0.0.1:8443 写在环境变量 WECHAT_MP_TUNNEL 或 ~/.wechat-mp.env 里。有就把对 api.weixin.qq.com 的请求全走它。"""
|
|
137
|
-
global TUNNEL
|
|
138
|
-
v = os.environ.get("WECHAT_MP_TUNNEL", "").strip()
|
|
139
|
-
path = os.environ.get("WECHAT_MP_ENV") or os.path.join(os.path.expanduser("~"), ".wechat-mp.env")
|
|
140
|
-
if not v and os.path.exists(path):
|
|
141
|
-
for line in io.open(path, encoding="utf-8"):
|
|
142
|
-
line = line.strip()
|
|
143
|
-
if "=" in line and not line.startswith("#"):
|
|
144
|
-
k, val = line.split("=", 1)
|
|
145
|
-
if k.strip().upper() in ("TUNNEL", "WECHAT_MP_TUNNEL"):
|
|
146
|
-
v = val.strip().strip('"').strip("'")
|
|
147
|
-
if v:
|
|
148
|
-
host, _, port = v.rpartition(":")
|
|
149
|
-
if host and port.isdigit():
|
|
150
|
-
TUNNEL = (host, int(port))
|
|
151
|
-
return TUNNEL
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
def tunnel_request(method, url, data=None, headers=None, timeout=60):
|
|
155
|
-
"""连隧道口(本机 ssh -L 开的端口),TLS 的 SNI 和证书校验仍按 api.weixin.qq.com,证书对得上。"""
|
|
156
|
-
u = urllib.parse.urlsplit(url)
|
|
157
|
-
path = u.path + ("?" + u.query if u.query else "")
|
|
158
|
-
ctx = ssl.create_default_context()
|
|
159
|
-
raw_sock = socket.create_connection(TUNNEL, timeout=timeout)
|
|
160
|
-
sock = ctx.wrap_socket(raw_sock, server_hostname=u.hostname)
|
|
161
|
-
conn = http.client.HTTPConnection(u.hostname, 443, timeout=timeout)
|
|
162
|
-
conn.sock = sock
|
|
163
|
-
hdrs = {"User-Agent": UA, "Host": u.hostname}
|
|
164
|
-
hdrs.update(headers or {})
|
|
165
|
-
conn.request(method, path, body=data, headers=hdrs)
|
|
166
|
-
resp = conn.getresponse()
|
|
167
|
-
body = resp.read()
|
|
168
|
-
conn.close()
|
|
169
|
-
return body
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
def load_credentials():
|
|
173
|
-
appid = os.environ.get("WECHAT_MP_APPID", "").strip()
|
|
174
|
-
secret = os.environ.get("WECHAT_MP_SECRET", "").strip()
|
|
175
|
-
path = os.environ.get("WECHAT_MP_ENV") or os.path.join(os.path.expanduser("~"), ".wechat-mp.env")
|
|
176
|
-
if (not appid or not secret) and os.path.exists(path):
|
|
177
|
-
for line in io.open(path, encoding="utf-8"):
|
|
178
|
-
line = line.strip()
|
|
179
|
-
if not line or line.startswith("#") or "=" not in line:
|
|
180
|
-
continue
|
|
181
|
-
k, v = line.split("=", 1)
|
|
182
|
-
k, v = k.strip().upper(), v.strip().strip('"').strip("'")
|
|
183
|
-
if k in ("APPID", "WECHAT_MP_APPID") and not appid:
|
|
184
|
-
appid = v
|
|
185
|
-
if k in ("SECRET", "APPSECRET", "WECHAT_MP_SECRET") and not secret:
|
|
186
|
-
secret = v
|
|
187
|
-
if not appid or not secret:
|
|
188
|
-
die("没找到凭据。设环境变量 WECHAT_MP_APPID / WECHAT_MP_SECRET,或写配置文件 %s(两行:APPID=... 与 SECRET=...)" % path)
|
|
189
|
-
return appid, secret
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
# ---------- HTTP(标准库) ----------
|
|
193
|
-
def http_json(method, url, data=None, headers=None, timeout=60, fatal=True):
|
|
194
|
-
"""fatal=True 时网络错误或非 JSON 直接退出;fatal=False 时返回 {"errcode": -1, "errmsg": ...} 交给调用方处理。"""
|
|
195
|
-
if TUNNEL and urllib.parse.urlsplit(url).hostname == "api.weixin.qq.com":
|
|
196
|
-
try:
|
|
197
|
-
raw = tunnel_request(method, url, data, headers, timeout)
|
|
198
|
-
except Exception as e:
|
|
199
|
-
if not fatal:
|
|
200
|
-
return {"errcode": -1, "errmsg": "隧道请求失败:%s" % e}
|
|
201
|
-
die("隧道请求失败:%s。隧道口 %s:%d 开着吗(本机先跑 ssh -N -L,见 tunnel 子命令)" % (e, TUNNEL[0], TUNNEL[1]))
|
|
202
|
-
else:
|
|
203
|
-
req = urllib.request.Request(url, data=data, method=method)
|
|
204
|
-
req.add_header("User-Agent", UA)
|
|
205
|
-
for k, v in (headers or {}).items():
|
|
206
|
-
req.add_header(k, v)
|
|
207
|
-
try:
|
|
208
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
209
|
-
raw = resp.read()
|
|
210
|
-
except urllib.error.HTTPError as e:
|
|
211
|
-
raw = e.read()
|
|
212
|
-
except Exception as e:
|
|
213
|
-
if not fatal:
|
|
214
|
-
return {"errcode": -1, "errmsg": "网络请求失败:%s" % e}
|
|
215
|
-
die("网络请求失败:%s(%s)" % (e, url.split("?")[0]))
|
|
216
|
-
try:
|
|
217
|
-
return json.loads(raw.decode("utf-8")) # 微信返回 text/plain 不带 charset,必须自己按 UTF-8 解
|
|
218
|
-
except Exception:
|
|
219
|
-
if not fatal:
|
|
220
|
-
return {"errcode": -1, "errmsg": "返回的不是 JSON:%r" % raw[:200]}
|
|
221
|
-
die("微信返回的不是 JSON:%r" % raw[:200])
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
def post_json(token, path, payload, timeout=60, fatal=True):
|
|
225
|
-
"""带 access_token 的 JSON POST,请求体按 UTF-8 直传不转义中文。"""
|
|
226
|
-
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
227
|
-
return http_json("POST", BASE + path + "?access_token=" + token, body,
|
|
228
|
-
{"Content-Type": "application/json; charset=utf-8"}, timeout=timeout, fatal=fatal)
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
def multipart(fields, file_field, filename, file_bytes, content_type):
|
|
232
|
-
boundary = "----wechatdraft" + uuid.uuid4().hex
|
|
233
|
-
body = bytearray()
|
|
234
|
-
for k, v in fields.items():
|
|
235
|
-
body.extend(("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" % (boundary, k, v)).encode("utf-8"))
|
|
236
|
-
body.extend(("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n"
|
|
237
|
-
% (boundary, file_field, filename, content_type)).encode("utf-8"))
|
|
238
|
-
body.extend(file_bytes)
|
|
239
|
-
body.extend(("\r\n--%s--\r\n" % boundary).encode("utf-8"))
|
|
240
|
-
return bytes(body), "multipart/form-data; boundary=" + boundary
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
def explain(j):
|
|
244
|
-
code = j.get("errcode")
|
|
245
|
-
tips = {
|
|
246
|
-
-1: "微信系统繁忙,这次没进去,稍等一会再推一次。",
|
|
247
|
-
40164: "调接口的这台机器的公网 IP 不在白名单里。去公众号后台「设置与开发 → 基本配置 → IP 白名单」加上 errmsg 里那个 IP,加完再跑一次。本机跑的,家里 IP 变了会再报一次,再加一次就行,白名单能存多个,旧的不用删。",
|
|
248
|
-
40013: "AppID 不对。",
|
|
249
|
-
40125: "AppSecret 不对,或者被重置过。",
|
|
250
|
-
40001: "access_token 失效,重跑一次。",
|
|
251
|
-
40002: "参数不合法,多半是 media_id 或 publish_id 写错了。",
|
|
252
|
-
40007: "media_id 不合法。推草稿时:先看封面是不是传成了永久素材(结果文件里有 thumb_media_id),不是就重传封面再推,是的话就是 media_id 抄错了;发布时:草稿 media_id 抄错了,从最近一份 draft-result 文件重新复制。",
|
|
253
|
-
45110: "author 太长,16 字以内。",
|
|
254
|
-
45003: "标题太长,32 字以内。",
|
|
255
|
-
45004: "digest 太长,120 字以内。",
|
|
256
|
-
45166: "content 不合法:正文里有微信不认的标签或属性(script/iframe/外站图片地址/未转义的尖括号之类),或小绿书 newspic 的正文传了 HTML。先跑 render 看 HTML,去掉可疑标签再推。",
|
|
257
|
-
53404: "文章内容涉嫌违规,到公众号后台看具体提示,改正文后再推。",
|
|
258
|
-
53405: "文章含敏感内容,到公众号后台看具体提示,改正文后再推。",
|
|
259
|
-
45009: "接口调用次数到上限,明天再推。",
|
|
260
|
-
48001: "这个账号没有这个接口的权限。",
|
|
261
|
-
53503: "这篇草稿没过发布检查,去后台看草稿内容。",
|
|
262
|
-
53504: "这篇草稿要去公众平台官网里用,接口发不了。",
|
|
263
|
-
53505: "要先在公众平台官网手动保存成功,再发布。",
|
|
264
|
-
}
|
|
265
|
-
return "errcode=%s errmsg=%s%s" % (code, j.get("errmsg"), ("。" + tips[code]) if code in tips else "")
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
def is_no_permission(j):
|
|
269
|
-
code = j.get("errcode")
|
|
270
|
-
msg = str(j.get("errmsg") or "")
|
|
271
|
-
return code in NO_PERMISSION_CODES or bool(NO_PERMISSION_RE.search(msg))
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
def get_token(appid, secret):
|
|
275
|
-
q = urllib.parse.urlencode({"grant_type": "client_credential", "appid": appid, "secret": secret})
|
|
276
|
-
j = http_json("GET", BASE + "/cgi-bin/token?" + q, timeout=20)
|
|
277
|
-
if "access_token" not in j:
|
|
278
|
-
die("拿 access_token 失败:" + explain(j))
|
|
279
|
-
return j["access_token"]
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
def read_image(path, limit, shrink):
|
|
283
|
-
if not os.path.exists(path):
|
|
284
|
-
die("图片不存在:" + path)
|
|
285
|
-
ext = os.path.splitext(path)[1].lower()
|
|
286
|
-
if ext not in (".jpg", ".jpeg", ".png"):
|
|
287
|
-
die("只收 jpg/png:" + path)
|
|
288
|
-
data = io.open(path, "rb").read()
|
|
289
|
-
ctype = "image/png" if ext == ".png" else "image/jpeg"
|
|
290
|
-
if len(data) > limit:
|
|
291
|
-
if not shrink:
|
|
292
|
-
die("图片超过 %dKB:%s" % (limit // 1024, path))
|
|
293
|
-
try:
|
|
294
|
-
from PIL import Image
|
|
295
|
-
except Exception:
|
|
296
|
-
die("图片超过 %dKB 且没装 Pillow 压不了:%s(自己压一下,或 pip install pillow)" % (limit // 1024, path))
|
|
297
|
-
im = Image.open(io.BytesIO(data)).convert("RGB")
|
|
298
|
-
quality, scale = 88, 1.0
|
|
299
|
-
while True:
|
|
300
|
-
w, h = im.size
|
|
301
|
-
out = io.BytesIO()
|
|
302
|
-
im.resize((max(1, int(w * scale)), max(1, int(h * scale)))).save(out, "JPEG", quality=quality, optimize=True)
|
|
303
|
-
if out.tell() <= limit or (quality <= 50 and scale <= 0.4):
|
|
304
|
-
break
|
|
305
|
-
if quality > 50:
|
|
306
|
-
quality -= 8
|
|
307
|
-
else:
|
|
308
|
-
scale *= 0.85
|
|
309
|
-
data, ctype = out.getvalue(), "image/jpeg"
|
|
310
|
-
path = os.path.splitext(path)[0] + ".jpg"
|
|
311
|
-
print(" 图片已压到 %dKB:%s" % (len(data) // 1024, os.path.basename(path)))
|
|
312
|
-
return os.path.basename(path), data, ctype
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
def upload_body_image(token, path):
|
|
316
|
-
name, data, ctype = read_image(path, BODY_IMG_LIMIT, shrink=True)
|
|
317
|
-
body, ct = multipart({}, "media", name, data, ctype)
|
|
318
|
-
j = http_json("POST", BASE + "/cgi-bin/media/uploadimg?access_token=" + token, body, {"Content-Type": ct}, timeout=120)
|
|
319
|
-
if "url" not in j:
|
|
320
|
-
die("uploadimg 失败(%s):%s" % (path, explain(j)))
|
|
321
|
-
return j["url"].replace("http://", "https://")
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
def upload_material(token, path, label="封面"):
|
|
325
|
-
"""传成永久图片素材,返回 media_id。图文的封面(thumb_media_id)和图片消息的每一张图都走这里。"""
|
|
326
|
-
name, data, ctype = read_image(path, COVER_LIMIT, shrink=False)
|
|
327
|
-
body, ct = multipart({}, "media", name, data, ctype)
|
|
328
|
-
j = http_json("POST", BASE + "/cgi-bin/material/add_material?access_token=%s&type=image" % token, body, {"Content-Type": ct}, timeout=180)
|
|
329
|
-
if "media_id" not in j:
|
|
330
|
-
die("%s add_material 失败(%s):%s" % (label, os.path.basename(path), explain(j)))
|
|
331
|
-
return j["media_id"]
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
def upload_cover(token, path):
|
|
335
|
-
return upload_material(token, path, "封面")
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
def no_reply(j):
|
|
339
|
-
"""draft/add 发出去了但没收到微信的回复(断网、超时、回的不是 JSON)。微信自己的 errcode -1 是「系统繁忙」,那是收到了回复,不算。"""
|
|
340
|
-
return j.get("errcode") == -1 and str(j.get("errmsg") or "").startswith(NO_REPLY_PREFIXES)
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
def draft_add_unknown(stem, kind, info):
|
|
344
|
-
"""没收到回复时草稿可能已经进了草稿箱:落一份 *-UNKNOWN-<时间>.json,退出码 3,让人先去草稿箱看,别重推。"""
|
|
345
|
-
now = _dt.datetime.now()
|
|
346
|
-
out = stem + ".%s-UNKNOWN-%s.json" % (kind, now.strftime("%Y%m%d-%H%M%S"))
|
|
347
|
-
info = dict(info, status="UNKNOWN", at=now.isoformat(timespec="seconds"))
|
|
348
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(info, ensure_ascii=False, indent=1))
|
|
349
|
-
print("draft/add 发出去了但没收到微信的回复:%s" % info.get("error"))
|
|
350
|
-
print("先去公众号后台草稿箱看有没有《%s》,有就别重推(重推会多一篇重复草稿);确定没有再推一次。这次的图片 media_id 已记在:%s" % (info.get("title"), out))
|
|
351
|
-
sys.exit(3)
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
# ---------- Markdown → 微信 HTML ----------
|
|
355
|
-
def inline(text, warnings):
|
|
356
|
-
"""行内:行内图片只留说明文字(并提醒单独成行)、行内代码先护住(里面的 * ** [] 都不排版)、转义、链接去 URL、粗体、斜体。
|
|
357
|
-
标题、列表、引用、表格、段落都走这一个函数。"""
|
|
358
|
-
for mm in INLINE_IMG_RE.finditer(text):
|
|
359
|
-
warnings.append("行内图片请单独成行:" + mm.group(2)[:60])
|
|
360
|
-
text = INLINE_IMG_RE.sub(lambda mm: mm.group(1), text)
|
|
361
|
-
codes = []
|
|
362
|
-
def keep(m):
|
|
363
|
-
codes.append(INLINE_CODE + escape(m.group(1)) + "</span>")
|
|
364
|
-
return "\x00%d\x00" % (len(codes) - 1)
|
|
365
|
-
text = re.sub(r"`([^`]+)`", keep, text)
|
|
366
|
-
parts = []
|
|
367
|
-
pos = 0
|
|
368
|
-
for m in LINK_RE.finditer(text):
|
|
369
|
-
parts.append(escape(text[pos:m.start()]))
|
|
370
|
-
label, url = m.group(1), m.group(2).strip()
|
|
371
|
-
if url.startswith("https://mp.weixin.qq.com/"):
|
|
372
|
-
parts.append('<a href="%s">%s</a>' % (escape(url, quote=True), escape(label)))
|
|
373
|
-
elif NO_CITE:
|
|
374
|
-
warnings.append("正文链接已去掉网址只留文字:%s" % url[:60])
|
|
375
|
-
parts.append(escape(label))
|
|
376
|
-
else:
|
|
377
|
-
CITATIONS.append((label, url))
|
|
378
|
-
parts.append(escape(label) + '<sup>[%d]</sup>' % len(CITATIONS))
|
|
379
|
-
pos = m.end()
|
|
380
|
-
parts.append(escape(text[pos:]))
|
|
381
|
-
s = "".join(parts)
|
|
382
|
-
s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
|
|
383
|
-
s = re.sub(r"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])", r"<em>\1</em>", s)
|
|
384
|
-
s = re.sub("\x00(\\d+)\x00", lambda m: codes[int(m.group(1))], s)
|
|
385
|
-
return s
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
def join_lines(parts):
|
|
389
|
-
"""软换行拼回一段:两边都是英文、数字的补一个空格,中文直接接上。"""
|
|
390
|
-
out = parts[0] if parts else ""
|
|
391
|
-
for p in parts[1:]:
|
|
392
|
-
if out and p and re.search(r"[A-Za-z0-9,.;:!?)\"']$", out) and re.match(r"[A-Za-z0-9(\"']", p):
|
|
393
|
-
out += " " + p
|
|
394
|
-
else:
|
|
395
|
-
out += p
|
|
396
|
-
return out
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
def quote_block(quote, warnings):
|
|
400
|
-
"""引用块。第一行是 [!NOTE] [!TIP] [!IMPORTANT] [!WARNING] [!CAUTION](GFM 提示块,后面可跟自定义标题)就按类型配色出带标题的信息卡;
|
|
401
|
-
不是就还是原来的橙色引用卡。"""
|
|
402
|
-
cm = CALLOUT_RE.match(quote[0]) if quote else None
|
|
403
|
-
if cm:
|
|
404
|
-
label, border, bg = CALLOUTS[cm.group(1).upper()]
|
|
405
|
-
head, body = (cm.group(2).strip() or label), quote[1:]
|
|
406
|
-
else:
|
|
407
|
-
head, body, border, bg = None, quote, "#ff8f00", "#fff8e1"
|
|
408
|
-
inner = (CARD_HEAD + inline(head, warnings) + "</p>") if head else ""
|
|
409
|
-
inner += "".join(P + inline(q, warnings) + "</p>" for q in body if q)
|
|
410
|
-
return CARD % (bg, border, inner)
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
def md_to_html(md_text, drop_first_h1=True):
|
|
414
|
-
"""返回 (blocks, images, title_from_h1, warnings)。images = [(占位符, 路径, 说明)]。"""
|
|
415
|
-
del CITATIONS[:]
|
|
416
|
-
text = md_text.replace("\r\n", "\n").replace("\r", "\n")
|
|
417
|
-
if text.startswith("---\n"):
|
|
418
|
-
end = text.find("\n---\n", 4)
|
|
419
|
-
if end != -1:
|
|
420
|
-
text = text[end + 5:]
|
|
421
|
-
warnings = []
|
|
422
|
-
n = len(DASH_RE.findall(text))
|
|
423
|
-
if n:
|
|
424
|
-
warnings.append("长破折号 %d 处已换成逗号" % n)
|
|
425
|
-
text = DASH_RE.sub(",", text)
|
|
426
|
-
lines = text.split("\n")
|
|
427
|
-
blocks, images, title = [], [], None
|
|
428
|
-
i = 0
|
|
429
|
-
while i < len(lines):
|
|
430
|
-
line = lines[i]
|
|
431
|
-
s = line.strip()
|
|
432
|
-
if not s:
|
|
433
|
-
i += 1
|
|
434
|
-
continue
|
|
435
|
-
if s.startswith("```"):
|
|
436
|
-
code = []
|
|
437
|
-
i += 1
|
|
438
|
-
while i < len(lines) and not lines[i].strip().startswith("```"):
|
|
439
|
-
code.append(lines[i])
|
|
440
|
-
i += 1
|
|
441
|
-
i += 1
|
|
442
|
-
inner = "".join(CODE_LINE + (escape(c) or " ") + "</p>" for c in code)
|
|
443
|
-
blocks.append('<section style="padding:12px 14px;background-color:#1f2937;border-radius:6px;">' + inner + "</section>")
|
|
444
|
-
continue
|
|
445
|
-
m = IMG_LINE_RE.match(s)
|
|
446
|
-
if m:
|
|
447
|
-
alt, src = m.group(1).strip(), m.group(2).strip()
|
|
448
|
-
ph = "{{IMG:%d}}" % len(images)
|
|
449
|
-
images.append((ph, src, alt))
|
|
450
|
-
b = '<p style="margin:0;"><img src="%s" style="width:100%%;"/></p>' % ph
|
|
451
|
-
if alt:
|
|
452
|
-
b += CAPTION + escape(alt) + "</p>"
|
|
453
|
-
blocks.append(b)
|
|
454
|
-
i += 1
|
|
455
|
-
continue
|
|
456
|
-
if re.match(r"^(-{3,}|\*{3,}|_{3,})$", s):
|
|
457
|
-
blocks.append(HR)
|
|
458
|
-
i += 1
|
|
459
|
-
continue
|
|
460
|
-
hm = re.match(r"^(#{1,6})\s+(.*)$", s)
|
|
461
|
-
if hm:
|
|
462
|
-
if hm.group(1) == "#" and title is None and drop_first_h1:
|
|
463
|
-
title = hm.group(2).strip()
|
|
464
|
-
i += 1
|
|
465
|
-
continue
|
|
466
|
-
blocks.append(H + inline(hm.group(2).strip(), warnings) + "</p>")
|
|
467
|
-
i += 1
|
|
468
|
-
continue
|
|
469
|
-
if s.startswith("|") and i + 1 < len(lines) and TABLE_SEP_RE.match(lines[i + 1].strip()):
|
|
470
|
-
header = [c.strip() for c in s.strip("|").split("|")]
|
|
471
|
-
i += 2
|
|
472
|
-
rows = []
|
|
473
|
-
while i < len(lines) and lines[i].strip().startswith("|"):
|
|
474
|
-
rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")])
|
|
475
|
-
i += 1
|
|
476
|
-
labels = [inline(h, warnings) if h else "" for h in header] # 表头只排一次,里面的链接只引一次
|
|
477
|
-
for row in rows:
|
|
478
|
-
cells = [inline(c, warnings) for c in row]
|
|
479
|
-
inner = CARD_HEAD + "%s</p>" % (cells[0] if cells else "")
|
|
480
|
-
for k, c in enumerate(cells[1:], 1):
|
|
481
|
-
label = labels[k] if k < len(labels) else ""
|
|
482
|
-
inner += P + (label + ":" if label else "") + c + "</p>"
|
|
483
|
-
blocks.append(CARD % ("#f0f7ff", "#1a73e8", inner))
|
|
484
|
-
continue
|
|
485
|
-
if s.startswith(">"):
|
|
486
|
-
quote = []
|
|
487
|
-
while i < len(lines) and lines[i].strip().startswith(">"):
|
|
488
|
-
quote.append(lines[i].strip()[1:].strip())
|
|
489
|
-
i += 1
|
|
490
|
-
blocks.append(quote_block(quote, warnings))
|
|
491
|
-
continue
|
|
492
|
-
if re.match(r"^([-*•]|\d+[.、])\s+", s):
|
|
493
|
-
items = []
|
|
494
|
-
while i < len(lines) and re.match(r"^([-*•]|\d+[.、])\s+", lines[i].strip()):
|
|
495
|
-
t = lines[i].strip()
|
|
496
|
-
mm = re.match(r"^(\d+[.、])\s+(.*)$", t)
|
|
497
|
-
items.append((mm.group(1) + " " + mm.group(2)) if mm else "• " + re.sub(r"^[-*•]\s+", "", t))
|
|
498
|
-
i += 1
|
|
499
|
-
blocks.append("".join(P + inline(it, warnings) + "</p>" for it in items))
|
|
500
|
-
continue
|
|
501
|
-
para = [s]
|
|
502
|
-
i += 1
|
|
503
|
-
while i < len(lines) and lines[i].strip() and not re.match(r"^(#{1,6}\s|```|>|\||!\[|[-*•]\s|\d+[.、]\s|-{3,}$)", lines[i].strip()):
|
|
504
|
-
para.append(lines[i].strip())
|
|
505
|
-
i += 1
|
|
506
|
-
blocks.append(P + inline(join_lines(para), warnings) + "</p>")
|
|
507
|
-
return blocks, images, title, warnings
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
def assemble(blocks):
|
|
511
|
-
body = ("\n" + BR + "\n").join(blocks)
|
|
512
|
-
if CITATIONS:
|
|
513
|
-
rows = "".join('<p style="font-size:13px;color:#888;line-height:1.7;margin:0 0 4px;word-break:break-all;">[%d] %s:%s</p>'
|
|
514
|
-
% (i + 1, escape(label), escape(url)) for i, (label, url) in enumerate(CITATIONS))
|
|
515
|
-
body += "\n" + BR + '\n<section style="margin-top:24px;padding-top:12px;border-top:1px solid #eee;"><p style="font-size:13px;color:#888;margin:0 0 6px;">参考链接</p>%s</section>' % rows
|
|
516
|
-
return body
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
def check_html(html, mode, images):
|
|
520
|
-
errors, warnings = [], []
|
|
521
|
-
for rx, msg in FORBIDDEN_HTML:
|
|
522
|
-
if rx.search(html):
|
|
523
|
-
errors.append(msg)
|
|
524
|
-
if DASH_RE.search(html):
|
|
525
|
-
errors.append("仍有长破折号")
|
|
526
|
-
markers = MARKER_RE.findall(html)
|
|
527
|
-
if markers:
|
|
528
|
-
(warnings if mode == "render" else errors).append("还有 %d 处待作者处理的标记 [📝/💬/🖼/📊],推之前要清掉" % len(markers))
|
|
529
|
-
if mode == "final":
|
|
530
|
-
for src in re.findall(r'<img src="([^"]+)"', html):
|
|
531
|
-
if not src.startswith("https://mmbiz.qpic.cn/") and not src.startswith("https://mmbiz.qlogo.cn/"):
|
|
532
|
-
errors.append("正文图不是微信图床地址:" + src[:60])
|
|
533
|
-
elif mode == "render" and images:
|
|
534
|
-
warnings.append("%d 张图在 render 模式下未上传,push 时会自动传" % len(images))
|
|
535
|
-
chars = len(html)
|
|
536
|
-
nbytes = len(html.encode("utf-8"))
|
|
537
|
-
if chars > CONTENT_MAX_CHARS:
|
|
538
|
-
errors.append("正文 HTML %d 字符,超过 %d" % (chars, CONTENT_MAX_CHARS))
|
|
539
|
-
if nbytes > CONTENT_MAX_BYTES:
|
|
540
|
-
errors.append("正文 HTML %d 字节,超过 1MB" % nbytes)
|
|
541
|
-
return errors, warnings
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
def build(md_path, title, mode):
|
|
545
|
-
md_text = io.open(md_path, encoding="utf-8").read()
|
|
546
|
-
blocks, images, h1, warnings = md_to_html(md_text)
|
|
547
|
-
title = (title or h1 or "").strip()
|
|
548
|
-
html = assemble(blocks)
|
|
549
|
-
errors, w2 = check_html(html, mode, images)
|
|
550
|
-
warnings += w2
|
|
551
|
-
if not title:
|
|
552
|
-
errors.append("没有标题:用 --title 给,或者 Markdown 第一行写 # 标题")
|
|
553
|
-
if len(title) > TITLE_MAX:
|
|
554
|
-
errors.append("标题 %d 字,超过 %d" % (len(title), TITLE_MAX))
|
|
555
|
-
return html, images, title, errors, warnings, cjk_count(md_text)
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
def report_build(title, html, images, errors, warnings, chars):
|
|
559
|
-
print("标题:%s(%d 字)" % (title, len(title)))
|
|
560
|
-
print("正文:约 %d 个汉字,%d 个区块,%d 张图" % (chars, html.count(BR) + 1, len(images)))
|
|
561
|
-
for w in warnings:
|
|
562
|
-
print(" 提醒:" + w)
|
|
563
|
-
for e in errors:
|
|
564
|
-
print(" 不过:" + e)
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
# ---------- 子命令 ----------
|
|
568
|
-
def cmd_check(args):
|
|
569
|
-
appid, secret = load_credentials()
|
|
570
|
-
token = get_token(appid, secret)
|
|
571
|
-
print("ok:AppID %s… 拿到 access_token(长度 %d),白名单通。什么都没推。" % (appid[:6], len(token)))
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
def preview_shell(title, fragment, note="本机预览,390 宽;不是微信的真实渲染,图片是本地路径"):
|
|
575
|
-
"""把微信 HTML 片段套进一个 390 宽的手机壳,浏览器打开就能看排版。只是看,不是微信渲染。"""
|
|
576
|
-
return ('<!doctype html>\n<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
577
|
-
'<title>预览:%s</title><style>body{margin:0;background:#e5e5e5;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif}'
|
|
578
|
-
'.phone{width:390px;max-width:100%%;margin:24px auto;background:#fff;padding:20px 16px 48px;box-sizing:border-box;min-height:844px}'
|
|
579
|
-
'.phone h1{font-size:22px;line-height:1.4;margin:0 0 6px;color:#111}.note{font-size:12px;color:#999;margin:0 0 20px}img{max-width:100%%}'
|
|
580
|
-
'</style></head><body><div class="phone"><h1>%s</h1><p class="note">%s</p>\n%s\n</div></body></html>\n'
|
|
581
|
-
% (escape(title), escape(title), escape(note), fragment))
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
def cmd_render(args):
|
|
585
|
-
html, images, title, errors, warnings, chars = build(args.md, args.title, "render")
|
|
586
|
-
report_build(title, html, images, errors, warnings, chars)
|
|
587
|
-
out = args.out or os.path.splitext(args.md)[0] + ".wechat.html"
|
|
588
|
-
for ph, src, _ in images:
|
|
589
|
-
html = html.replace(ph, escape(src, quote=True))
|
|
590
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(html)
|
|
591
|
-
print("HTML 已写到:" + out + ("(有不过项,推之前先改)" if errors else ""))
|
|
592
|
-
prev = os.path.splitext(args.md)[0] + ".preview.html"
|
|
593
|
-
io.open(prev, "w", encoding="utf-8", newline="\n").write(preview_shell(title or "(没有标题)", html))
|
|
594
|
-
print("预览页已写到:" + prev + "(浏览器打开看 390 宽的排版;不是微信的真实渲染,最终以草稿箱为准)")
|
|
595
|
-
sys.exit(1 if errors else 0)
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
def article_opts(args):
|
|
599
|
-
"""draft/add 的三个可选项:留言开关、仅粉丝留言、「阅读原文」地址。"""
|
|
600
|
-
comment = getattr(args, "comment", "open") or "open"
|
|
601
|
-
d = {"need_open_comment": 0 if comment == "off" else 1,
|
|
602
|
-
"only_fans_can_comment": 1 if comment == "fans" else 0}
|
|
603
|
-
src = (getattr(args, "source_url", None) or "").strip()
|
|
604
|
-
if src:
|
|
605
|
-
if not src.startswith(("http://", "https://")):
|
|
606
|
-
die("--source-url 要以 http:// 或 https:// 开头")
|
|
607
|
-
d["content_source_url"] = src
|
|
608
|
-
return d
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
def cmd_tunnel(args):
|
|
612
|
-
vps = args.vps or "root@远程机IP"
|
|
613
|
-
print("备选,不想每次 IP 变了都去加白名单时用:白名单只填远程机的 IP,本机开一条隧道,微信接口的流量从远程机出去,AppSecret 不离开本机。")
|
|
614
|
-
print("一 本机开着一条隧道(开着别关):")
|
|
615
|
-
print(" ssh -N -L 127.0.0.1:8443:api.weixin.qq.com:443 %s" % vps)
|
|
616
|
-
print("二 ~/.wechat-mp.env 加一行:TUNNEL=127.0.0.1:8443")
|
|
617
|
-
print("三 之后 check / push / publish 照常跑,流量自动走隧道。")
|
|
618
|
-
if not TUNNEL:
|
|
619
|
-
print("现在没配 TUNNEL,先做第二步再回来测。")
|
|
620
|
-
return
|
|
621
|
-
q = urllib.parse.urlencode({"grant_type": "client_credential", "appid": "tunnel-test", "secret": "tunnel-test"})
|
|
622
|
-
j = http_json("GET", BASE + "/cgi-bin/token?" + q, timeout=20, fatal=False)
|
|
623
|
-
if j.get("errcode") in (40013, 40125, 41002, 40001):
|
|
624
|
-
print("ok:隧道通,微信那头收到了请求(回 errcode=%s 是因为用的测试 appid,正常)。" % j.get("errcode"))
|
|
625
|
-
else:
|
|
626
|
-
print("隧道不通或微信没回:%s" % explain(j))
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
def cmd_push(args):
|
|
630
|
-
html, images, title, errors, warnings, chars = build(args.md, args.title, "prepush")
|
|
631
|
-
report_build(title, html, images, errors, warnings, chars)
|
|
632
|
-
if errors:
|
|
633
|
-
die("先把上面的不过项改掉再推")
|
|
634
|
-
author = (args.author or "").strip()
|
|
635
|
-
if len(author) > AUTHOR_MAX:
|
|
636
|
-
die("作者 %d 字,超过 %d" % (len(author), AUTHOR_MAX))
|
|
637
|
-
digest = (args.digest or "").strip()
|
|
638
|
-
if len(digest) > DIGEST_MAX:
|
|
639
|
-
die("摘要 %d 字,超过 %d" % (len(digest), DIGEST_MAX))
|
|
640
|
-
if not args.cover or not os.path.exists(args.cover):
|
|
641
|
-
die("封面必填(--cover 封面.jpg),图文草稿没有封面推不进去")
|
|
642
|
-
base_dir = os.path.dirname(os.path.abspath(args.md))
|
|
643
|
-
paths = []
|
|
644
|
-
for ph, src, _ in images:
|
|
645
|
-
p = src if os.path.isabs(src) else os.path.join(base_dir, src)
|
|
646
|
-
if src.startswith("https://mmbiz.qpic.cn/"):
|
|
647
|
-
paths.append((ph, None, src))
|
|
648
|
-
elif src.startswith("http://") or src.startswith("https://"):
|
|
649
|
-
die("正文图是外链,先下载到本地再引用:" + src[:80])
|
|
650
|
-
elif not os.path.exists(p):
|
|
651
|
-
die("正文图不存在:" + p)
|
|
652
|
-
else:
|
|
653
|
-
paths.append((ph, p, None))
|
|
654
|
-
if args.dry_run:
|
|
655
|
-
for ph, p, url in paths:
|
|
656
|
-
html = html.replace(ph, url or escape(p, quote=True))
|
|
657
|
-
payload = {"articles": [dict({"title": title, "author": author, "digest": digest, "content": html,
|
|
658
|
-
"thumb_media_id": "<dry-run>"}, **article_opts(args))]}
|
|
659
|
-
out = os.path.splitext(args.md)[0] + ".draft-dryrun.json"
|
|
660
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(payload, ensure_ascii=False, indent=1))
|
|
661
|
-
print("dry-run:没联网。请求体已写到 " + out)
|
|
662
|
-
return
|
|
663
|
-
appid, secret = load_credentials()
|
|
664
|
-
token = get_token(appid, secret)
|
|
665
|
-
print("ok:access_token 拿到")
|
|
666
|
-
img_urls = {}
|
|
667
|
-
for ph, p, url in paths:
|
|
668
|
-
if url is None:
|
|
669
|
-
url = upload_body_image(token, p)
|
|
670
|
-
print(" 正文图已传:%s -> %s…" % (os.path.basename(p), url[:48]))
|
|
671
|
-
img_urls[ph] = url
|
|
672
|
-
html = html.replace(ph, url)
|
|
673
|
-
thumb = upload_cover(token, args.cover)
|
|
674
|
-
print(" 封面已传为永久素材:thumb_media_id=" + thumb)
|
|
675
|
-
errors, _ = check_html(html, "final", images)
|
|
676
|
-
if errors:
|
|
677
|
-
die("推送前校验不过:" + ";".join(errors))
|
|
678
|
-
article = dict({"title": title, "author": author, "digest": digest, "content": html,
|
|
679
|
-
"thumb_media_id": thumb}, **article_opts(args))
|
|
680
|
-
body = json.dumps({"articles": [article]}, ensure_ascii=False).encode("utf-8")
|
|
681
|
-
j = http_json("POST", BASE + "/cgi-bin/draft/add?access_token=" + token, body,
|
|
682
|
-
{"Content-Type": "application/json; charset=utf-8"}, timeout=120, fatal=False)
|
|
683
|
-
if no_reply(j):
|
|
684
|
-
draft_add_unknown(os.path.splitext(args.md)[0], "draft-result",
|
|
685
|
-
{"title": title, "thumb_media_id": thumb, "images": img_urls, "error": j.get("errmsg")})
|
|
686
|
-
if "media_id" not in j:
|
|
687
|
-
die("draft/add 失败:" + explain(j))
|
|
688
|
-
media_id = j["media_id"]
|
|
689
|
-
print("ok:草稿已进草稿箱,media_id=" + media_id)
|
|
690
|
-
ok, msg = readback(token, media_id, title, len(img_urls))
|
|
691
|
-
print(("ok:" if ok else "注意:") + msg)
|
|
692
|
-
result = {"title": title, "media_id": media_id, "thumb_media_id": thumb, "images": img_urls,
|
|
693
|
-
"chinese_chars": chars, "pushed_at": _dt.datetime.now().isoformat(timespec="seconds"), "readback": msg}
|
|
694
|
-
out = os.path.splitext(args.md)[0] + ".draft-result-%s.json" % _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
695
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
696
|
-
print("结果已落盘:" + out + "(报 media_id 从这里复制,别手抄)")
|
|
697
|
-
print("接下来是人的活:去公众号后台草稿箱点进这篇,看图和排版,勾「声明原创」,开「赞赏」,没问题再点发布。")
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
# ---------- 图片消息(公众号里的「贴图」,接口叫 newspic) ----------
|
|
701
|
-
def newspic_text(raw):
|
|
702
|
-
"""配文归一:换行统一、每行去尾空格、三个以上空行压成两个、长破折号换逗号(记一条提醒)。不动别的。"""
|
|
703
|
-
warnings = []
|
|
704
|
-
text = raw.replace("\r\n", "\n").replace("\r", "\n")
|
|
705
|
-
n = len(re.findall("[—–]+", text))
|
|
706
|
-
if n:
|
|
707
|
-
warnings.append("长破折号 %d 处已换成逗号" % n)
|
|
708
|
-
text = re.sub("[—–]+", ",", text)
|
|
709
|
-
text = "\n".join(l.rstrip() for l in text.split("\n"))
|
|
710
|
-
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
|
711
|
-
return text, warnings
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
def newspic_gate(title, text, image_paths):
|
|
715
|
-
"""推之前的门:标题 32 字内、配文非空且是纯文本(不带尖括号、不带待填标记、不带长破折号)、1 到 20 张本地 jpg/png、单张 10MB 内。返回错误列表,空=过。"""
|
|
716
|
-
errors = []
|
|
717
|
-
title = (title or "").strip()
|
|
718
|
-
if not title:
|
|
719
|
-
errors.append("没有标题:--title")
|
|
720
|
-
elif len(title) > TITLE_MAX:
|
|
721
|
-
errors.append("标题 %d 字,超过 %d" % (len(title), TITLE_MAX))
|
|
722
|
-
if not text.strip():
|
|
723
|
-
errors.append("配文是空的")
|
|
724
|
-
if "<" in text or ">" in text:
|
|
725
|
-
errors.append("配文里有尖括号:图片消息的 content 是纯文本,不能带 HTML(否则 45166)")
|
|
726
|
-
markers = MARKER_RE.findall(text)
|
|
727
|
-
if markers:
|
|
728
|
-
errors.append("配文还有 %d 处待作者处理的标记 [📝/💬/🖼/📊]" % len(markers))
|
|
729
|
-
if DASH_RE.search(text):
|
|
730
|
-
errors.append("配文仍有长破折号")
|
|
731
|
-
if NEWSPIC_TEXT_MAX_BYTES and len(text.encode("utf-8")) > NEWSPIC_TEXT_MAX_BYTES:
|
|
732
|
-
errors.append("配文 %d 字节,超过 %d" % (len(text.encode("utf-8")), NEWSPIC_TEXT_MAX_BYTES))
|
|
733
|
-
n = len(image_paths)
|
|
734
|
-
if n < 1:
|
|
735
|
-
errors.append("至少要 1 张图:--images 或 --images-dir")
|
|
736
|
-
elif n > NEWSPIC_MAX_IMAGES:
|
|
737
|
-
errors.append("%d 张图,超过 %d 张" % (n, NEWSPIC_MAX_IMAGES))
|
|
738
|
-
for p in image_paths:
|
|
739
|
-
if not os.path.exists(p):
|
|
740
|
-
errors.append("图片不存在:" + p)
|
|
741
|
-
elif os.path.splitext(p)[1].lower() not in (".jpg", ".jpeg", ".png"):
|
|
742
|
-
errors.append("只收 jpg/png:" + p)
|
|
743
|
-
elif os.path.getsize(p) > COVER_LIMIT:
|
|
744
|
-
errors.append("图片超过 %dMB:%s" % (COVER_LIMIT // 1024 // 1024, p))
|
|
745
|
-
return errors
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
def collect_images(images, images_dir):
|
|
749
|
-
"""--images a.png,b.png 按给的顺序;--images-dir 目录里的 jpg/png 按文件名排序(newspic_cards.py 出的 01.png…NN.png 刚好)。两个都给就先 --images 再目录。"""
|
|
750
|
-
paths = [p.strip() for p in (images or "").split(",") if p.strip()]
|
|
751
|
-
if images_dir:
|
|
752
|
-
if not os.path.isdir(images_dir):
|
|
753
|
-
die("--images-dir 不是目录:" + images_dir)
|
|
754
|
-
paths += [os.path.join(images_dir, f) for f in sorted(os.listdir(images_dir)) if f.lower().endswith((".png", ".jpg", ".jpeg"))]
|
|
755
|
-
return [os.path.abspath(p) for p in paths]
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
def readback_newspic(token, media_id, title):
|
|
759
|
-
"""图片消息的回读只核标题。news_item 里还有哪些字段先记下来(结果文件里的 readback_fields),攒够实测再决定核什么。"""
|
|
760
|
-
j = draft_get(token, media_id)
|
|
761
|
-
if "news_item" not in j:
|
|
762
|
-
return False, "draft/get 失败:" + explain(j), []
|
|
763
|
-
a = j["news_item"][0]
|
|
764
|
-
fields = sorted(a.keys())
|
|
765
|
-
got = a.get("title")
|
|
766
|
-
if got != title:
|
|
767
|
-
return False, "回读:标题不一致,回的是《%s》" % got, fields
|
|
768
|
-
return True, "回读:标题《%s》一致,article_type=%s" % (got, a.get("article_type", "(接口没回这个字段)")), fields
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
def cmd_push_newspic(args):
|
|
772
|
-
if not os.path.exists(args.text):
|
|
773
|
-
die("配文文件不存在:" + args.text)
|
|
774
|
-
text, warnings = newspic_text(io.open(args.text, encoding="utf-8").read())
|
|
775
|
-
title = (args.title or "").strip()
|
|
776
|
-
paths = collect_images(args.images, args.images_dir)
|
|
777
|
-
errors = newspic_gate(title, text, paths)
|
|
778
|
-
print("标题:%s(%d 字)" % (title, len(title)))
|
|
779
|
-
print("配文:%d 字 %d 字节;%d 张图,第一张是封面" % (len(text), len(text.encode("utf-8")), len(paths)))
|
|
780
|
-
for p in paths:
|
|
781
|
-
print(" 图:%s(%dKB)" % (os.path.basename(p), (os.path.getsize(p) // 1024) if os.path.exists(p) else 0))
|
|
782
|
-
for w in warnings:
|
|
783
|
-
print(" 提醒:" + w)
|
|
784
|
-
for e in errors:
|
|
785
|
-
print(" 不过:" + e)
|
|
786
|
-
if errors:
|
|
787
|
-
die("先把上面的不过项改掉再推")
|
|
788
|
-
stem = os.path.splitext(os.path.abspath(args.text))[0]
|
|
789
|
-
if args.dry_run:
|
|
790
|
-
payload = {"articles": [dict({"article_type": "newspic", "title": title, "content": text,
|
|
791
|
-
"image_info": {"image_list": [{"image_media_id": "<dry-run:%s>" % os.path.basename(p)} for p in paths]}},
|
|
792
|
-
**article_opts(args))]}
|
|
793
|
-
out = stem + ".newspic-dryrun.json"
|
|
794
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(payload, ensure_ascii=False, indent=1))
|
|
795
|
-
print("dry-run:没联网。请求体已写到 " + out)
|
|
796
|
-
return
|
|
797
|
-
appid, secret = load_credentials()
|
|
798
|
-
token = get_token(appid, secret)
|
|
799
|
-
print("ok:access_token 拿到")
|
|
800
|
-
media_ids = []
|
|
801
|
-
for k, p in enumerate(paths, 1):
|
|
802
|
-
mid = upload_material(token, p, "第 %d 张图" % k)
|
|
803
|
-
media_ids.append({"path": p, "media_id": mid})
|
|
804
|
-
print(" 第 %d 张已传为永久素材:%s -> %s" % (k, os.path.basename(p), mid))
|
|
805
|
-
article = dict({"article_type": "newspic", "title": title, "content": text,
|
|
806
|
-
"image_info": {"image_list": [{"image_media_id": m["media_id"]} for m in media_ids]}}, **article_opts(args))
|
|
807
|
-
j = post_json(token, "/cgi-bin/draft/add", {"articles": [article]}, timeout=120, fatal=False)
|
|
808
|
-
if no_reply(j):
|
|
809
|
-
draft_add_unknown(stem, "newspic-result", {"title": title, "images": media_ids, "error": j.get("errmsg")})
|
|
810
|
-
if "media_id" not in j:
|
|
811
|
-
die("draft/add 失败:" + explain(j))
|
|
812
|
-
media_id = j["media_id"]
|
|
813
|
-
print("ok:图片消息已进草稿箱,media_id=" + media_id)
|
|
814
|
-
ok, msg, fields = readback_newspic(token, media_id, title)
|
|
815
|
-
print(("ok:" if ok else "注意:") + msg)
|
|
816
|
-
result = {"type": "newspic", "title": title, "media_id": media_id, "images": media_ids, "chars": len(text),
|
|
817
|
-
"pushed_at": _dt.datetime.now().isoformat(timespec="seconds"), "readback": msg, "readback_fields": fields}
|
|
818
|
-
out = stem + ".newspic-result-%s.json" % _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
819
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
820
|
-
print("结果已落盘:" + out + "(报 media_id 从这里复制,别手抄)")
|
|
821
|
-
print("接下来是人的活:去公众号后台草稿箱点进这条,逐张看图、看配文、看封面裁切,没问题再点发布。")
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
def draft_get(token, media_id):
|
|
825
|
-
"""draft/get 原样返回 JSON(响应是 text/plain 不带 charset,http_json 已按 UTF-8 解)。"""
|
|
826
|
-
return post_json(token, "/cgi-bin/draft/get", {"media_id": media_id}, timeout=60)
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
def readback(token, media_id, title=None, n_images=None):
|
|
830
|
-
j = draft_get(token, media_id)
|
|
831
|
-
if "news_item" not in j:
|
|
832
|
-
return False, "draft/get 失败:" + explain(j)
|
|
833
|
-
a = j["news_item"][0]
|
|
834
|
-
content = a.get("content", "")
|
|
835
|
-
imgs = content.count("mmbiz.qpic.cn")
|
|
836
|
-
problems = []
|
|
837
|
-
if title and a.get("title") != title:
|
|
838
|
-
problems.append("标题回读不一致:%r" % a.get("title"))
|
|
839
|
-
if n_images is not None and imgs < n_images:
|
|
840
|
-
problems.append("图片回读 %d 张,少于上传的 %d 张" % (imgs, n_images))
|
|
841
|
-
if DASH_RE.search(content):
|
|
842
|
-
problems.append("回读正文里有长破折号")
|
|
843
|
-
summary = "回读:标题《%s》,正文约 %d 汉字,%d 张微信图床图" % (a.get("title"), cjk_count(content), imgs)
|
|
844
|
-
return (not problems), summary + ("" if not problems else ";" + ";".join(problems))
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
def cmd_verify(args):
|
|
848
|
-
appid, secret = load_credentials()
|
|
849
|
-
token = get_token(appid, secret)
|
|
850
|
-
ok, msg = readback(token, args.media_id)
|
|
851
|
-
print(("ok:" if ok else "注意:") + msg)
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
# ---------- 发布(只在人说「发」之后、只对微信认证企业号) ----------
|
|
855
|
-
def publish_status_text(status):
|
|
856
|
-
return PUBLISH_STATUS.get(status, "未知状态")
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
def cmd_publish(args):
|
|
860
|
-
if not args.reviewed:
|
|
861
|
-
print("拒绝:人要先在后台看过草稿 说一句发 才能跑。看过了、说了发,再加 --reviewed 跑一次。什么都没发。")
|
|
862
|
-
sys.exit(2)
|
|
863
|
-
media_id = (args.media_id or "").strip()
|
|
864
|
-
if not media_id:
|
|
865
|
-
die("--media-id 不能为空,从 *.draft-result-<时间>.json 里复制")
|
|
866
|
-
out_dir = os.path.abspath(args.out_dir or os.getcwd())
|
|
867
|
-
if not os.path.isdir(out_dir):
|
|
868
|
-
die("--out-dir 不存在,什么都没发:" + out_dir)
|
|
869
|
-
appid, secret = load_credentials()
|
|
870
|
-
token = get_token(appid, secret)
|
|
871
|
-
print("ok:access_token 拿到")
|
|
872
|
-
|
|
873
|
-
# 1. 回读:确认草稿还在,打印标题
|
|
874
|
-
j = draft_get(token, media_id)
|
|
875
|
-
if "news_item" not in j:
|
|
876
|
-
die("draft/get 失败,草稿不存在、media_id 不对或这个号的草稿箱接口没开通,什么都没发:" + explain(j))
|
|
877
|
-
items = j["news_item"]
|
|
878
|
-
titles = [a.get("title") or "" for a in items]
|
|
879
|
-
print("回读:草稿存在,%d 篇,标题《%s》" % (len(items), "》《".join(titles)))
|
|
880
|
-
print("提交发布后接口收不回来,发之前确认人已经在后台看过这篇草稿。")
|
|
881
|
-
|
|
882
|
-
# 2. 提交发布
|
|
883
|
-
j = post_json(token, "/cgi-bin/freepublish/submit", {"media_id": media_id}, timeout=60)
|
|
884
|
-
if j.get("errcode", 0) != 0 or "publish_id" not in j:
|
|
885
|
-
if is_no_permission(j):
|
|
886
|
-
die("freepublish/submit 没权限:%s %s" % (explain(j), PUBLISH_PERMISSION_NOTE))
|
|
887
|
-
die("freepublish/submit 失败:" + explain(j))
|
|
888
|
-
publish_id = j["publish_id"]
|
|
889
|
-
msg_data_id = j.get("msg_data_id")
|
|
890
|
-
print("ok:发布任务已提交,publish_id=%s" % publish_id)
|
|
891
|
-
|
|
892
|
-
# 提交成功就先落一次盘:publish_id 一定进文件,后面查状态出什么错都不丢
|
|
893
|
-
now = _dt.datetime.now()
|
|
894
|
-
safe_id = re.sub(r"[^A-Za-z0-9_\-]", "_", media_id)
|
|
895
|
-
out = os.path.join(out_dir, "%s.publish-result-%s.json" % (safe_id, now.strftime("%Y%m%d-%H%M%S")))
|
|
896
|
-
|
|
897
|
-
def write_result(status, last, polls):
|
|
898
|
-
detail = last.get("article_detail") or {}
|
|
899
|
-
urls = [it.get("article_url") for it in (detail.get("item") or []) if it.get("article_url")]
|
|
900
|
-
fail_idx = last.get("fail_idx") or []
|
|
901
|
-
result = {
|
|
902
|
-
"media_id": media_id,
|
|
903
|
-
"titles": titles,
|
|
904
|
-
"publish_id": publish_id,
|
|
905
|
-
"msg_data_id": msg_data_id,
|
|
906
|
-
"publish_status": status,
|
|
907
|
-
"publish_status_text": publish_status_text(status) if status is not None else "没查到状态",
|
|
908
|
-
"article_id": last.get("article_id"),
|
|
909
|
-
"article_urls": urls,
|
|
910
|
-
"fail_idx": fail_idx,
|
|
911
|
-
"polls": polls,
|
|
912
|
-
"submitted_at": now.isoformat(timespec="seconds"),
|
|
913
|
-
}
|
|
914
|
-
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
915
|
-
return urls, fail_idx
|
|
916
|
-
|
|
917
|
-
write_result(None, {}, [])
|
|
918
|
-
print("结果已落盘(publish_id 已记进去,查状态之后会覆盖写):" + out)
|
|
919
|
-
|
|
920
|
-
# 3. 轮询状态:最多 6 次,每次隔 5 秒。查状态的网络错误不致命,记进 polls 继续查
|
|
921
|
-
status, last, polls = None, {}, []
|
|
922
|
-
for attempt in range(1, PUBLISH_POLL_TIMES + 1):
|
|
923
|
-
last = post_json(token, "/cgi-bin/freepublish/get", {"publish_id": publish_id}, timeout=60, fatal=False)
|
|
924
|
-
if "publish_status" not in last:
|
|
925
|
-
print(" 第 %d 次查状态失败:%s" % (attempt, explain(last)))
|
|
926
|
-
polls.append({"attempt": attempt, "error": explain(last)})
|
|
927
|
-
else:
|
|
928
|
-
status = last.get("publish_status")
|
|
929
|
-
polls.append({"attempt": attempt, "publish_status": status})
|
|
930
|
-
print(" 第 %d 次查状态:%s(publish_status=%s)" % (attempt, publish_status_text(status), status))
|
|
931
|
-
if status != 1:
|
|
932
|
-
break
|
|
933
|
-
if attempt < PUBLISH_POLL_TIMES:
|
|
934
|
-
time.sleep(PUBLISH_POLL_INTERVAL)
|
|
935
|
-
|
|
936
|
-
# 4. 落盘:同一个文件名覆盖写
|
|
937
|
-
urls, fail_idx = write_result(status, last, polls)
|
|
938
|
-
print("结果已落盘:" + out)
|
|
939
|
-
|
|
940
|
-
# 5. 按状态报中文
|
|
941
|
-
if status == 0:
|
|
942
|
-
print("ok:发布成功,《%s》已发布。" % "》《".join(titles))
|
|
943
|
-
for u in urls:
|
|
944
|
-
print(" article_url=" + u)
|
|
945
|
-
if not urls:
|
|
946
|
-
print(" 接口没回 article_url,去后台「已发表」里拿链接。")
|
|
947
|
-
print("接下来是人的活:把文章链接交回群。原创和赞赏要在后台草稿里勾好再说发,评论置顶去后台做。")
|
|
948
|
-
return
|
|
949
|
-
if status == 1:
|
|
950
|
-
print("注意:查了 %d 次还在发布中,不再等了。publish_id=%s 已记在结果文件里,几分钟后去后台「已发表」看结果。"
|
|
951
|
-
% (PUBLISH_POLL_TIMES, publish_id))
|
|
952
|
-
return
|
|
953
|
-
if status is None:
|
|
954
|
-
die("提交成功但 %d 次都没查到状态。publish_id=%s 已记在结果文件里,去后台「已发表」看结果。"
|
|
955
|
-
% (PUBLISH_POLL_TIMES, publish_id))
|
|
956
|
-
hint = {
|
|
957
|
-
2: "原创声明没过,去后台看这篇的原创状态,改完重新推草稿再发。",
|
|
958
|
-
3: "常规失败,去后台看这篇草稿,fail_idx=%s。" % fail_idx,
|
|
959
|
-
4: "平台审核不通过,去后台看通知里的原因,改完重新推草稿再发。",
|
|
960
|
-
5: "发出去过,之后被用户在后台删了。",
|
|
961
|
-
6: "发出去过,之后被系统封了,去后台看通知。",
|
|
962
|
-
}.get(status, "publish_status=%s 不在已知表里,去后台看。" % status)
|
|
963
|
-
die("发布没成:%s。%s" % (publish_status_text(status), hint))
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
def main():
|
|
967
|
-
ap = argparse.ArgumentParser(description="公众号推草稿箱;publish 只在人说「发」之后跑,只有微信认证企业号能用;没有删草稿命令")
|
|
968
|
-
sub = ap.add_subparsers(dest="cmd")
|
|
969
|
-
sub.add_parser("check", help="拿 token 验证凭据和白名单,不推")
|
|
970
|
-
r = sub.add_parser("render", help="Markdown 转微信 HTML 并校验,不联网")
|
|
971
|
-
r.add_argument("--md", required=True)
|
|
972
|
-
r.add_argument("--out")
|
|
973
|
-
r.add_argument("--title")
|
|
974
|
-
r.add_argument("--no-cite", action="store_true", help="外链只留文字,不生成文末「参考链接」")
|
|
975
|
-
p = sub.add_parser("push", help="传图、传封面、推草稿箱、回读")
|
|
976
|
-
p.add_argument("--no-cite", action="store_true", help="外链只留文字,不生成文末「参考链接」")
|
|
977
|
-
p.add_argument("--comment", choices=["open", "fans", "off"], default="open", help="留言:open 所有人可留言(默认)/ fans 仅粉丝 / off 关闭")
|
|
978
|
-
p.add_argument("--source-url", help="「阅读原文」指向的地址(content_source_url),不填就没有")
|
|
979
|
-
p.add_argument("--md", required=True)
|
|
980
|
-
p.add_argument("--title")
|
|
981
|
-
p.add_argument("--cover")
|
|
982
|
-
p.add_argument("--digest", default="")
|
|
983
|
-
p.add_argument("--author", default="")
|
|
984
|
-
p.add_argument("--dry-run", action="store_true", help="不联网,把请求体写到文件看")
|
|
985
|
-
pn = sub.add_parser("push-newspic", help="图片消息(公众号里的「贴图」):一组图加一段纯文本配文推进草稿箱,第一张是封面")
|
|
986
|
-
pn.add_argument("--title", required=True, help="32 字内")
|
|
987
|
-
pn.add_argument("--text", required=True, help="配文文件,纯文本,不能带 HTML;结果文件写在它旁边")
|
|
988
|
-
pn.add_argument("--images", help="图片路径,逗号分隔,顺序就是展示顺序,第一张是封面")
|
|
989
|
-
pn.add_argument("--images-dir", help="或者给目录:里面的 jpg/png 按文件名排序;newspic_cards.py 出的 cards 目录直接用")
|
|
990
|
-
pn.add_argument("--comment", choices=["open", "fans", "off"], default="open", help="留言:open 所有人可留言(默认)/ fans 仅粉丝 / off 关闭")
|
|
991
|
-
pn.add_argument("--dry-run", action="store_true", help="不联网,把请求体写到文件看")
|
|
992
|
-
v = sub.add_parser("verify", help="回读一篇草稿")
|
|
993
|
-
v.add_argument("--media-id", required=True)
|
|
994
|
-
pb = sub.add_parser("publish", help="人在后台看过草稿、说了「发」之后才跑:回读、提交发布、轮询状态;只有微信认证企业号能用")
|
|
995
|
-
pb.add_argument("--media-id", required=True, help="草稿的 media_id,从 *.draft-result-<时间>.json 里复制")
|
|
996
|
-
pb.add_argument("--reviewed", action="store_true", help="人已经在后台看过这篇草稿并说了发。没有这个参数直接拒绝")
|
|
997
|
-
pb.add_argument("--out-dir", help="结果文件 *.publish-result-<时间>.json 放哪个目录,默认当前目录")
|
|
998
|
-
tn = sub.add_parser("tunnel", help="备选:借远程机的 IP 过白名单(不想每次 IP 变了都加白名单时用)。打印 ssh 命令,配了 TUNNEL 就顺带测一下通不通")
|
|
999
|
-
tn.add_argument("--vps", help="远程机 用户@IP,只用来打印 ssh 命令")
|
|
1000
|
-
args = ap.parse_args()
|
|
1001
|
-
load_tunnel()
|
|
1002
|
-
global NO_CITE
|
|
1003
|
-
NO_CITE = bool(getattr(args, "no_cite", False))
|
|
1004
|
-
if args.cmd == "check":
|
|
1005
|
-
cmd_check(args)
|
|
1006
|
-
elif args.cmd == "render":
|
|
1007
|
-
cmd_render(args)
|
|
1008
|
-
elif args.cmd == "push":
|
|
1009
|
-
cmd_push(args)
|
|
1010
|
-
elif args.cmd == "push-newspic":
|
|
1011
|
-
cmd_push_newspic(args)
|
|
1012
|
-
elif args.cmd == "verify":
|
|
1013
|
-
cmd_verify(args)
|
|
1014
|
-
elif args.cmd == "publish":
|
|
1015
|
-
cmd_publish(args)
|
|
1016
|
-
elif args.cmd == "tunnel":
|
|
1017
|
-
cmd_tunnel(args)
|
|
1018
|
-
else:
|
|
1019
|
-
ap.print_help()
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
if __name__ == "__main__":
|
|
1023
|
-
main()
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""公众号推草稿箱,外加一个只在人说「发」之后才跑的发布命令(没有删草稿命令)。
|
|
4
|
+
|
|
5
|
+
用法:
|
|
6
|
+
python wechat_draft.py check 读配置、拿 access_token、打印 ok,不推任何东西
|
|
7
|
+
python wechat_draft.py render --md 文章.md [--out 文章.html] 只把 Markdown 转成微信 HTML 并校验,不联网;顺带写一个 390 宽的预览页 *.preview.html
|
|
8
|
+
python wechat_draft.py push --md 文章.md --title "标题" --cover 封面.jpg [--digest "摘要"] [--author "作者"] [--dry-run]
|
|
9
|
+
传图、传封面、推草稿箱、回读核对、落盘结果
|
|
10
|
+
python wechat_draft.py push-newspic --title "标题" --text 配文.txt --images 1.png,2.png [--images-dir cards] [--comment open|fans|off] [--dry-run]
|
|
11
|
+
图片消息(公众号里的「贴图」):一组图加一段纯文本配文,第一张是封面;
|
|
12
|
+
图先传成永久素材再 draft/add,回读标题,落盘结果。卡片图用 newspic_cards.py 出
|
|
13
|
+
python wechat_draft.py verify --media-id XXXX 回读一篇草稿,核对中文、图片数、字数
|
|
14
|
+
python wechat_draft.py publish --media-id XXXX --reviewed 人在后台看过草稿、说了「发」之后才跑:
|
|
15
|
+
回读确认草稿存在并打印标题,提交发布,轮询状态,落盘结果
|
|
16
|
+
没有 --reviewed 直接拒绝。只有微信认证企业号能用发布接口。
|
|
17
|
+
|
|
18
|
+
凭据(二选一,永远不要贴进对话):
|
|
19
|
+
环境变量 WECHAT_MP_APPID / WECHAT_MP_SECRET
|
|
20
|
+
或配置文件 ~/.wechat-mp.env(可用 WECHAT_MP_ENV 指定路径),内容两行:
|
|
21
|
+
APPID=wx...
|
|
22
|
+
SECRET=...
|
|
23
|
+
|
|
24
|
+
只依赖 Python 3.8+ 标准库。装了 Pillow 时正文图超过 1MB 会自动压到 1MB 以内,没装就报错让你自己压。
|
|
25
|
+
"""
|
|
26
|
+
import argparse
|
|
27
|
+
import datetime as _dt
|
|
28
|
+
import io
|
|
29
|
+
import json
|
|
30
|
+
import mimetypes
|
|
31
|
+
import os
|
|
32
|
+
import re
|
|
33
|
+
import sys
|
|
34
|
+
import time
|
|
35
|
+
import urllib.parse
|
|
36
|
+
import urllib.request
|
|
37
|
+
import uuid
|
|
38
|
+
import http.client
|
|
39
|
+
import socket
|
|
40
|
+
import ssl
|
|
41
|
+
from html import escape
|
|
42
|
+
|
|
43
|
+
# 强制 IPv4(老板 2026-10-12 定):公众号 IP 白名单按 IPv4 核,机器走 IPv6 出去会报 40164 而且 errmsg 里是个 v6 地址,填不进去。
|
|
44
|
+
_getaddrinfo_orig = socket.getaddrinfo
|
|
45
|
+
def _getaddrinfo_v4_first(*args, **kwargs):
|
|
46
|
+
res = _getaddrinfo_orig(*args, **kwargs)
|
|
47
|
+
v4 = [r for r in res if r[0] == socket.AF_INET]
|
|
48
|
+
return v4 or res
|
|
49
|
+
socket.getaddrinfo = _getaddrinfo_v4_first
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
53
|
+
sys.stderr.reconfigure(encoding="utf-8")
|
|
54
|
+
except Exception:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
BASE = "https://api.weixin.qq.com"
|
|
58
|
+
UA = "wechat-draft-push/2.3"
|
|
59
|
+
CITATIONS = [] # 正文里的外链 → 文末「参考链接」[n]
|
|
60
|
+
NO_CITE = False # --no-cite:外链只留文字不留引用
|
|
61
|
+
TUNNEL = None # (host, port),本机→远程机的 ssh -L 隧道口,走它去 api.weixin.qq.com
|
|
62
|
+
BODY_IMG_LIMIT = 1024 * 1024 # uploadimg:jpg/png,1MB 以内
|
|
63
|
+
COVER_LIMIT = 10 * 1024 * 1024 # add_material type=image:10MB 以内
|
|
64
|
+
TITLE_MAX, AUTHOR_MAX, DIGEST_MAX = 32, 16, 120
|
|
65
|
+
CONTENT_MAX_CHARS, CONTENT_MAX_BYTES = 20000, 1024 * 1024
|
|
66
|
+
NEWSPIC_MAX_IMAGES = 20 # 图片消息:官方写的上限 20 张,第一张是封面
|
|
67
|
+
NEWSPIC_TEXT_MAX_BYTES = None # 官方文档没写配文长度,不硬编码;真撞到限制再把实测值填这里
|
|
68
|
+
NO_REPLY_PREFIXES = ("网络请求失败", "隧道请求失败", "返回的不是 JSON") # http_json(fatal=False) 自己造的三种「没收到回复」
|
|
69
|
+
|
|
70
|
+
# 发布状态(freepublish/get 的 publish_status)
|
|
71
|
+
PUBLISH_POLL_TIMES = 6 # 最多查 6 次
|
|
72
|
+
PUBLISH_POLL_INTERVAL = 5 # 每次隔 5 秒
|
|
73
|
+
PUBLISH_STATUS = {
|
|
74
|
+
0: "发布成功",
|
|
75
|
+
1: "发布中",
|
|
76
|
+
2: "原创失败",
|
|
77
|
+
3: "常规失败",
|
|
78
|
+
4: "平台审核不通过",
|
|
79
|
+
5: "成功后用户删除",
|
|
80
|
+
6: "成功后系统封禁",
|
|
81
|
+
}
|
|
82
|
+
PUBLISH_PERMISSION_NOTE = ("只有微信认证企业号能用发布接口,个人主体账号 2025 年 7 月起被回收。"
|
|
83
|
+
"草稿还在草稿箱里没动,去公众号后台点发布。")
|
|
84
|
+
NO_PERMISSION_CODES = {48001}
|
|
85
|
+
NO_PERMISSION_RE = re.compile(r"unauthorized|not authorized|no permission", re.I)
|
|
86
|
+
|
|
87
|
+
# 排版常量(内联样式,微信只认这个)
|
|
88
|
+
FONT = "font-size:15px;color:#333;line-height:1.8;letter-spacing:0.5px;"
|
|
89
|
+
P = '<p style="%smargin:0;">' % FONT
|
|
90
|
+
H = '<p style="font-size:17px;font-weight:bold;color:#111;line-height:1.8;letter-spacing:0.5px;margin:0;">'
|
|
91
|
+
BR = "<p><br/></p>"
|
|
92
|
+
CAPTION = '<p style="font-size:12px;color:#999;text-align:center;letter-spacing:0.5px;margin:0;">'
|
|
93
|
+
HR = '<p style="text-align:center;color:#ccc;margin:0;">────────</p>'
|
|
94
|
+
CODE_LINE = '<p style="font-family:Menlo,Consolas,monospace;font-size:13px;color:#e5e7eb;line-height:1.6;margin:0;word-break:break-all;">'
|
|
95
|
+
INLINE_CODE = '<span style="font-family:Menlo,Consolas,monospace;background-color:#f3f4f6;padding:1px 4px;border-radius:3px;font-size:14px;">'
|
|
96
|
+
CARD_HEAD = '<p style="font-size:15px;font-weight:bold;color:#111;line-height:1.8;letter-spacing:0.5px;margin:0;">'
|
|
97
|
+
CARD = '<section style="padding:12px 15px;background-color:%s;border-left:4px solid %s;margin:0;">%s</section>'
|
|
98
|
+
# GFM 提示块 > [!NOTE] 之类 → 四色信息卡,颜色沿用 html-rules.md 的调色板:蓝 正常信息、绿 推荐、橙 提醒、红 避坑
|
|
99
|
+
CALLOUTS = {
|
|
100
|
+
"NOTE": ("说明", "#1a73e8", "#f0f7ff"),
|
|
101
|
+
"IMPORTANT": ("重点", "#1a73e8", "#f0f7ff"),
|
|
102
|
+
"TIP": ("推荐", "#2e7d32", "#f1f8f2"),
|
|
103
|
+
"WARNING": ("注意", "#ff8f00", "#fff8e1"),
|
|
104
|
+
"CAUTION": ("避坑", "#c62828", "#fef2f2"),
|
|
105
|
+
}
|
|
106
|
+
CALLOUT_RE = re.compile(r"^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*(.*)$", re.I)
|
|
107
|
+
|
|
108
|
+
MARKER_RE = re.compile(r"\[(📝|💬|🖼|📊)[^\]]*\]")
|
|
109
|
+
DASH_RE = re.compile("[—–]")
|
|
110
|
+
IMG_LINE_RE = re.compile(r"^!\[([^\]]*)\]\(([^)]+)\)\s*$")
|
|
111
|
+
INLINE_IMG_RE = re.compile(r"!\[([^\]]*)\]\(([^)]+)\)")
|
|
112
|
+
LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)")
|
|
113
|
+
TABLE_SEP_RE = re.compile(r"^\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$")
|
|
114
|
+
FORBIDDEN_HTML = [
|
|
115
|
+
(re.compile(r"<table[\s>]", re.I), "table 标签微信不渲染"),
|
|
116
|
+
(re.compile(r"</?div[\s>]", re.I), "div 会被改写,用 section"),
|
|
117
|
+
(re.compile(r"<style[\s>]", re.I), "style 标签会被过滤"),
|
|
118
|
+
(re.compile(r"<script[\s>]", re.I), "script 会被过滤"),
|
|
119
|
+
(re.compile(r"\sclass\s*=", re.I), "class 属性会被剥离"),
|
|
120
|
+
(re.compile(r"\sid\s*=", re.I), "id 属性会被剥离"),
|
|
121
|
+
(re.compile(r"position\s*:\s*(fixed|absolute|sticky)", re.I), "position fixed/absolute 不支持"),
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def die(msg, code=1):
|
|
126
|
+
print("错误:" + msg)
|
|
127
|
+
sys.exit(code)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def cjk_count(text):
|
|
131
|
+
return sum(1 for c in text if "一" <= c <= "鿿")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# ---------- 凭据 ----------
|
|
135
|
+
def load_tunnel():
|
|
136
|
+
"""TUNNEL=127.0.0.1:8443 写在环境变量 WECHAT_MP_TUNNEL 或 ~/.wechat-mp.env 里。有就把对 api.weixin.qq.com 的请求全走它。"""
|
|
137
|
+
global TUNNEL
|
|
138
|
+
v = os.environ.get("WECHAT_MP_TUNNEL", "").strip()
|
|
139
|
+
path = os.environ.get("WECHAT_MP_ENV") or os.path.join(os.path.expanduser("~"), ".wechat-mp.env")
|
|
140
|
+
if not v and os.path.exists(path):
|
|
141
|
+
for line in io.open(path, encoding="utf-8"):
|
|
142
|
+
line = line.strip()
|
|
143
|
+
if "=" in line and not line.startswith("#"):
|
|
144
|
+
k, val = line.split("=", 1)
|
|
145
|
+
if k.strip().upper() in ("TUNNEL", "WECHAT_MP_TUNNEL"):
|
|
146
|
+
v = val.strip().strip('"').strip("'")
|
|
147
|
+
if v:
|
|
148
|
+
host, _, port = v.rpartition(":")
|
|
149
|
+
if host and port.isdigit():
|
|
150
|
+
TUNNEL = (host, int(port))
|
|
151
|
+
return TUNNEL
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def tunnel_request(method, url, data=None, headers=None, timeout=60):
|
|
155
|
+
"""连隧道口(本机 ssh -L 开的端口),TLS 的 SNI 和证书校验仍按 api.weixin.qq.com,证书对得上。"""
|
|
156
|
+
u = urllib.parse.urlsplit(url)
|
|
157
|
+
path = u.path + ("?" + u.query if u.query else "")
|
|
158
|
+
ctx = ssl.create_default_context()
|
|
159
|
+
raw_sock = socket.create_connection(TUNNEL, timeout=timeout)
|
|
160
|
+
sock = ctx.wrap_socket(raw_sock, server_hostname=u.hostname)
|
|
161
|
+
conn = http.client.HTTPConnection(u.hostname, 443, timeout=timeout)
|
|
162
|
+
conn.sock = sock
|
|
163
|
+
hdrs = {"User-Agent": UA, "Host": u.hostname}
|
|
164
|
+
hdrs.update(headers or {})
|
|
165
|
+
conn.request(method, path, body=data, headers=hdrs)
|
|
166
|
+
resp = conn.getresponse()
|
|
167
|
+
body = resp.read()
|
|
168
|
+
conn.close()
|
|
169
|
+
return body
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def load_credentials():
|
|
173
|
+
appid = os.environ.get("WECHAT_MP_APPID", "").strip()
|
|
174
|
+
secret = os.environ.get("WECHAT_MP_SECRET", "").strip()
|
|
175
|
+
path = os.environ.get("WECHAT_MP_ENV") or os.path.join(os.path.expanduser("~"), ".wechat-mp.env")
|
|
176
|
+
if (not appid or not secret) and os.path.exists(path):
|
|
177
|
+
for line in io.open(path, encoding="utf-8"):
|
|
178
|
+
line = line.strip()
|
|
179
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
180
|
+
continue
|
|
181
|
+
k, v = line.split("=", 1)
|
|
182
|
+
k, v = k.strip().upper(), v.strip().strip('"').strip("'")
|
|
183
|
+
if k in ("APPID", "WECHAT_MP_APPID") and not appid:
|
|
184
|
+
appid = v
|
|
185
|
+
if k in ("SECRET", "APPSECRET", "WECHAT_MP_SECRET") and not secret:
|
|
186
|
+
secret = v
|
|
187
|
+
if not appid or not secret:
|
|
188
|
+
die("没找到凭据。设环境变量 WECHAT_MP_APPID / WECHAT_MP_SECRET,或写配置文件 %s(两行:APPID=... 与 SECRET=...)" % path)
|
|
189
|
+
return appid, secret
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---------- HTTP(标准库) ----------
|
|
193
|
+
def http_json(method, url, data=None, headers=None, timeout=60, fatal=True):
|
|
194
|
+
"""fatal=True 时网络错误或非 JSON 直接退出;fatal=False 时返回 {"errcode": -1, "errmsg": ...} 交给调用方处理。"""
|
|
195
|
+
if TUNNEL and urllib.parse.urlsplit(url).hostname == "api.weixin.qq.com":
|
|
196
|
+
try:
|
|
197
|
+
raw = tunnel_request(method, url, data, headers, timeout)
|
|
198
|
+
except Exception as e:
|
|
199
|
+
if not fatal:
|
|
200
|
+
return {"errcode": -1, "errmsg": "隧道请求失败:%s" % e}
|
|
201
|
+
die("隧道请求失败:%s。隧道口 %s:%d 开着吗(本机先跑 ssh -N -L,见 tunnel 子命令)" % (e, TUNNEL[0], TUNNEL[1]))
|
|
202
|
+
else:
|
|
203
|
+
req = urllib.request.Request(url, data=data, method=method)
|
|
204
|
+
req.add_header("User-Agent", UA)
|
|
205
|
+
for k, v in (headers or {}).items():
|
|
206
|
+
req.add_header(k, v)
|
|
207
|
+
try:
|
|
208
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
209
|
+
raw = resp.read()
|
|
210
|
+
except urllib.error.HTTPError as e:
|
|
211
|
+
raw = e.read()
|
|
212
|
+
except Exception as e:
|
|
213
|
+
if not fatal:
|
|
214
|
+
return {"errcode": -1, "errmsg": "网络请求失败:%s" % e}
|
|
215
|
+
die("网络请求失败:%s(%s)" % (e, url.split("?")[0]))
|
|
216
|
+
try:
|
|
217
|
+
return json.loads(raw.decode("utf-8")) # 微信返回 text/plain 不带 charset,必须自己按 UTF-8 解
|
|
218
|
+
except Exception:
|
|
219
|
+
if not fatal:
|
|
220
|
+
return {"errcode": -1, "errmsg": "返回的不是 JSON:%r" % raw[:200]}
|
|
221
|
+
die("微信返回的不是 JSON:%r" % raw[:200])
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def post_json(token, path, payload, timeout=60, fatal=True):
|
|
225
|
+
"""带 access_token 的 JSON POST,请求体按 UTF-8 直传不转义中文。"""
|
|
226
|
+
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
227
|
+
return http_json("POST", BASE + path + "?access_token=" + token, body,
|
|
228
|
+
{"Content-Type": "application/json; charset=utf-8"}, timeout=timeout, fatal=fatal)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def multipart(fields, file_field, filename, file_bytes, content_type):
|
|
232
|
+
boundary = "----wechatdraft" + uuid.uuid4().hex
|
|
233
|
+
body = bytearray()
|
|
234
|
+
for k, v in fields.items():
|
|
235
|
+
body.extend(("--%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n" % (boundary, k, v)).encode("utf-8"))
|
|
236
|
+
body.extend(("--%s\r\nContent-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n"
|
|
237
|
+
% (boundary, file_field, filename, content_type)).encode("utf-8"))
|
|
238
|
+
body.extend(file_bytes)
|
|
239
|
+
body.extend(("\r\n--%s--\r\n" % boundary).encode("utf-8"))
|
|
240
|
+
return bytes(body), "multipart/form-data; boundary=" + boundary
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def explain(j):
|
|
244
|
+
code = j.get("errcode")
|
|
245
|
+
tips = {
|
|
246
|
+
-1: "微信系统繁忙,这次没进去,稍等一会再推一次。",
|
|
247
|
+
40164: "调接口的这台机器的公网 IP 不在白名单里。去公众号后台「设置与开发 → 基本配置 → IP 白名单」加上 errmsg 里那个 IP,加完再跑一次。本机跑的,家里 IP 变了会再报一次,再加一次就行,白名单能存多个,旧的不用删。",
|
|
248
|
+
40013: "AppID 不对。",
|
|
249
|
+
40125: "AppSecret 不对,或者被重置过。",
|
|
250
|
+
40001: "access_token 失效,重跑一次。",
|
|
251
|
+
40002: "参数不合法,多半是 media_id 或 publish_id 写错了。",
|
|
252
|
+
40007: "media_id 不合法。推草稿时:先看封面是不是传成了永久素材(结果文件里有 thumb_media_id),不是就重传封面再推,是的话就是 media_id 抄错了;发布时:草稿 media_id 抄错了,从最近一份 draft-result 文件重新复制。",
|
|
253
|
+
45110: "author 太长,16 字以内。",
|
|
254
|
+
45003: "标题太长,32 字以内。",
|
|
255
|
+
45004: "digest 太长,120 字以内。",
|
|
256
|
+
45166: "content 不合法:正文里有微信不认的标签或属性(script/iframe/外站图片地址/未转义的尖括号之类),或小绿书 newspic 的正文传了 HTML。先跑 render 看 HTML,去掉可疑标签再推。",
|
|
257
|
+
53404: "文章内容涉嫌违规,到公众号后台看具体提示,改正文后再推。",
|
|
258
|
+
53405: "文章含敏感内容,到公众号后台看具体提示,改正文后再推。",
|
|
259
|
+
45009: "接口调用次数到上限,明天再推。",
|
|
260
|
+
48001: "这个账号没有这个接口的权限。",
|
|
261
|
+
53503: "这篇草稿没过发布检查,去后台看草稿内容。",
|
|
262
|
+
53504: "这篇草稿要去公众平台官网里用,接口发不了。",
|
|
263
|
+
53505: "要先在公众平台官网手动保存成功,再发布。",
|
|
264
|
+
}
|
|
265
|
+
return "errcode=%s errmsg=%s%s" % (code, j.get("errmsg"), ("。" + tips[code]) if code in tips else "")
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def is_no_permission(j):
|
|
269
|
+
code = j.get("errcode")
|
|
270
|
+
msg = str(j.get("errmsg") or "")
|
|
271
|
+
return code in NO_PERMISSION_CODES or bool(NO_PERMISSION_RE.search(msg))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def get_token(appid, secret):
|
|
275
|
+
q = urllib.parse.urlencode({"grant_type": "client_credential", "appid": appid, "secret": secret})
|
|
276
|
+
j = http_json("GET", BASE + "/cgi-bin/token?" + q, timeout=20)
|
|
277
|
+
if "access_token" not in j:
|
|
278
|
+
die("拿 access_token 失败:" + explain(j))
|
|
279
|
+
return j["access_token"]
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def read_image(path, limit, shrink):
|
|
283
|
+
if not os.path.exists(path):
|
|
284
|
+
die("图片不存在:" + path)
|
|
285
|
+
ext = os.path.splitext(path)[1].lower()
|
|
286
|
+
if ext not in (".jpg", ".jpeg", ".png"):
|
|
287
|
+
die("只收 jpg/png:" + path)
|
|
288
|
+
data = io.open(path, "rb").read()
|
|
289
|
+
ctype = "image/png" if ext == ".png" else "image/jpeg"
|
|
290
|
+
if len(data) > limit:
|
|
291
|
+
if not shrink:
|
|
292
|
+
die("图片超过 %dKB:%s" % (limit // 1024, path))
|
|
293
|
+
try:
|
|
294
|
+
from PIL import Image
|
|
295
|
+
except Exception:
|
|
296
|
+
die("图片超过 %dKB 且没装 Pillow 压不了:%s(自己压一下,或 pip install pillow)" % (limit // 1024, path))
|
|
297
|
+
im = Image.open(io.BytesIO(data)).convert("RGB")
|
|
298
|
+
quality, scale = 88, 1.0
|
|
299
|
+
while True:
|
|
300
|
+
w, h = im.size
|
|
301
|
+
out = io.BytesIO()
|
|
302
|
+
im.resize((max(1, int(w * scale)), max(1, int(h * scale)))).save(out, "JPEG", quality=quality, optimize=True)
|
|
303
|
+
if out.tell() <= limit or (quality <= 50 and scale <= 0.4):
|
|
304
|
+
break
|
|
305
|
+
if quality > 50:
|
|
306
|
+
quality -= 8
|
|
307
|
+
else:
|
|
308
|
+
scale *= 0.85
|
|
309
|
+
data, ctype = out.getvalue(), "image/jpeg"
|
|
310
|
+
path = os.path.splitext(path)[0] + ".jpg"
|
|
311
|
+
print(" 图片已压到 %dKB:%s" % (len(data) // 1024, os.path.basename(path)))
|
|
312
|
+
return os.path.basename(path), data, ctype
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def upload_body_image(token, path):
|
|
316
|
+
name, data, ctype = read_image(path, BODY_IMG_LIMIT, shrink=True)
|
|
317
|
+
body, ct = multipart({}, "media", name, data, ctype)
|
|
318
|
+
j = http_json("POST", BASE + "/cgi-bin/media/uploadimg?access_token=" + token, body, {"Content-Type": ct}, timeout=120)
|
|
319
|
+
if "url" not in j:
|
|
320
|
+
die("uploadimg 失败(%s):%s" % (path, explain(j)))
|
|
321
|
+
return j["url"].replace("http://", "https://")
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def upload_material(token, path, label="封面"):
|
|
325
|
+
"""传成永久图片素材,返回 media_id。图文的封面(thumb_media_id)和图片消息的每一张图都走这里。"""
|
|
326
|
+
name, data, ctype = read_image(path, COVER_LIMIT, shrink=False)
|
|
327
|
+
body, ct = multipart({}, "media", name, data, ctype)
|
|
328
|
+
j = http_json("POST", BASE + "/cgi-bin/material/add_material?access_token=%s&type=image" % token, body, {"Content-Type": ct}, timeout=180)
|
|
329
|
+
if "media_id" not in j:
|
|
330
|
+
die("%s add_material 失败(%s):%s" % (label, os.path.basename(path), explain(j)))
|
|
331
|
+
return j["media_id"]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def upload_cover(token, path):
|
|
335
|
+
return upload_material(token, path, "封面")
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def no_reply(j):
|
|
339
|
+
"""draft/add 发出去了但没收到微信的回复(断网、超时、回的不是 JSON)。微信自己的 errcode -1 是「系统繁忙」,那是收到了回复,不算。"""
|
|
340
|
+
return j.get("errcode") == -1 and str(j.get("errmsg") or "").startswith(NO_REPLY_PREFIXES)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def draft_add_unknown(stem, kind, info):
|
|
344
|
+
"""没收到回复时草稿可能已经进了草稿箱:落一份 *-UNKNOWN-<时间>.json,退出码 3,让人先去草稿箱看,别重推。"""
|
|
345
|
+
now = _dt.datetime.now()
|
|
346
|
+
out = stem + ".%s-UNKNOWN-%s.json" % (kind, now.strftime("%Y%m%d-%H%M%S"))
|
|
347
|
+
info = dict(info, status="UNKNOWN", at=now.isoformat(timespec="seconds"))
|
|
348
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(info, ensure_ascii=False, indent=1))
|
|
349
|
+
print("draft/add 发出去了但没收到微信的回复:%s" % info.get("error"))
|
|
350
|
+
print("先去公众号后台草稿箱看有没有《%s》,有就别重推(重推会多一篇重复草稿);确定没有再推一次。这次的图片 media_id 已记在:%s" % (info.get("title"), out))
|
|
351
|
+
sys.exit(3)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
# ---------- Markdown → 微信 HTML ----------
|
|
355
|
+
def inline(text, warnings):
|
|
356
|
+
"""行内:行内图片只留说明文字(并提醒单独成行)、行内代码先护住(里面的 * ** [] 都不排版)、转义、链接去 URL、粗体、斜体。
|
|
357
|
+
标题、列表、引用、表格、段落都走这一个函数。"""
|
|
358
|
+
for mm in INLINE_IMG_RE.finditer(text):
|
|
359
|
+
warnings.append("行内图片请单独成行:" + mm.group(2)[:60])
|
|
360
|
+
text = INLINE_IMG_RE.sub(lambda mm: mm.group(1), text)
|
|
361
|
+
codes = []
|
|
362
|
+
def keep(m):
|
|
363
|
+
codes.append(INLINE_CODE + escape(m.group(1)) + "</span>")
|
|
364
|
+
return "\x00%d\x00" % (len(codes) - 1)
|
|
365
|
+
text = re.sub(r"`([^`]+)`", keep, text)
|
|
366
|
+
parts = []
|
|
367
|
+
pos = 0
|
|
368
|
+
for m in LINK_RE.finditer(text):
|
|
369
|
+
parts.append(escape(text[pos:m.start()]))
|
|
370
|
+
label, url = m.group(1), m.group(2).strip()
|
|
371
|
+
if url.startswith("https://mp.weixin.qq.com/"):
|
|
372
|
+
parts.append('<a href="%s">%s</a>' % (escape(url, quote=True), escape(label)))
|
|
373
|
+
elif NO_CITE:
|
|
374
|
+
warnings.append("正文链接已去掉网址只留文字:%s" % url[:60])
|
|
375
|
+
parts.append(escape(label))
|
|
376
|
+
else:
|
|
377
|
+
CITATIONS.append((label, url))
|
|
378
|
+
parts.append(escape(label) + '<sup>[%d]</sup>' % len(CITATIONS))
|
|
379
|
+
pos = m.end()
|
|
380
|
+
parts.append(escape(text[pos:]))
|
|
381
|
+
s = "".join(parts)
|
|
382
|
+
s = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", s)
|
|
383
|
+
s = re.sub(r"(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])", r"<em>\1</em>", s)
|
|
384
|
+
s = re.sub("\x00(\\d+)\x00", lambda m: codes[int(m.group(1))], s)
|
|
385
|
+
return s
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def join_lines(parts):
|
|
389
|
+
"""软换行拼回一段:两边都是英文、数字的补一个空格,中文直接接上。"""
|
|
390
|
+
out = parts[0] if parts else ""
|
|
391
|
+
for p in parts[1:]:
|
|
392
|
+
if out and p and re.search(r"[A-Za-z0-9,.;:!?)\"']$", out) and re.match(r"[A-Za-z0-9(\"']", p):
|
|
393
|
+
out += " " + p
|
|
394
|
+
else:
|
|
395
|
+
out += p
|
|
396
|
+
return out
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def quote_block(quote, warnings):
|
|
400
|
+
"""引用块。第一行是 [!NOTE] [!TIP] [!IMPORTANT] [!WARNING] [!CAUTION](GFM 提示块,后面可跟自定义标题)就按类型配色出带标题的信息卡;
|
|
401
|
+
不是就还是原来的橙色引用卡。"""
|
|
402
|
+
cm = CALLOUT_RE.match(quote[0]) if quote else None
|
|
403
|
+
if cm:
|
|
404
|
+
label, border, bg = CALLOUTS[cm.group(1).upper()]
|
|
405
|
+
head, body = (cm.group(2).strip() or label), quote[1:]
|
|
406
|
+
else:
|
|
407
|
+
head, body, border, bg = None, quote, "#ff8f00", "#fff8e1"
|
|
408
|
+
inner = (CARD_HEAD + inline(head, warnings) + "</p>") if head else ""
|
|
409
|
+
inner += "".join(P + inline(q, warnings) + "</p>" for q in body if q)
|
|
410
|
+
return CARD % (bg, border, inner)
|
|
411
|
+
|
|
412
|
+
|
|
413
|
+
def md_to_html(md_text, drop_first_h1=True):
|
|
414
|
+
"""返回 (blocks, images, title_from_h1, warnings)。images = [(占位符, 路径, 说明)]。"""
|
|
415
|
+
del CITATIONS[:]
|
|
416
|
+
text = md_text.replace("\r\n", "\n").replace("\r", "\n")
|
|
417
|
+
if text.startswith("---\n"):
|
|
418
|
+
end = text.find("\n---\n", 4)
|
|
419
|
+
if end != -1:
|
|
420
|
+
text = text[end + 5:]
|
|
421
|
+
warnings = []
|
|
422
|
+
n = len(DASH_RE.findall(text))
|
|
423
|
+
if n:
|
|
424
|
+
warnings.append("长破折号 %d 处已换成逗号" % n)
|
|
425
|
+
text = DASH_RE.sub(",", text)
|
|
426
|
+
lines = text.split("\n")
|
|
427
|
+
blocks, images, title = [], [], None
|
|
428
|
+
i = 0
|
|
429
|
+
while i < len(lines):
|
|
430
|
+
line = lines[i]
|
|
431
|
+
s = line.strip()
|
|
432
|
+
if not s:
|
|
433
|
+
i += 1
|
|
434
|
+
continue
|
|
435
|
+
if s.startswith("```"):
|
|
436
|
+
code = []
|
|
437
|
+
i += 1
|
|
438
|
+
while i < len(lines) and not lines[i].strip().startswith("```"):
|
|
439
|
+
code.append(lines[i])
|
|
440
|
+
i += 1
|
|
441
|
+
i += 1
|
|
442
|
+
inner = "".join(CODE_LINE + (escape(c) or " ") + "</p>" for c in code)
|
|
443
|
+
blocks.append('<section style="padding:12px 14px;background-color:#1f2937;border-radius:6px;">' + inner + "</section>")
|
|
444
|
+
continue
|
|
445
|
+
m = IMG_LINE_RE.match(s)
|
|
446
|
+
if m:
|
|
447
|
+
alt, src = m.group(1).strip(), m.group(2).strip()
|
|
448
|
+
ph = "{{IMG:%d}}" % len(images)
|
|
449
|
+
images.append((ph, src, alt))
|
|
450
|
+
b = '<p style="margin:0;"><img src="%s" style="width:100%%;"/></p>' % ph
|
|
451
|
+
if alt:
|
|
452
|
+
b += CAPTION + escape(alt) + "</p>"
|
|
453
|
+
blocks.append(b)
|
|
454
|
+
i += 1
|
|
455
|
+
continue
|
|
456
|
+
if re.match(r"^(-{3,}|\*{3,}|_{3,})$", s):
|
|
457
|
+
blocks.append(HR)
|
|
458
|
+
i += 1
|
|
459
|
+
continue
|
|
460
|
+
hm = re.match(r"^(#{1,6})\s+(.*)$", s)
|
|
461
|
+
if hm:
|
|
462
|
+
if hm.group(1) == "#" and title is None and drop_first_h1:
|
|
463
|
+
title = hm.group(2).strip()
|
|
464
|
+
i += 1
|
|
465
|
+
continue
|
|
466
|
+
blocks.append(H + inline(hm.group(2).strip(), warnings) + "</p>")
|
|
467
|
+
i += 1
|
|
468
|
+
continue
|
|
469
|
+
if s.startswith("|") and i + 1 < len(lines) and TABLE_SEP_RE.match(lines[i + 1].strip()):
|
|
470
|
+
header = [c.strip() for c in s.strip("|").split("|")]
|
|
471
|
+
i += 2
|
|
472
|
+
rows = []
|
|
473
|
+
while i < len(lines) and lines[i].strip().startswith("|"):
|
|
474
|
+
rows.append([c.strip() for c in lines[i].strip().strip("|").split("|")])
|
|
475
|
+
i += 1
|
|
476
|
+
labels = [inline(h, warnings) if h else "" for h in header] # 表头只排一次,里面的链接只引一次
|
|
477
|
+
for row in rows:
|
|
478
|
+
cells = [inline(c, warnings) for c in row]
|
|
479
|
+
inner = CARD_HEAD + "%s</p>" % (cells[0] if cells else "")
|
|
480
|
+
for k, c in enumerate(cells[1:], 1):
|
|
481
|
+
label = labels[k] if k < len(labels) else ""
|
|
482
|
+
inner += P + (label + ":" if label else "") + c + "</p>"
|
|
483
|
+
blocks.append(CARD % ("#f0f7ff", "#1a73e8", inner))
|
|
484
|
+
continue
|
|
485
|
+
if s.startswith(">"):
|
|
486
|
+
quote = []
|
|
487
|
+
while i < len(lines) and lines[i].strip().startswith(">"):
|
|
488
|
+
quote.append(lines[i].strip()[1:].strip())
|
|
489
|
+
i += 1
|
|
490
|
+
blocks.append(quote_block(quote, warnings))
|
|
491
|
+
continue
|
|
492
|
+
if re.match(r"^([-*•]|\d+[.、])\s+", s):
|
|
493
|
+
items = []
|
|
494
|
+
while i < len(lines) and re.match(r"^([-*•]|\d+[.、])\s+", lines[i].strip()):
|
|
495
|
+
t = lines[i].strip()
|
|
496
|
+
mm = re.match(r"^(\d+[.、])\s+(.*)$", t)
|
|
497
|
+
items.append((mm.group(1) + " " + mm.group(2)) if mm else "• " + re.sub(r"^[-*•]\s+", "", t))
|
|
498
|
+
i += 1
|
|
499
|
+
blocks.append("".join(P + inline(it, warnings) + "</p>" for it in items))
|
|
500
|
+
continue
|
|
501
|
+
para = [s]
|
|
502
|
+
i += 1
|
|
503
|
+
while i < len(lines) and lines[i].strip() and not re.match(r"^(#{1,6}\s|```|>|\||!\[|[-*•]\s|\d+[.、]\s|-{3,}$)", lines[i].strip()):
|
|
504
|
+
para.append(lines[i].strip())
|
|
505
|
+
i += 1
|
|
506
|
+
blocks.append(P + inline(join_lines(para), warnings) + "</p>")
|
|
507
|
+
return blocks, images, title, warnings
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def assemble(blocks):
|
|
511
|
+
body = ("\n" + BR + "\n").join(blocks)
|
|
512
|
+
if CITATIONS:
|
|
513
|
+
rows = "".join('<p style="font-size:13px;color:#888;line-height:1.7;margin:0 0 4px;word-break:break-all;">[%d] %s:%s</p>'
|
|
514
|
+
% (i + 1, escape(label), escape(url)) for i, (label, url) in enumerate(CITATIONS))
|
|
515
|
+
body += "\n" + BR + '\n<section style="margin-top:24px;padding-top:12px;border-top:1px solid #eee;"><p style="font-size:13px;color:#888;margin:0 0 6px;">参考链接</p>%s</section>' % rows
|
|
516
|
+
return body
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def check_html(html, mode, images):
|
|
520
|
+
errors, warnings = [], []
|
|
521
|
+
for rx, msg in FORBIDDEN_HTML:
|
|
522
|
+
if rx.search(html):
|
|
523
|
+
errors.append(msg)
|
|
524
|
+
if DASH_RE.search(html):
|
|
525
|
+
errors.append("仍有长破折号")
|
|
526
|
+
markers = MARKER_RE.findall(html)
|
|
527
|
+
if markers:
|
|
528
|
+
(warnings if mode == "render" else errors).append("还有 %d 处待作者处理的标记 [📝/💬/🖼/📊],推之前要清掉" % len(markers))
|
|
529
|
+
if mode == "final":
|
|
530
|
+
for src in re.findall(r'<img src="([^"]+)"', html):
|
|
531
|
+
if not src.startswith("https://mmbiz.qpic.cn/") and not src.startswith("https://mmbiz.qlogo.cn/"):
|
|
532
|
+
errors.append("正文图不是微信图床地址:" + src[:60])
|
|
533
|
+
elif mode == "render" and images:
|
|
534
|
+
warnings.append("%d 张图在 render 模式下未上传,push 时会自动传" % len(images))
|
|
535
|
+
chars = len(html)
|
|
536
|
+
nbytes = len(html.encode("utf-8"))
|
|
537
|
+
if chars > CONTENT_MAX_CHARS:
|
|
538
|
+
errors.append("正文 HTML %d 字符,超过 %d" % (chars, CONTENT_MAX_CHARS))
|
|
539
|
+
if nbytes > CONTENT_MAX_BYTES:
|
|
540
|
+
errors.append("正文 HTML %d 字节,超过 1MB" % nbytes)
|
|
541
|
+
return errors, warnings
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def build(md_path, title, mode):
|
|
545
|
+
md_text = io.open(md_path, encoding="utf-8").read()
|
|
546
|
+
blocks, images, h1, warnings = md_to_html(md_text)
|
|
547
|
+
title = (title or h1 or "").strip()
|
|
548
|
+
html = assemble(blocks)
|
|
549
|
+
errors, w2 = check_html(html, mode, images)
|
|
550
|
+
warnings += w2
|
|
551
|
+
if not title:
|
|
552
|
+
errors.append("没有标题:用 --title 给,或者 Markdown 第一行写 # 标题")
|
|
553
|
+
if len(title) > TITLE_MAX:
|
|
554
|
+
errors.append("标题 %d 字,超过 %d" % (len(title), TITLE_MAX))
|
|
555
|
+
return html, images, title, errors, warnings, cjk_count(md_text)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def report_build(title, html, images, errors, warnings, chars):
|
|
559
|
+
print("标题:%s(%d 字)" % (title, len(title)))
|
|
560
|
+
print("正文:约 %d 个汉字,%d 个区块,%d 张图" % (chars, html.count(BR) + 1, len(images)))
|
|
561
|
+
for w in warnings:
|
|
562
|
+
print(" 提醒:" + w)
|
|
563
|
+
for e in errors:
|
|
564
|
+
print(" 不过:" + e)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
# ---------- 子命令 ----------
|
|
568
|
+
def cmd_check(args):
|
|
569
|
+
appid, secret = load_credentials()
|
|
570
|
+
token = get_token(appid, secret)
|
|
571
|
+
print("ok:AppID %s… 拿到 access_token(长度 %d),白名单通。什么都没推。" % (appid[:6], len(token)))
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def preview_shell(title, fragment, note="本机预览,390 宽;不是微信的真实渲染,图片是本地路径"):
|
|
575
|
+
"""把微信 HTML 片段套进一个 390 宽的手机壳,浏览器打开就能看排版。只是看,不是微信渲染。"""
|
|
576
|
+
return ('<!doctype html>\n<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
|
577
|
+
'<title>预览:%s</title><style>body{margin:0;background:#e5e5e5;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif}'
|
|
578
|
+
'.phone{width:390px;max-width:100%%;margin:24px auto;background:#fff;padding:20px 16px 48px;box-sizing:border-box;min-height:844px}'
|
|
579
|
+
'.phone h1{font-size:22px;line-height:1.4;margin:0 0 6px;color:#111}.note{font-size:12px;color:#999;margin:0 0 20px}img{max-width:100%%}'
|
|
580
|
+
'</style></head><body><div class="phone"><h1>%s</h1><p class="note">%s</p>\n%s\n</div></body></html>\n'
|
|
581
|
+
% (escape(title), escape(title), escape(note), fragment))
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def cmd_render(args):
|
|
585
|
+
html, images, title, errors, warnings, chars = build(args.md, args.title, "render")
|
|
586
|
+
report_build(title, html, images, errors, warnings, chars)
|
|
587
|
+
out = args.out or os.path.splitext(args.md)[0] + ".wechat.html"
|
|
588
|
+
for ph, src, _ in images:
|
|
589
|
+
html = html.replace(ph, escape(src, quote=True))
|
|
590
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(html)
|
|
591
|
+
print("HTML 已写到:" + out + ("(有不过项,推之前先改)" if errors else ""))
|
|
592
|
+
prev = os.path.splitext(args.md)[0] + ".preview.html"
|
|
593
|
+
io.open(prev, "w", encoding="utf-8", newline="\n").write(preview_shell(title or "(没有标题)", html))
|
|
594
|
+
print("预览页已写到:" + prev + "(浏览器打开看 390 宽的排版;不是微信的真实渲染,最终以草稿箱为准)")
|
|
595
|
+
sys.exit(1 if errors else 0)
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def article_opts(args):
|
|
599
|
+
"""draft/add 的三个可选项:留言开关、仅粉丝留言、「阅读原文」地址。"""
|
|
600
|
+
comment = getattr(args, "comment", "open") or "open"
|
|
601
|
+
d = {"need_open_comment": 0 if comment == "off" else 1,
|
|
602
|
+
"only_fans_can_comment": 1 if comment == "fans" else 0}
|
|
603
|
+
src = (getattr(args, "source_url", None) or "").strip()
|
|
604
|
+
if src:
|
|
605
|
+
if not src.startswith(("http://", "https://")):
|
|
606
|
+
die("--source-url 要以 http:// 或 https:// 开头")
|
|
607
|
+
d["content_source_url"] = src
|
|
608
|
+
return d
|
|
609
|
+
|
|
610
|
+
|
|
611
|
+
def cmd_tunnel(args):
|
|
612
|
+
vps = args.vps or "root@远程机IP"
|
|
613
|
+
print("备选,不想每次 IP 变了都去加白名单时用:白名单只填远程机的 IP,本机开一条隧道,微信接口的流量从远程机出去,AppSecret 不离开本机。")
|
|
614
|
+
print("一 本机开着一条隧道(开着别关):")
|
|
615
|
+
print(" ssh -N -L 127.0.0.1:8443:api.weixin.qq.com:443 %s" % vps)
|
|
616
|
+
print("二 ~/.wechat-mp.env 加一行:TUNNEL=127.0.0.1:8443")
|
|
617
|
+
print("三 之后 check / push / publish 照常跑,流量自动走隧道。")
|
|
618
|
+
if not TUNNEL:
|
|
619
|
+
print("现在没配 TUNNEL,先做第二步再回来测。")
|
|
620
|
+
return
|
|
621
|
+
q = urllib.parse.urlencode({"grant_type": "client_credential", "appid": "tunnel-test", "secret": "tunnel-test"})
|
|
622
|
+
j = http_json("GET", BASE + "/cgi-bin/token?" + q, timeout=20, fatal=False)
|
|
623
|
+
if j.get("errcode") in (40013, 40125, 41002, 40001):
|
|
624
|
+
print("ok:隧道通,微信那头收到了请求(回 errcode=%s 是因为用的测试 appid,正常)。" % j.get("errcode"))
|
|
625
|
+
else:
|
|
626
|
+
print("隧道不通或微信没回:%s" % explain(j))
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def cmd_push(args):
|
|
630
|
+
html, images, title, errors, warnings, chars = build(args.md, args.title, "prepush")
|
|
631
|
+
report_build(title, html, images, errors, warnings, chars)
|
|
632
|
+
if errors:
|
|
633
|
+
die("先把上面的不过项改掉再推")
|
|
634
|
+
author = (args.author or "").strip()
|
|
635
|
+
if len(author) > AUTHOR_MAX:
|
|
636
|
+
die("作者 %d 字,超过 %d" % (len(author), AUTHOR_MAX))
|
|
637
|
+
digest = (args.digest or "").strip()
|
|
638
|
+
if len(digest) > DIGEST_MAX:
|
|
639
|
+
die("摘要 %d 字,超过 %d" % (len(digest), DIGEST_MAX))
|
|
640
|
+
if not args.cover or not os.path.exists(args.cover):
|
|
641
|
+
die("封面必填(--cover 封面.jpg),图文草稿没有封面推不进去")
|
|
642
|
+
base_dir = os.path.dirname(os.path.abspath(args.md))
|
|
643
|
+
paths = []
|
|
644
|
+
for ph, src, _ in images:
|
|
645
|
+
p = src if os.path.isabs(src) else os.path.join(base_dir, src)
|
|
646
|
+
if src.startswith("https://mmbiz.qpic.cn/"):
|
|
647
|
+
paths.append((ph, None, src))
|
|
648
|
+
elif src.startswith("http://") or src.startswith("https://"):
|
|
649
|
+
die("正文图是外链,先下载到本地再引用:" + src[:80])
|
|
650
|
+
elif not os.path.exists(p):
|
|
651
|
+
die("正文图不存在:" + p)
|
|
652
|
+
else:
|
|
653
|
+
paths.append((ph, p, None))
|
|
654
|
+
if args.dry_run:
|
|
655
|
+
for ph, p, url in paths:
|
|
656
|
+
html = html.replace(ph, url or escape(p, quote=True))
|
|
657
|
+
payload = {"articles": [dict({"title": title, "author": author, "digest": digest, "content": html,
|
|
658
|
+
"thumb_media_id": "<dry-run>"}, **article_opts(args))]}
|
|
659
|
+
out = os.path.splitext(args.md)[0] + ".draft-dryrun.json"
|
|
660
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(payload, ensure_ascii=False, indent=1))
|
|
661
|
+
print("dry-run:没联网。请求体已写到 " + out)
|
|
662
|
+
return
|
|
663
|
+
appid, secret = load_credentials()
|
|
664
|
+
token = get_token(appid, secret)
|
|
665
|
+
print("ok:access_token 拿到")
|
|
666
|
+
img_urls = {}
|
|
667
|
+
for ph, p, url in paths:
|
|
668
|
+
if url is None:
|
|
669
|
+
url = upload_body_image(token, p)
|
|
670
|
+
print(" 正文图已传:%s -> %s…" % (os.path.basename(p), url[:48]))
|
|
671
|
+
img_urls[ph] = url
|
|
672
|
+
html = html.replace(ph, url)
|
|
673
|
+
thumb = upload_cover(token, args.cover)
|
|
674
|
+
print(" 封面已传为永久素材:thumb_media_id=" + thumb)
|
|
675
|
+
errors, _ = check_html(html, "final", images)
|
|
676
|
+
if errors:
|
|
677
|
+
die("推送前校验不过:" + ";".join(errors))
|
|
678
|
+
article = dict({"title": title, "author": author, "digest": digest, "content": html,
|
|
679
|
+
"thumb_media_id": thumb}, **article_opts(args))
|
|
680
|
+
body = json.dumps({"articles": [article]}, ensure_ascii=False).encode("utf-8")
|
|
681
|
+
j = http_json("POST", BASE + "/cgi-bin/draft/add?access_token=" + token, body,
|
|
682
|
+
{"Content-Type": "application/json; charset=utf-8"}, timeout=120, fatal=False)
|
|
683
|
+
if no_reply(j):
|
|
684
|
+
draft_add_unknown(os.path.splitext(args.md)[0], "draft-result",
|
|
685
|
+
{"title": title, "thumb_media_id": thumb, "images": img_urls, "error": j.get("errmsg")})
|
|
686
|
+
if "media_id" not in j:
|
|
687
|
+
die("draft/add 失败:" + explain(j))
|
|
688
|
+
media_id = j["media_id"]
|
|
689
|
+
print("ok:草稿已进草稿箱,media_id=" + media_id)
|
|
690
|
+
ok, msg = readback(token, media_id, title, len(img_urls))
|
|
691
|
+
print(("ok:" if ok else "注意:") + msg)
|
|
692
|
+
result = {"title": title, "media_id": media_id, "thumb_media_id": thumb, "images": img_urls,
|
|
693
|
+
"chinese_chars": chars, "pushed_at": _dt.datetime.now().isoformat(timespec="seconds"), "readback": msg}
|
|
694
|
+
out = os.path.splitext(args.md)[0] + ".draft-result-%s.json" % _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
695
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
696
|
+
print("结果已落盘:" + out + "(报 media_id 从这里复制,别手抄)")
|
|
697
|
+
print("接下来是人的活:去公众号后台草稿箱点进这篇,看图和排版,勾「声明原创」,开「赞赏」,没问题再点发布。")
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
# ---------- 图片消息(公众号里的「贴图」,接口叫 newspic) ----------
|
|
701
|
+
def newspic_text(raw):
|
|
702
|
+
"""配文归一:换行统一、每行去尾空格、三个以上空行压成两个、长破折号换逗号(记一条提醒)。不动别的。"""
|
|
703
|
+
warnings = []
|
|
704
|
+
text = raw.replace("\r\n", "\n").replace("\r", "\n")
|
|
705
|
+
n = len(re.findall("[—–]+", text))
|
|
706
|
+
if n:
|
|
707
|
+
warnings.append("长破折号 %d 处已换成逗号" % n)
|
|
708
|
+
text = re.sub("[—–]+", ",", text)
|
|
709
|
+
text = "\n".join(l.rstrip() for l in text.split("\n"))
|
|
710
|
+
text = re.sub(r"\n{3,}", "\n\n", text).strip()
|
|
711
|
+
return text, warnings
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def newspic_gate(title, text, image_paths):
|
|
715
|
+
"""推之前的门:标题 32 字内、配文非空且是纯文本(不带尖括号、不带待填标记、不带长破折号)、1 到 20 张本地 jpg/png、单张 10MB 内。返回错误列表,空=过。"""
|
|
716
|
+
errors = []
|
|
717
|
+
title = (title or "").strip()
|
|
718
|
+
if not title:
|
|
719
|
+
errors.append("没有标题:--title")
|
|
720
|
+
elif len(title) > TITLE_MAX:
|
|
721
|
+
errors.append("标题 %d 字,超过 %d" % (len(title), TITLE_MAX))
|
|
722
|
+
if not text.strip():
|
|
723
|
+
errors.append("配文是空的")
|
|
724
|
+
if "<" in text or ">" in text:
|
|
725
|
+
errors.append("配文里有尖括号:图片消息的 content 是纯文本,不能带 HTML(否则 45166)")
|
|
726
|
+
markers = MARKER_RE.findall(text)
|
|
727
|
+
if markers:
|
|
728
|
+
errors.append("配文还有 %d 处待作者处理的标记 [📝/💬/🖼/📊]" % len(markers))
|
|
729
|
+
if DASH_RE.search(text):
|
|
730
|
+
errors.append("配文仍有长破折号")
|
|
731
|
+
if NEWSPIC_TEXT_MAX_BYTES and len(text.encode("utf-8")) > NEWSPIC_TEXT_MAX_BYTES:
|
|
732
|
+
errors.append("配文 %d 字节,超过 %d" % (len(text.encode("utf-8")), NEWSPIC_TEXT_MAX_BYTES))
|
|
733
|
+
n = len(image_paths)
|
|
734
|
+
if n < 1:
|
|
735
|
+
errors.append("至少要 1 张图:--images 或 --images-dir")
|
|
736
|
+
elif n > NEWSPIC_MAX_IMAGES:
|
|
737
|
+
errors.append("%d 张图,超过 %d 张" % (n, NEWSPIC_MAX_IMAGES))
|
|
738
|
+
for p in image_paths:
|
|
739
|
+
if not os.path.exists(p):
|
|
740
|
+
errors.append("图片不存在:" + p)
|
|
741
|
+
elif os.path.splitext(p)[1].lower() not in (".jpg", ".jpeg", ".png"):
|
|
742
|
+
errors.append("只收 jpg/png:" + p)
|
|
743
|
+
elif os.path.getsize(p) > COVER_LIMIT:
|
|
744
|
+
errors.append("图片超过 %dMB:%s" % (COVER_LIMIT // 1024 // 1024, p))
|
|
745
|
+
return errors
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def collect_images(images, images_dir):
|
|
749
|
+
"""--images a.png,b.png 按给的顺序;--images-dir 目录里的 jpg/png 按文件名排序(newspic_cards.py 出的 01.png…NN.png 刚好)。两个都给就先 --images 再目录。"""
|
|
750
|
+
paths = [p.strip() for p in (images or "").split(",") if p.strip()]
|
|
751
|
+
if images_dir:
|
|
752
|
+
if not os.path.isdir(images_dir):
|
|
753
|
+
die("--images-dir 不是目录:" + images_dir)
|
|
754
|
+
paths += [os.path.join(images_dir, f) for f in sorted(os.listdir(images_dir)) if f.lower().endswith((".png", ".jpg", ".jpeg"))]
|
|
755
|
+
return [os.path.abspath(p) for p in paths]
|
|
756
|
+
|
|
757
|
+
|
|
758
|
+
def readback_newspic(token, media_id, title):
|
|
759
|
+
"""图片消息的回读只核标题。news_item 里还有哪些字段先记下来(结果文件里的 readback_fields),攒够实测再决定核什么。"""
|
|
760
|
+
j = draft_get(token, media_id)
|
|
761
|
+
if "news_item" not in j:
|
|
762
|
+
return False, "draft/get 失败:" + explain(j), []
|
|
763
|
+
a = j["news_item"][0]
|
|
764
|
+
fields = sorted(a.keys())
|
|
765
|
+
got = a.get("title")
|
|
766
|
+
if got != title:
|
|
767
|
+
return False, "回读:标题不一致,回的是《%s》" % got, fields
|
|
768
|
+
return True, "回读:标题《%s》一致,article_type=%s" % (got, a.get("article_type", "(接口没回这个字段)")), fields
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def cmd_push_newspic(args):
|
|
772
|
+
if not os.path.exists(args.text):
|
|
773
|
+
die("配文文件不存在:" + args.text)
|
|
774
|
+
text, warnings = newspic_text(io.open(args.text, encoding="utf-8").read())
|
|
775
|
+
title = (args.title or "").strip()
|
|
776
|
+
paths = collect_images(args.images, args.images_dir)
|
|
777
|
+
errors = newspic_gate(title, text, paths)
|
|
778
|
+
print("标题:%s(%d 字)" % (title, len(title)))
|
|
779
|
+
print("配文:%d 字 %d 字节;%d 张图,第一张是封面" % (len(text), len(text.encode("utf-8")), len(paths)))
|
|
780
|
+
for p in paths:
|
|
781
|
+
print(" 图:%s(%dKB)" % (os.path.basename(p), (os.path.getsize(p) // 1024) if os.path.exists(p) else 0))
|
|
782
|
+
for w in warnings:
|
|
783
|
+
print(" 提醒:" + w)
|
|
784
|
+
for e in errors:
|
|
785
|
+
print(" 不过:" + e)
|
|
786
|
+
if errors:
|
|
787
|
+
die("先把上面的不过项改掉再推")
|
|
788
|
+
stem = os.path.splitext(os.path.abspath(args.text))[0]
|
|
789
|
+
if args.dry_run:
|
|
790
|
+
payload = {"articles": [dict({"article_type": "newspic", "title": title, "content": text,
|
|
791
|
+
"image_info": {"image_list": [{"image_media_id": "<dry-run:%s>" % os.path.basename(p)} for p in paths]}},
|
|
792
|
+
**article_opts(args))]}
|
|
793
|
+
out = stem + ".newspic-dryrun.json"
|
|
794
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(payload, ensure_ascii=False, indent=1))
|
|
795
|
+
print("dry-run:没联网。请求体已写到 " + out)
|
|
796
|
+
return
|
|
797
|
+
appid, secret = load_credentials()
|
|
798
|
+
token = get_token(appid, secret)
|
|
799
|
+
print("ok:access_token 拿到")
|
|
800
|
+
media_ids = []
|
|
801
|
+
for k, p in enumerate(paths, 1):
|
|
802
|
+
mid = upload_material(token, p, "第 %d 张图" % k)
|
|
803
|
+
media_ids.append({"path": p, "media_id": mid})
|
|
804
|
+
print(" 第 %d 张已传为永久素材:%s -> %s" % (k, os.path.basename(p), mid))
|
|
805
|
+
article = dict({"article_type": "newspic", "title": title, "content": text,
|
|
806
|
+
"image_info": {"image_list": [{"image_media_id": m["media_id"]} for m in media_ids]}}, **article_opts(args))
|
|
807
|
+
j = post_json(token, "/cgi-bin/draft/add", {"articles": [article]}, timeout=120, fatal=False)
|
|
808
|
+
if no_reply(j):
|
|
809
|
+
draft_add_unknown(stem, "newspic-result", {"title": title, "images": media_ids, "error": j.get("errmsg")})
|
|
810
|
+
if "media_id" not in j:
|
|
811
|
+
die("draft/add 失败:" + explain(j))
|
|
812
|
+
media_id = j["media_id"]
|
|
813
|
+
print("ok:图片消息已进草稿箱,media_id=" + media_id)
|
|
814
|
+
ok, msg, fields = readback_newspic(token, media_id, title)
|
|
815
|
+
print(("ok:" if ok else "注意:") + msg)
|
|
816
|
+
result = {"type": "newspic", "title": title, "media_id": media_id, "images": media_ids, "chars": len(text),
|
|
817
|
+
"pushed_at": _dt.datetime.now().isoformat(timespec="seconds"), "readback": msg, "readback_fields": fields}
|
|
818
|
+
out = stem + ".newspic-result-%s.json" % _dt.datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
819
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
820
|
+
print("结果已落盘:" + out + "(报 media_id 从这里复制,别手抄)")
|
|
821
|
+
print("接下来是人的活:去公众号后台草稿箱点进这条,逐张看图、看配文、看封面裁切,没问题再点发布。")
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def draft_get(token, media_id):
|
|
825
|
+
"""draft/get 原样返回 JSON(响应是 text/plain 不带 charset,http_json 已按 UTF-8 解)。"""
|
|
826
|
+
return post_json(token, "/cgi-bin/draft/get", {"media_id": media_id}, timeout=60)
|
|
827
|
+
|
|
828
|
+
|
|
829
|
+
def readback(token, media_id, title=None, n_images=None):
|
|
830
|
+
j = draft_get(token, media_id)
|
|
831
|
+
if "news_item" not in j:
|
|
832
|
+
return False, "draft/get 失败:" + explain(j)
|
|
833
|
+
a = j["news_item"][0]
|
|
834
|
+
content = a.get("content", "")
|
|
835
|
+
imgs = content.count("mmbiz.qpic.cn")
|
|
836
|
+
problems = []
|
|
837
|
+
if title and a.get("title") != title:
|
|
838
|
+
problems.append("标题回读不一致:%r" % a.get("title"))
|
|
839
|
+
if n_images is not None and imgs < n_images:
|
|
840
|
+
problems.append("图片回读 %d 张,少于上传的 %d 张" % (imgs, n_images))
|
|
841
|
+
if DASH_RE.search(content):
|
|
842
|
+
problems.append("回读正文里有长破折号")
|
|
843
|
+
summary = "回读:标题《%s》,正文约 %d 汉字,%d 张微信图床图" % (a.get("title"), cjk_count(content), imgs)
|
|
844
|
+
return (not problems), summary + ("" if not problems else ";" + ";".join(problems))
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
def cmd_verify(args):
|
|
848
|
+
appid, secret = load_credentials()
|
|
849
|
+
token = get_token(appid, secret)
|
|
850
|
+
ok, msg = readback(token, args.media_id)
|
|
851
|
+
print(("ok:" if ok else "注意:") + msg)
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
# ---------- 发布(只在人说「发」之后、只对微信认证企业号) ----------
|
|
855
|
+
def publish_status_text(status):
|
|
856
|
+
return PUBLISH_STATUS.get(status, "未知状态")
|
|
857
|
+
|
|
858
|
+
|
|
859
|
+
def cmd_publish(args):
|
|
860
|
+
if not args.reviewed:
|
|
861
|
+
print("拒绝:人要先在后台看过草稿 说一句发 才能跑。看过了、说了发,再加 --reviewed 跑一次。什么都没发。")
|
|
862
|
+
sys.exit(2)
|
|
863
|
+
media_id = (args.media_id or "").strip()
|
|
864
|
+
if not media_id:
|
|
865
|
+
die("--media-id 不能为空,从 *.draft-result-<时间>.json 里复制")
|
|
866
|
+
out_dir = os.path.abspath(args.out_dir or os.getcwd())
|
|
867
|
+
if not os.path.isdir(out_dir):
|
|
868
|
+
die("--out-dir 不存在,什么都没发:" + out_dir)
|
|
869
|
+
appid, secret = load_credentials()
|
|
870
|
+
token = get_token(appid, secret)
|
|
871
|
+
print("ok:access_token 拿到")
|
|
872
|
+
|
|
873
|
+
# 1. 回读:确认草稿还在,打印标题
|
|
874
|
+
j = draft_get(token, media_id)
|
|
875
|
+
if "news_item" not in j:
|
|
876
|
+
die("draft/get 失败,草稿不存在、media_id 不对或这个号的草稿箱接口没开通,什么都没发:" + explain(j))
|
|
877
|
+
items = j["news_item"]
|
|
878
|
+
titles = [a.get("title") or "" for a in items]
|
|
879
|
+
print("回读:草稿存在,%d 篇,标题《%s》" % (len(items), "》《".join(titles)))
|
|
880
|
+
print("提交发布后接口收不回来,发之前确认人已经在后台看过这篇草稿。")
|
|
881
|
+
|
|
882
|
+
# 2. 提交发布
|
|
883
|
+
j = post_json(token, "/cgi-bin/freepublish/submit", {"media_id": media_id}, timeout=60)
|
|
884
|
+
if j.get("errcode", 0) != 0 or "publish_id" not in j:
|
|
885
|
+
if is_no_permission(j):
|
|
886
|
+
die("freepublish/submit 没权限:%s %s" % (explain(j), PUBLISH_PERMISSION_NOTE))
|
|
887
|
+
die("freepublish/submit 失败:" + explain(j))
|
|
888
|
+
publish_id = j["publish_id"]
|
|
889
|
+
msg_data_id = j.get("msg_data_id")
|
|
890
|
+
print("ok:发布任务已提交,publish_id=%s" % publish_id)
|
|
891
|
+
|
|
892
|
+
# 提交成功就先落一次盘:publish_id 一定进文件,后面查状态出什么错都不丢
|
|
893
|
+
now = _dt.datetime.now()
|
|
894
|
+
safe_id = re.sub(r"[^A-Za-z0-9_\-]", "_", media_id)
|
|
895
|
+
out = os.path.join(out_dir, "%s.publish-result-%s.json" % (safe_id, now.strftime("%Y%m%d-%H%M%S")))
|
|
896
|
+
|
|
897
|
+
def write_result(status, last, polls):
|
|
898
|
+
detail = last.get("article_detail") or {}
|
|
899
|
+
urls = [it.get("article_url") for it in (detail.get("item") or []) if it.get("article_url")]
|
|
900
|
+
fail_idx = last.get("fail_idx") or []
|
|
901
|
+
result = {
|
|
902
|
+
"media_id": media_id,
|
|
903
|
+
"titles": titles,
|
|
904
|
+
"publish_id": publish_id,
|
|
905
|
+
"msg_data_id": msg_data_id,
|
|
906
|
+
"publish_status": status,
|
|
907
|
+
"publish_status_text": publish_status_text(status) if status is not None else "没查到状态",
|
|
908
|
+
"article_id": last.get("article_id"),
|
|
909
|
+
"article_urls": urls,
|
|
910
|
+
"fail_idx": fail_idx,
|
|
911
|
+
"polls": polls,
|
|
912
|
+
"submitted_at": now.isoformat(timespec="seconds"),
|
|
913
|
+
}
|
|
914
|
+
io.open(out, "w", encoding="utf-8", newline="\n").write(json.dumps(result, ensure_ascii=False, indent=1))
|
|
915
|
+
return urls, fail_idx
|
|
916
|
+
|
|
917
|
+
write_result(None, {}, [])
|
|
918
|
+
print("结果已落盘(publish_id 已记进去,查状态之后会覆盖写):" + out)
|
|
919
|
+
|
|
920
|
+
# 3. 轮询状态:最多 6 次,每次隔 5 秒。查状态的网络错误不致命,记进 polls 继续查
|
|
921
|
+
status, last, polls = None, {}, []
|
|
922
|
+
for attempt in range(1, PUBLISH_POLL_TIMES + 1):
|
|
923
|
+
last = post_json(token, "/cgi-bin/freepublish/get", {"publish_id": publish_id}, timeout=60, fatal=False)
|
|
924
|
+
if "publish_status" not in last:
|
|
925
|
+
print(" 第 %d 次查状态失败:%s" % (attempt, explain(last)))
|
|
926
|
+
polls.append({"attempt": attempt, "error": explain(last)})
|
|
927
|
+
else:
|
|
928
|
+
status = last.get("publish_status")
|
|
929
|
+
polls.append({"attempt": attempt, "publish_status": status})
|
|
930
|
+
print(" 第 %d 次查状态:%s(publish_status=%s)" % (attempt, publish_status_text(status), status))
|
|
931
|
+
if status != 1:
|
|
932
|
+
break
|
|
933
|
+
if attempt < PUBLISH_POLL_TIMES:
|
|
934
|
+
time.sleep(PUBLISH_POLL_INTERVAL)
|
|
935
|
+
|
|
936
|
+
# 4. 落盘:同一个文件名覆盖写
|
|
937
|
+
urls, fail_idx = write_result(status, last, polls)
|
|
938
|
+
print("结果已落盘:" + out)
|
|
939
|
+
|
|
940
|
+
# 5. 按状态报中文
|
|
941
|
+
if status == 0:
|
|
942
|
+
print("ok:发布成功,《%s》已发布。" % "》《".join(titles))
|
|
943
|
+
for u in urls:
|
|
944
|
+
print(" article_url=" + u)
|
|
945
|
+
if not urls:
|
|
946
|
+
print(" 接口没回 article_url,去后台「已发表」里拿链接。")
|
|
947
|
+
print("接下来是人的活:把文章链接交回群。原创和赞赏要在后台草稿里勾好再说发,评论置顶去后台做。")
|
|
948
|
+
return
|
|
949
|
+
if status == 1:
|
|
950
|
+
print("注意:查了 %d 次还在发布中,不再等了。publish_id=%s 已记在结果文件里,几分钟后去后台「已发表」看结果。"
|
|
951
|
+
% (PUBLISH_POLL_TIMES, publish_id))
|
|
952
|
+
return
|
|
953
|
+
if status is None:
|
|
954
|
+
die("提交成功但 %d 次都没查到状态。publish_id=%s 已记在结果文件里,去后台「已发表」看结果。"
|
|
955
|
+
% (PUBLISH_POLL_TIMES, publish_id))
|
|
956
|
+
hint = {
|
|
957
|
+
2: "原创声明没过,去后台看这篇的原创状态,改完重新推草稿再发。",
|
|
958
|
+
3: "常规失败,去后台看这篇草稿,fail_idx=%s。" % fail_idx,
|
|
959
|
+
4: "平台审核不通过,去后台看通知里的原因,改完重新推草稿再发。",
|
|
960
|
+
5: "发出去过,之后被用户在后台删了。",
|
|
961
|
+
6: "发出去过,之后被系统封了,去后台看通知。",
|
|
962
|
+
}.get(status, "publish_status=%s 不在已知表里,去后台看。" % status)
|
|
963
|
+
die("发布没成:%s。%s" % (publish_status_text(status), hint))
|
|
964
|
+
|
|
965
|
+
|
|
966
|
+
def main():
|
|
967
|
+
ap = argparse.ArgumentParser(description="公众号推草稿箱;publish 只在人说「发」之后跑,只有微信认证企业号能用;没有删草稿命令")
|
|
968
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
969
|
+
sub.add_parser("check", help="拿 token 验证凭据和白名单,不推")
|
|
970
|
+
r = sub.add_parser("render", help="Markdown 转微信 HTML 并校验,不联网")
|
|
971
|
+
r.add_argument("--md", required=True)
|
|
972
|
+
r.add_argument("--out")
|
|
973
|
+
r.add_argument("--title")
|
|
974
|
+
r.add_argument("--no-cite", action="store_true", help="外链只留文字,不生成文末「参考链接」")
|
|
975
|
+
p = sub.add_parser("push", help="传图、传封面、推草稿箱、回读")
|
|
976
|
+
p.add_argument("--no-cite", action="store_true", help="外链只留文字,不生成文末「参考链接」")
|
|
977
|
+
p.add_argument("--comment", choices=["open", "fans", "off"], default="open", help="留言:open 所有人可留言(默认)/ fans 仅粉丝 / off 关闭")
|
|
978
|
+
p.add_argument("--source-url", help="「阅读原文」指向的地址(content_source_url),不填就没有")
|
|
979
|
+
p.add_argument("--md", required=True)
|
|
980
|
+
p.add_argument("--title")
|
|
981
|
+
p.add_argument("--cover")
|
|
982
|
+
p.add_argument("--digest", default="")
|
|
983
|
+
p.add_argument("--author", default="")
|
|
984
|
+
p.add_argument("--dry-run", action="store_true", help="不联网,把请求体写到文件看")
|
|
985
|
+
pn = sub.add_parser("push-newspic", help="图片消息(公众号里的「贴图」):一组图加一段纯文本配文推进草稿箱,第一张是封面")
|
|
986
|
+
pn.add_argument("--title", required=True, help="32 字内")
|
|
987
|
+
pn.add_argument("--text", required=True, help="配文文件,纯文本,不能带 HTML;结果文件写在它旁边")
|
|
988
|
+
pn.add_argument("--images", help="图片路径,逗号分隔,顺序就是展示顺序,第一张是封面")
|
|
989
|
+
pn.add_argument("--images-dir", help="或者给目录:里面的 jpg/png 按文件名排序;newspic_cards.py 出的 cards 目录直接用")
|
|
990
|
+
pn.add_argument("--comment", choices=["open", "fans", "off"], default="open", help="留言:open 所有人可留言(默认)/ fans 仅粉丝 / off 关闭")
|
|
991
|
+
pn.add_argument("--dry-run", action="store_true", help="不联网,把请求体写到文件看")
|
|
992
|
+
v = sub.add_parser("verify", help="回读一篇草稿")
|
|
993
|
+
v.add_argument("--media-id", required=True)
|
|
994
|
+
pb = sub.add_parser("publish", help="人在后台看过草稿、说了「发」之后才跑:回读、提交发布、轮询状态;只有微信认证企业号能用")
|
|
995
|
+
pb.add_argument("--media-id", required=True, help="草稿的 media_id,从 *.draft-result-<时间>.json 里复制")
|
|
996
|
+
pb.add_argument("--reviewed", action="store_true", help="人已经在后台看过这篇草稿并说了发。没有这个参数直接拒绝")
|
|
997
|
+
pb.add_argument("--out-dir", help="结果文件 *.publish-result-<时间>.json 放哪个目录,默认当前目录")
|
|
998
|
+
tn = sub.add_parser("tunnel", help="备选:借远程机的 IP 过白名单(不想每次 IP 变了都加白名单时用)。打印 ssh 命令,配了 TUNNEL 就顺带测一下通不通")
|
|
999
|
+
tn.add_argument("--vps", help="远程机 用户@IP,只用来打印 ssh 命令")
|
|
1000
|
+
args = ap.parse_args()
|
|
1001
|
+
load_tunnel()
|
|
1002
|
+
global NO_CITE
|
|
1003
|
+
NO_CITE = bool(getattr(args, "no_cite", False))
|
|
1004
|
+
if args.cmd == "check":
|
|
1005
|
+
cmd_check(args)
|
|
1006
|
+
elif args.cmd == "render":
|
|
1007
|
+
cmd_render(args)
|
|
1008
|
+
elif args.cmd == "push":
|
|
1009
|
+
cmd_push(args)
|
|
1010
|
+
elif args.cmd == "push-newspic":
|
|
1011
|
+
cmd_push_newspic(args)
|
|
1012
|
+
elif args.cmd == "verify":
|
|
1013
|
+
cmd_verify(args)
|
|
1014
|
+
elif args.cmd == "publish":
|
|
1015
|
+
cmd_publish(args)
|
|
1016
|
+
elif args.cmd == "tunnel":
|
|
1017
|
+
cmd_tunnel(args)
|
|
1018
|
+
else:
|
|
1019
|
+
ap.print_help()
|
|
1020
|
+
|
|
1021
|
+
|
|
1022
|
+
if __name__ == "__main__":
|
|
1023
|
+
main()
|