-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwechat_api.py
More file actions
349 lines (284 loc) · 11.3 KB
/
wechat_api.py
File metadata and controls
349 lines (284 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/usr/bin/env python3
"""
微信公众号 API 集成
自动发布文章到草稿箱
"""
import os
import json
import time
import requests
from typing import Dict, Optional
from datetime import datetime
class WeChatMPAPI:
"""微信公众号 API 封装"""
def __init__(
self,
app_id: Optional[str] = None,
app_secret: Optional[str] = None
):
self.app_id = app_id or os.getenv('WECHAT_APP_ID')
self.app_secret = app_secret or os.getenv('WECHAT_APP_SECRET')
self.base_url = "https://api.weixin.qq.com/cgi-bin"
self.access_token = None
self.token_expire_time = 0
if not self.app_id or not self.app_secret:
raise ValueError("请配置 WECHAT_APP_ID 和 WECHAT_APP_SECRET 环境变量")
def _get_access_token(self) -> str:
"""获取 access_token"""
# 检查是否已有有效 token
if self.access_token and time.time() < self.token_expire_time:
return self.access_token
url = f"{self.base_url}/token"
params = {
"grant_type": "client_credential",
"appid": self.app_id,
"secret": self.app_secret
}
response = requests.get(url, params=params, timeout=10)
response.raise_for_status()
data = response.json()
if "access_token" not in data:
raise Exception(f"获取 access_token 失败: {data.get('errmsg', '未知错误')}")
self.access_token = data["access_token"]
# token 有效期 2 小时,提前 5 分钟刷新
self.token_expire_time = time.time() + 7200 - 300
return self.access_token
def upload_image(self, image_path: str, image_type: str = "thumb") -> str:
"""
上传图片到微信服务器
Args:
image_path: 图片本地路径
image_type: 图片类型 (thumb:缩略图, image:其他图片)
Returns:
微信服务器返回的 media_id
"""
access_token = self._get_access_token()
url = f"{self.base_url}/material/add_material"
params = {
"access_token": access_token,
"type": image_type
}
with open(image_path, 'rb') as f:
files = {'media': f}
response = requests.post(url, params=params, files=files, timeout=30)
response.raise_for_status()
data = response.json()
if "media_id" not in data:
raise Exception(f"上传图片失败: {data.get('errmsg', '未知错误')}")
return data["media_id"]
def upload_news_image(self, image_path: str) -> str:
"""
上传图文消息内的图片
Args:
image_path: 图片本地路径
Returns:
图片 URL
"""
access_token = self._get_access_token()
url = f"{self.base_url}/media/uploadimg"
params = {"access_token": access_token}
with open(image_path, 'rb') as f:
files = {'media': f}
response = requests.post(url, params=params, files=files, timeout=30)
response.raise_for_status()
data = response.json()
if "url" not in data:
raise Exception(f"上传图文图片失败: {data.get('errmsg', '未知错误')}")
return data["url"]
def add_draft(
self,
title: str,
content: str,
thumb_media_id: str,
author: str = "ruby鑫燕",
digest: str = "",
show_cover_pic: int = 1
) -> str:
"""
添加草稿
Args:
title: 标题
content: 内容(HTML格式)
thumb_media_id: 封面图片 media_id
author: 作者
digest: 摘要(为空则自动提取)
show_cover_pic: 是否显示封面 (1:显示, 0:不显示)
Returns:
草稿 media_id
"""
access_token = self._get_access_token()
url = f"{self.base_url}/draft/add"
params = {"access_token": access_token}
# 如果没有提供摘要,自动生成
if not digest:
# 从内容中提取纯文本作为摘要,限制在50字节以内
import re
text = re.sub('<[^<]+?>', '', content) # 去除HTML标签
text = text.strip()
# 确保摘要不超过50字节
while len(text.encode('utf-8')) > 50:
text = text[:-1]
digest = text + "..." if len(text) > 10 else text
articles = [{
"title": title,
"author": author,
"digest": digest,
"content": content,
"content_source_url": "",
"thumb_media_id": thumb_media_id,
"show_cover_pic": show_cover_pic,
"need_open_comment": 0,
"only_fans_can_comment": 0
}]
payload = {"articles": articles}
response = requests.post(url, params=params, json=payload, timeout=30)
response.raise_for_status()
data = response.json()
if data.get("errcode", 0) != 0:
raise Exception(f"添加草稿失败: {data.get('errmsg', '未知错误')}")
return data.get("media_id", "")
def convert_to_wechat_html(self, content: str) -> str:
"""
将HTML转换为微信公众号兼容格式
Args:
content: 原始HTML内容
Returns:
微信兼容的HTML
"""
from bs4 import BeautifulSoup
# 确保内容是字符串格式
if isinstance(content, bytes):
content = content.decode('utf-8')
soup = BeautifulSoup(content, 'html.parser')
# 移除不支持的标签但保留内容(先做这个)
for tag in soup.find_all(['div', 'span']):
tag.unwrap()
# 处理段落 - 添加内联样式
for p in soup.find_all('p'):
# 保持原有文本内容
p['style'] = 'margin: 10px 0; line-height: 1.8; font-size: 15px; color: #333; text-align: left;'
# 处理标题
for h2 in soup.find_all('h2'):
h2.name = 'p' # 转换为段落
h2['style'] = 'font-size: 18px; font-weight: bold; margin: 20px 0 10px 0; color: #333;'
for h3 in soup.find_all('h3'):
h3.name = 'p' # 转换为段落
h3['style'] = 'font-size: 16px; font-weight: bold; margin: 15px 0 8px 0; color: #555;'
# 处理加粗和斜体
for strong in soup.find_all(['strong', 'b']):
strong['style'] = 'font-weight: bold; color: #000;'
for em in soup.find_all(['em', 'i']):
em['style'] = 'font-style: italic;'
# 处理列表 - 转换为段落
for ul in soup.find_all('ul'):
for li in ul.find_all('li'):
p = soup.new_tag('p')
p['style'] = 'margin: 5px 0; line-height: 1.6;'
p.string = '• ' + li.get_text()
li.replace_with(p)
ul.unwrap()
for ol in soup.find_all('ol'):
idx = 1
for li in ol.find_all('li'):
p = soup.new_tag('p')
p['style'] = 'margin: 5px 0; line-height: 1.6;'
p.string = f'{idx}. ' + li.get_text()
li.replace_with(p)
idx += 1
ol.unwrap()
# 处理引用
for blockquote in soup.find_all('blockquote'):
blockquote.name = 'p'
blockquote['style'] = 'border-left: 4px solid #ddd; padding-left: 15px; margin: 15px 0; color: #666; font-style: italic;'
# 处理图片
for img in soup.find_all('img'):
img['style'] = 'max-width: 100%; height: auto; display: block; margin: 15px auto;'
# 使用prettify并确保UTF-8编码
html_str = soup.prettify(formatter='html')
return html_str
def publish_draft(
self,
title: str,
content: str,
cover_image_path: str,
inline_images: list = None,
author: str = "ruby鑫燕",
digest: str = ""
) -> Dict:
"""
发布文章到草稿箱(完整流程)
Args:
title: 标题
content: 内容(HTML格式)
cover_image_path: 封面图片路径
inline_images: 正文图片路径列表
author: 作者
digest: 摘要
Returns:
结果信息
"""
print(f"\n📤 开始发布到微信公众号草稿箱...")
print(f" 标题: {title}")
try:
# 转换为微信兼容格式
print("\n【预处理】转换为微信兼容格式...")
content = self.convert_to_wechat_html(content)
# 1. 上传封面图
print("\n【1/3】上传封面图...")
thumb_media_id = self.upload_image(cover_image_path, "thumb")
print(f" ✅ 封面图上传成功: {thumb_media_id}")
# 2. 上传正文图片并替换内容中的图片路径
if inline_images:
print(f"\n【2/3】上传正文图片 ({len(inline_images)} 张)...")
for idx, img_path in enumerate(inline_images, 1):
print(f" 上传图片 {idx}/{len(inline_images)}...")
img_url = self.upload_news_image(img_path)
# 替换 HTML 中的本地路径为微信 URL
content = content.replace(img_path, img_url)
print(f" ✅ 图片 {idx} 上传成功")
# 3. 添加到草稿箱
print("\n【3/3】添加到草稿箱...")
media_id = self.add_draft(
title=title,
content=content,
thumb_media_id=thumb_media_id,
author=author,
digest=digest
)
print(f"\n✅ 发布成功!")
print(f" Media ID: {media_id}")
print(f"\n💡 请登录微信公众号后台查看草稿:")
print(f" https://mp.weixin.qq.com/")
return {
"success": True,
"media_id": media_id,
"thumb_media_id": thumb_media_id,
"title": title
}
except Exception as e:
print(f"\n❌ 发布失败: {e}")
return {
"success": False,
"error": str(e)
}
# ============ 测试代码 ============
if __name__ == "__main__":
print("🧪 测试微信公众号 API 连接...\n")
try:
wechat = WeChatMPAPI()
print("✅ 初始化成功")
print(f" App ID: {wechat.app_id[:10]}...\n")
# 测试获取 token
token = wechat._get_access_token()
print(f"✅ Access Token 获取成功: {token[:20]}...\n")
print("🎉 所有测试通过!微信公众号 API 配置正确。")
print("\n💡 使用方法:")
print(" from wechat_api import WeChatMPAPI")
print(" wechat = WeChatMPAPI()")
print(" wechat.publish_draft(title, content, cover, inline_images)")
except Exception as e:
print(f"❌ 测试失败: {e}")
print("\n请检查:")
print("1. 环境变量 WECHAT_APP_ID 和 WECHAT_APP_SECRET 是否正确配置")
print("2. 微信公众号是否已认证(未认证无法使用高级接口)")
print("3. 网络连接是否正常")