weixin.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  1. # -*- coding: utf-8 -*-
  2. """
  3. 微信视频号发布器
  4. 参考: matrix/tencent_uploader/main.py
  5. """
  6. import asyncio
  7. import json
  8. import os
  9. from datetime import datetime
  10. from typing import List
  11. from .base import (
  12. BasePublisher, PublishParams, PublishResult,
  13. WorkItem, WorksResult, CommentItem, CommentsResult
  14. )
  15. import os
  16. import time
  17. # 允许通过环境变量手动指定“上传视频入口”的选择器,便于在页面结构频繁变更时快速调整
  18. WEIXIN_UPLOAD_SELECTOR = os.environ.get("WEIXIN_UPLOAD_SELECTOR", "").strip()
  19. def format_short_title(origin_title: str) -> str:
  20. """
  21. 格式化短标题
  22. - 移除特殊字符
  23. - 长度限制在 6-16 字符
  24. """
  25. allowed_special_chars = "《》"":+?%°"
  26. filtered_chars = [
  27. char if char.isalnum() or char in allowed_special_chars
  28. else ' ' if char == ',' else ''
  29. for char in origin_title
  30. ]
  31. formatted_string = ''.join(filtered_chars)
  32. if len(formatted_string) > 16:
  33. formatted_string = formatted_string[:16]
  34. elif len(formatted_string) < 6:
  35. formatted_string += ' ' * (6 - len(formatted_string))
  36. return formatted_string
  37. class WeixinPublisher(BasePublisher):
  38. """
  39. 微信视频号发布器
  40. 使用 Playwright 自动化操作视频号创作者中心
  41. 注意: 需要使用 Chrome 浏览器,否则可能出现 H264 编码错误
  42. """
  43. platform_name = "weixin"
  44. login_url = "https://channels.weixin.qq.com/platform"
  45. publish_url = "https://channels.weixin.qq.com/platform/post/create"
  46. cookie_domain = ".weixin.qq.com"
  47. def _parse_count(self, count_str: str) -> int:
  48. """解析数字(支持带'万'的格式)"""
  49. try:
  50. count_str = count_str.strip()
  51. if '万' in count_str:
  52. return int(float(count_str.replace('万', '')) * 10000)
  53. return int(count_str)
  54. except:
  55. return 0
  56. async def ai_find_upload_selector(self, frame_html: str, frame_name: str = "main") -> str:
  57. """
  58. 使用 AI 从 HTML 中识别“上传视频/选择文件”相关元素的 CSS 选择器。
  59. 设计思路:
  60. - 仅在常规 DOM 选择器都失败时调用,避免频繁占用 AI 配额;
  61. - 通过 DashScope 文本模型(与验证码识别同一套配置)分析 HTML;
  62. - 返回一个适合用于 frame.locator(selector) 的 CSS 选择器。
  63. """
  64. import json
  65. import re
  66. import requests
  67. import os
  68. # 避免 HTML 过长导致 token 超限,只截取前 N 字符
  69. if not frame_html:
  70. return ""
  71. max_len = 20000
  72. if len(frame_html) > max_len:
  73. frame_html = frame_html[:max_len]
  74. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  75. ai_base_url = os.environ.get("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
  76. ai_text_model = os.environ.get("AI_TEXT_MODEL", "qwen-plus")
  77. if not ai_api_key:
  78. print(f"[{self.platform_name}] AI上传入口识别: 未配置 AI API Key,跳过")
  79. return ""
  80. prompt = f"""
  81. 你是熟悉微信视频号后台的前端工程师,现在需要在一段 HTML 中找到“上传视频文件”的入口。
  82. 页面说明:
  83. - 平台:微信视频号(channels.weixin.qq.com)
  84. - 目标:用于上传视频文件的按钮或 input(一般会触发文件选择框)
  85. - 你会收到某个 frame 的完整 HTML 片段(不包含截图)。
  86. 请你根据下面的 HTML,推断最适合用于上传视频文件的元素,并输出一个可以被 Playwright 使用的 CSS 选择器。
  87. 要求:
  88. 1. 只考虑“上传/选择视频文件”的入口,不要返回“发布/发表/下一步”等按钮;
  89. 2. 选择器需要尽量稳定,不要使用自动生成的随机类名(例如带很多随机字母/数字的类名可以用前缀匹配);
  90. 3. 选择器必须是 CSS 选择器(不要返回 XPath);
  91. 4. 如果确实找不到合理的上传入口,返回 selector 为空字符串。
  92. 请以 JSON 格式输出,严格遵守以下结构(不要添加任何解释文字):
  93. ```json
  94. {{
  95. "selector": "CSS 选择器字符串,比如:input[type='file'] 或 div.upload-content input[type='file']"
  96. }}
  97. ```
  98. 下面是 frame=\"{frame_name}\" 的 HTML:
  99. ```html
  100. {frame_html}
  101. ```"""
  102. payload = {
  103. "model": ai_text_model,
  104. "messages": [
  105. {
  106. "role": "user",
  107. "content": prompt,
  108. }
  109. ],
  110. "max_tokens": 600,
  111. }
  112. headers = {
  113. "Authorization": f"Bearer {ai_api_key}",
  114. "Content-Type": "application/json",
  115. }
  116. try:
  117. print(f"[{self.platform_name}] AI上传入口识别: 正在分析 frame={frame_name} HTML...")
  118. resp = requests.post(
  119. f"{ai_base_url}/chat/completions",
  120. headers=headers,
  121. json=payload,
  122. timeout=40,
  123. )
  124. if resp.status_code != 200:
  125. print(f"[{self.platform_name}] AI上传入口识别: API 返回错误 {resp.status_code}")
  126. return ""
  127. data = resp.json()
  128. content = data.get("choices", [{}])[0].get("message", {}).get("content", "") or ""
  129. # 尝试从 ```json``` 代码块中解析
  130. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", content)
  131. if json_match:
  132. json_str = json_match.group(1)
  133. else:
  134. json_match = re.search(r"\\{[\\s\\S]*\\}", content)
  135. json_str = json_match.group(0) if json_match else "{}"
  136. try:
  137. result = json.loads(json_str)
  138. except Exception:
  139. result = {}
  140. selector = (result.get("selector") or "").strip()
  141. print(f"[{self.platform_name}] AI上传入口识别结果: selector='{selector}'")
  142. return selector
  143. except Exception as e:
  144. print(f"[{self.platform_name}] AI上传入口识别异常: {e}")
  145. return ""
  146. async def ai_pick_selector_from_candidates(self, candidates: list, goal: str, frame_name: str = "main") -> str:
  147. """
  148. 将“候选元素列表(包含 css selector + 文本/属性)”发给 AI,让 AI 直接挑选最符合 goal 的元素。
  149. 适用于:HTML 里看不出上传入口、或页面大量动态渲染时。
  150. """
  151. import json
  152. import re
  153. import requests
  154. import os
  155. if not candidates:
  156. return ""
  157. ai_api_key = os.environ.get("DASHSCOPE_API_KEY", "")
  158. ai_base_url = os.environ.get("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
  159. ai_text_model = os.environ.get("AI_TEXT_MODEL", "qwen-plus")
  160. if not ai_api_key:
  161. print(f"[{self.platform_name}] AI候选选择器: 未配置 AI API Key,跳过")
  162. return ""
  163. # 控制长度,最多取前 120 个候选
  164. candidates = candidates[:120]
  165. prompt = f"""
  166. 你是自动化发布工程师。现在要在微信视频号(channels.weixin.qq.com)发布页面里找到“{goal}”相关的入口元素。
  167. 我会给你一组候选元素,每个候选都包含:
  168. - css: 可直接用于 Playwright 的 CSS 选择器
  169. - tag / type / role / ariaLabel / text / id / className(部分字段可能为空)
  170. 你的任务:
  171. - 从候选中选出最可能用于“{goal}”的元素,返回它的 css 选择器;
  172. - 如果没有任何候选符合,返回空字符串。
  173. 注意:
  174. - 如果 goal 是“上传视频入口”,优先选择 input[type=file] 或看起来会触发选择文件/上传的区域;
  175. - 不要选择“发布/发表/下一步”等按钮(除非 goal 明确是发布按钮)。
  176. 请严格按 JSON 输出(不要解释):
  177. ```json
  178. {{ "selector": "..." }}
  179. ```
  180. 候选列表(frame={frame_name}):
  181. ```json
  182. {json.dumps(candidates, ensure_ascii=False)}
  183. ```"""
  184. payload = {
  185. "model": ai_text_model,
  186. "messages": [{"role": "user", "content": prompt}],
  187. "max_tokens": 400,
  188. }
  189. headers = {
  190. "Authorization": f"Bearer {ai_api_key}",
  191. "Content-Type": "application/json",
  192. }
  193. try:
  194. print(f"[{self.platform_name}] AI候选选择器: 正在分析 frame={frame_name}, goal={goal} ...")
  195. resp = requests.post(
  196. f"{ai_base_url}/chat/completions",
  197. headers=headers,
  198. json=payload,
  199. timeout=40,
  200. )
  201. if resp.status_code != 200:
  202. print(f"[{self.platform_name}] AI候选选择器: API 返回错误 {resp.status_code}")
  203. return ""
  204. data = resp.json()
  205. content = data.get("choices", [{}])[0].get("message", {}).get("content", "") or ""
  206. json_match = re.search(r"```json\\s*([\\s\\S]*?)\\s*```", content)
  207. if json_match:
  208. json_str = json_match.group(1)
  209. else:
  210. json_match = re.search(r"\\{[\\s\\S]*\\}", content)
  211. json_str = json_match.group(0) if json_match else "{}"
  212. try:
  213. result = json.loads(json_str)
  214. except Exception:
  215. result = {}
  216. selector = (result.get("selector") or "").strip()
  217. print(f"[{self.platform_name}] AI候选选择器结果: selector='{selector}'")
  218. return selector
  219. except Exception as e:
  220. print(f"[{self.platform_name}] AI候选选择器异常: {e}")
  221. return ""
  222. async def _extract_relevant_html_snippets(self, html: str) -> str:
  223. """
  224. 从 HTML 中抽取与上传相关的片段,减少 token,提升 AI 命中率。
  225. - 优先抓取包含 upload/上传/file/input 等关键词的窗口片段
  226. - 若未命中关键词,返回“开头 + 结尾”的拼接
  227. """
  228. import re
  229. if not html:
  230. return ""
  231. patterns = [
  232. r"upload",
  233. r"uploader",
  234. r"file",
  235. r"type\\s*=\\s*['\\\"]file['\\\"]",
  236. r"input",
  237. r"drag",
  238. r"drop",
  239. r"选择",
  240. r"上传",
  241. r"添加",
  242. r"视频",
  243. ]
  244. regex = re.compile("|".join(patterns), re.IGNORECASE)
  245. snippets = []
  246. for m in regex.finditer(html):
  247. start = max(0, m.start() - 350)
  248. end = min(len(html), m.end() + 350)
  249. snippets.append(html[start:end])
  250. if len(snippets) >= 18:
  251. break
  252. if snippets:
  253. # 去重(粗略)
  254. unique = []
  255. seen = set()
  256. for s in snippets:
  257. key = hash(s)
  258. if key not in seen:
  259. seen.add(key)
  260. unique.append(s)
  261. return "\n\n<!-- SNIPPET -->\n\n".join(unique)[:20000]
  262. # fallback: head + tail
  263. head = html[:9000]
  264. tail = html[-9000:] if len(html) > 9000 else ""
  265. return (head + "\n\n<!-- TAIL -->\n\n" + tail)[:20000]
  266. async def init_browser(self, storage_state: str = None):
  267. """初始化浏览器 - 参考 matrix 使用 channel=chrome 避免 H264 编码错误"""
  268. from playwright.async_api import async_playwright
  269. playwright = await async_playwright().start()
  270. # 参考 matrix: 使用系统内的 Chrome 浏览器,避免 H264 编码错误
  271. # 如果没有安装 Chrome,则使用默认 Chromium
  272. try:
  273. self.browser = await playwright.chromium.launch(
  274. headless=self.headless,
  275. channel="chrome" # 使用系统 Chrome
  276. )
  277. print(f"[{self.platform_name}] 使用系统 Chrome 浏览器")
  278. except Exception as e:
  279. print(f"[{self.platform_name}] Chrome 不可用,使用 Chromium: {e}")
  280. self.browser = await playwright.chromium.launch(headless=self.headless)
  281. # 设置 HTTP Headers 防止重定向
  282. headers = {
  283. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  284. "Referer": "https://channels.weixin.qq.com/platform/post/list",
  285. }
  286. self.context = await self.browser.new_context(
  287. extra_http_headers=headers,
  288. ignore_https_errors=True,
  289. viewport={"width": 1920, "height": 1080},
  290. user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
  291. )
  292. self.page = await self.context.new_page()
  293. return self.page
  294. async def set_schedule_time(self, publish_date: datetime):
  295. """设置定时发布"""
  296. if not self.page:
  297. return
  298. print(f"[{self.platform_name}] 设置定时发布...")
  299. # 点击定时选项
  300. label_element = self.page.locator("label").filter(has_text="定时").nth(1)
  301. await label_element.click()
  302. # 选择日期
  303. await self.page.click('input[placeholder="请选择发表时间"]')
  304. publish_month = f"{publish_date.month:02d}"
  305. current_month = f"{publish_month}月"
  306. # 检查月份
  307. page_month = await self.page.inner_text('span.weui-desktop-picker__panel__label:has-text("月")')
  308. if page_month != current_month:
  309. await self.page.click('button.weui-desktop-btn__icon__right')
  310. # 选择日期
  311. elements = await self.page.query_selector_all('table.weui-desktop-picker__table a')
  312. for element in elements:
  313. class_name = await element.evaluate('el => el.className')
  314. if 'weui-desktop-picker__disabled' in class_name:
  315. continue
  316. text = await element.inner_text()
  317. if text.strip() == str(publish_date.day):
  318. await element.click()
  319. break
  320. # 输入时间
  321. await self.page.click('input[placeholder="请选择时间"]')
  322. await self.page.keyboard.press("Control+KeyA")
  323. await self.page.keyboard.type(str(publish_date.hour))
  324. # 点击其他地方确认
  325. await self.page.locator("div.input-editor").click()
  326. async def handle_upload_error(self, video_path: str):
  327. """处理上传错误"""
  328. if not self.page:
  329. return
  330. print(f"[{self.platform_name}] 视频出错了,重新上传中...")
  331. await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').click()
  332. await self.page.get_by_role('button', name="删除", exact=True).click()
  333. file_input = self.page.locator('input[type="file"]')
  334. await file_input.set_input_files(video_path)
  335. async def add_title_tags(self, params: PublishParams):
  336. """添加标题和话题"""
  337. if not self.page:
  338. return
  339. await self.page.locator("div.input-editor").click()
  340. await self.page.keyboard.type(params.title)
  341. if params.tags:
  342. await self.page.keyboard.press("Enter")
  343. for tag in params.tags:
  344. await self.page.keyboard.type("#" + tag)
  345. await self.page.keyboard.press("Space")
  346. print(f"[{self.platform_name}] 成功添加标题和 {len(params.tags)} 个话题")
  347. async def add_short_title(self):
  348. """添加短标题"""
  349. if not self.page:
  350. return
  351. try:
  352. short_title_element = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  353. "xpath=following-sibling::div").locator('span input[type="text"]')
  354. if await short_title_element.count():
  355. # 获取已有内容作为短标题
  356. pass
  357. except:
  358. pass
  359. async def upload_cover(self, cover_path: str):
  360. """上传封面图"""
  361. if not self.page or not cover_path or not os.path.exists(cover_path):
  362. return
  363. try:
  364. await asyncio.sleep(2)
  365. preview_btn_info = await self.page.locator(
  366. 'div.finder-tag-wrap.btn:has-text("更换封面")').get_attribute('class')
  367. if "disabled" not in preview_btn_info:
  368. await self.page.locator('div.finder-tag-wrap.btn:has-text("更换封面")').click()
  369. await self.page.locator('div.single-cover-uploader-wrap > div.wrap').hover()
  370. # 删除现有封面
  371. if await self.page.locator(".del-wrap > .svg-icon").count():
  372. await self.page.locator(".del-wrap > .svg-icon").click()
  373. # 上传新封面
  374. preview_div = self.page.locator("div.single-cover-uploader-wrap > div.wrap")
  375. async with self.page.expect_file_chooser() as fc_info:
  376. await preview_div.click()
  377. preview_chooser = await fc_info.value
  378. await preview_chooser.set_files(cover_path)
  379. await asyncio.sleep(2)
  380. await self.page.get_by_role("button", name="确定").click()
  381. await asyncio.sleep(1)
  382. await self.page.get_by_role("button", name="确认").click()
  383. print(f"[{self.platform_name}] 封面上传成功")
  384. except Exception as e:
  385. print(f"[{self.platform_name}] 封面上传失败: {e}")
  386. async def check_captcha(self) -> dict:
  387. """检查页面是否需要验证码"""
  388. if not self.page:
  389. return {'need_captcha': False, 'captcha_type': ''}
  390. try:
  391. # 检查各种验证码
  392. captcha_selectors = [
  393. 'text="请输入验证码"',
  394. 'text="滑动验证"',
  395. '[class*="captcha"]',
  396. '[class*="verify"]',
  397. ]
  398. for selector in captcha_selectors:
  399. try:
  400. if await self.page.locator(selector).count() > 0:
  401. print(f"[{self.platform_name}] 检测到验证码: {selector}")
  402. return {'need_captcha': True, 'captcha_type': 'image'}
  403. except:
  404. pass
  405. # 检查登录弹窗
  406. login_selectors = [
  407. 'text="请登录"',
  408. 'text="扫码登录"',
  409. '[class*="login-dialog"]',
  410. ]
  411. for selector in login_selectors:
  412. try:
  413. if await self.page.locator(selector).count() > 0:
  414. print(f"[{self.platform_name}] 检测到需要登录: {selector}")
  415. return {'need_captcha': True, 'captcha_type': 'login'}
  416. except:
  417. pass
  418. except Exception as e:
  419. print(f"[{self.platform_name}] 验证码检测异常: {e}")
  420. return {'need_captcha': False, 'captcha_type': ''}
  421. async def publish(self, cookies: str, params: PublishParams) -> PublishResult:
  422. """发布视频到视频号"""
  423. print(f"\n{'='*60}")
  424. print(f"[{self.platform_name}] 开始发布视频")
  425. print(f"[{self.platform_name}] 视频路径: {params.video_path}")
  426. print(f"[{self.platform_name}] 标题: {params.title}")
  427. print(f"[{self.platform_name}] Headless: {self.headless}")
  428. print(f"{'='*60}")
  429. self.report_progress(5, "正在初始化浏览器...")
  430. # 初始化浏览器(使用 Chrome)
  431. await self.init_browser()
  432. print(f"[{self.platform_name}] 浏览器初始化完成")
  433. # 解析并设置 cookies
  434. cookie_list = self.parse_cookies(cookies)
  435. print(cookie_list)
  436. print(f"[{self.platform_name}] 解析到 {len(cookie_list)} 个 cookies")
  437. await self.set_cookies(cookie_list)
  438. if not self.page:
  439. raise Exception("Page not initialized")
  440. # 检查视频文件
  441. if not os.path.exists(params.video_path):
  442. raise Exception(f"视频文件不存在: {params.video_path}")
  443. print(f"[{self.platform_name}] 视频文件存在,大小: {os.path.getsize(params.video_path)} bytes")
  444. self.report_progress(10, "正在打开上传页面...")
  445. # 访问上传页面
  446. await self.page.goto(self.publish_url, wait_until="networkidle", timeout=60000)
  447. await asyncio.sleep(3)
  448. # 检查是否跳转到登录页
  449. current_url = self.page.url
  450. print(f"[{self.platform_name}] 当前页面: {current_url}")
  451. if "login" in current_url:
  452. screenshot_base64 = await self.capture_screenshot()
  453. return PublishResult(
  454. success=False,
  455. platform=self.platform_name,
  456. error="Cookie 已过期,需要重新登录",
  457. need_captcha=True,
  458. captcha_type='login',
  459. screenshot_base64=screenshot_base64,
  460. page_url=current_url,
  461. status='need_captcha'
  462. )
  463. # 使用 AI 检查验证码
  464. ai_captcha = await self.ai_check_captcha()
  465. if ai_captcha['has_captcha']:
  466. print(f"[{self.platform_name}] AI检测到验证码: {ai_captcha['captcha_type']}", flush=True)
  467. screenshot_base64 = await self.capture_screenshot()
  468. return PublishResult(
  469. success=False,
  470. platform=self.platform_name,
  471. error=f"检测到{ai_captcha['captcha_type']}验证码,需要使用有头浏览器完成验证",
  472. need_captcha=True,
  473. captcha_type=ai_captcha['captcha_type'],
  474. screenshot_base64=screenshot_base64,
  475. page_url=current_url,
  476. status='need_captcha'
  477. )
  478. # 传统方式检查验证码
  479. captcha_result = await self.check_captcha()
  480. if captcha_result['need_captcha']:
  481. screenshot_base64 = await self.capture_screenshot()
  482. return PublishResult(
  483. success=False,
  484. platform=self.platform_name,
  485. error=f"需要{captcha_result['captcha_type']}验证码,请使用有头浏览器完成验证",
  486. need_captcha=True,
  487. captcha_type=captcha_result['captcha_type'],
  488. screenshot_base64=screenshot_base64,
  489. page_url=current_url,
  490. status='need_captcha'
  491. )
  492. self.report_progress(15, "正在选择视频文件...")
  493. # 上传视频
  494. # 说明:视频号发布页在不同账号/地区/灰度下 DOM 结构差异较大,且上传组件可能在 iframe 中。
  495. # 因此这里按 matrix 的思路“点击触发 file chooser”,同时增加“遍历全部 frame + 精确挑选 video input”的兜底。
  496. upload_success = False
  497. if not self.page:
  498. raise Exception("Page not initialized")
  499. # 等待页面把上传区域渲染出来(避免过早判断)
  500. try:
  501. await self.page.wait_for_selector("div.upload-content, input[type='file'], iframe", timeout=20000)
  502. except Exception:
  503. pass
  504. async def _try_set_files_in_frame(frame, frame_name: str) -> bool:
  505. """在指定 frame 中尝试触发上传"""
  506. nonlocal upload_success
  507. if upload_success:
  508. return True
  509. # 方法0:如果用户通过环境变量显式配置了选择器,优先尝试这个
  510. if WEIXIN_UPLOAD_SELECTOR:
  511. try:
  512. el = frame.locator(WEIXIN_UPLOAD_SELECTOR).first
  513. if await el.count() > 0 and await el.is_visible():
  514. print(f"[{self.platform_name}] [{frame_name}] 使用环境变量 WEIXIN_UPLOAD_SELECTOR: {WEIXIN_UPLOAD_SELECTOR}")
  515. try:
  516. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  517. await el.click()
  518. chooser = await fc_info.value
  519. await chooser.set_files(params.video_path)
  520. upload_success = True
  521. print(f"[{self.platform_name}] [{frame_name}] 通过环境变量选择器上传成功")
  522. return True
  523. except Exception as e:
  524. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器点击失败,尝试直接 set_input_files: {e}")
  525. try:
  526. await el.set_input_files(params.video_path)
  527. upload_success = True
  528. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器 set_input_files 成功")
  529. return True
  530. except Exception as e2:
  531. print(f"[{self.platform_name}] [{frame_name}] 环境变量选择器 set_input_files 仍失败: {e2}")
  532. except Exception as e:
  533. print(f"[{self.platform_name}] [{frame_name}] 使用环境变量选择器定位元素失败: {e}")
  534. # 先尝试点击上传区域触发 chooser(最贴近 matrix)
  535. click_selectors = [
  536. "div.upload-content",
  537. "div[class*='upload-content']",
  538. "div[class*='upload']",
  539. "div.add-wrap",
  540. "[class*='uploader']",
  541. "text=点击上传",
  542. "text=上传视频",
  543. "text=选择视频",
  544. ]
  545. for selector in click_selectors:
  546. try:
  547. el = frame.locator(selector).first
  548. if await el.count() > 0 and await el.is_visible():
  549. print(f"[{self.platform_name}] [{frame_name}] 找到可点击上传区域: {selector}")
  550. try:
  551. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  552. await el.click()
  553. chooser = await fc_info.value
  554. await chooser.set_files(params.video_path)
  555. upload_success = True
  556. print(f"[{self.platform_name}] [{frame_name}] 通过 file chooser 上传成功")
  557. return True
  558. except Exception as e:
  559. print(f"[{self.platform_name}] [{frame_name}] 点击触发 chooser 失败: {e}")
  560. except Exception:
  561. pass
  562. # 再尝试直接设置 input[type=file](iframe/隐藏 input 常见)
  563. try:
  564. inputs = frame.locator("input[type='file']")
  565. cnt = await inputs.count()
  566. if cnt > 0:
  567. best_idx = 0
  568. best_score = -1
  569. for i in range(cnt):
  570. try:
  571. inp = inputs.nth(i)
  572. accept = (await inp.get_attribute("accept")) or ""
  573. multiple = (await inp.get_attribute("multiple")) or ""
  574. score = 0
  575. if "video" in accept:
  576. score += 10
  577. if "mp4" in accept:
  578. score += 3
  579. if multiple:
  580. score += 1
  581. if score > best_score:
  582. best_score = score
  583. best_idx = i
  584. except Exception:
  585. continue
  586. target = inputs.nth(best_idx)
  587. print(f"[{self.platform_name}] [{frame_name}] 尝试对 input[{best_idx}] set_input_files (score={best_score})")
  588. await target.set_input_files(params.video_path)
  589. upload_success = True
  590. print(f"[{self.platform_name}] [{frame_name}] 通过 file input 上传成功")
  591. return True
  592. except Exception as e:
  593. print(f"[{self.platform_name}] [{frame_name}] file input 上传失败: {e}")
  594. # 不直接返回,让后面的 AI 兜底有机会执行
  595. # 方法4: 兜底使用 AI 分析 HTML,猜测上传入口
  596. try:
  597. frame_url = getattr(frame, "url", "")
  598. html_full = await frame.content()
  599. html_for_ai = await self._extract_relevant_html_snippets(html_full)
  600. print(f"[{self.platform_name}] [{frame_name}] frame_url={frame_url}, html_len={len(html_full)}, html_for_ai_len={len(html_for_ai)}")
  601. ai_selector = await self.ai_find_upload_selector(html_for_ai, frame_name=frame_name)
  602. if ai_selector:
  603. try:
  604. el = frame.locator(ai_selector).first
  605. if await el.count() > 0:
  606. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 选择器点击上传入口: {ai_selector}")
  607. try:
  608. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  609. await el.click()
  610. chooser = await fc_info.value
  611. await chooser.set_files(params.video_path)
  612. upload_success = True
  613. print(f"[{self.platform_name}] [{frame_name}] 通过 AI 选择器上传成功")
  614. return True
  615. except Exception as e:
  616. print(f"[{self.platform_name}] [{frame_name}] AI 选择器点击失败,改为直接 set_input_files: {e}")
  617. try:
  618. await el.set_input_files(params.video_path)
  619. upload_success = True
  620. print(f"[{self.platform_name}] [{frame_name}] AI 选择器直接 set_input_files 成功")
  621. return True
  622. except Exception as e2:
  623. print(f"[{self.platform_name}] [{frame_name}] AI 选择器 set_input_files 仍失败: {e2}")
  624. except Exception as e:
  625. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 选择器定位元素失败: {e}")
  626. else:
  627. # 如果 AI 无法从 HTML 推断,退一步:构造候选元素列表交给 AI 选择
  628. try:
  629. candidates = await frame.evaluate("""
  630. () => {
  631. function cssEscape(s) {
  632. try { return CSS.escape(s); } catch (e) { return s.replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
  633. }
  634. function buildSelector(el) {
  635. if (!el || el.nodeType !== 1) return '';
  636. if (el.id) return `#${cssEscape(el.id)}`;
  637. let parts = [];
  638. let cur = el;
  639. for (let depth = 0; cur && cur.nodeType === 1 && depth < 5; depth++) {
  640. let part = cur.tagName.toLowerCase();
  641. const role = cur.getAttribute('role');
  642. const type = cur.getAttribute('type');
  643. if (type) part += `[type="${type}"]`;
  644. if (role) part += `[role="${role}"]`;
  645. const cls = (cur.className || '').toString().trim().split(/\\s+/).filter(Boolean);
  646. if (cls.length) part += '.' + cls.slice(0, 2).map(cssEscape).join('.');
  647. // nth-of-type
  648. let idx = 1;
  649. let sib = cur;
  650. while (sib && (sib = sib.previousElementSibling)) {
  651. if (sib.tagName === cur.tagName) idx++;
  652. }
  653. part += `:nth-of-type(${idx})`;
  654. parts.unshift(part);
  655. cur = cur.parentElement;
  656. }
  657. return parts.join(' > ');
  658. }
  659. const nodes = Array.from(document.querySelectorAll('input, button, a, div, span'))
  660. .filter(el => {
  661. const tag = el.tagName.toLowerCase();
  662. const type = (el.getAttribute('type') || '').toLowerCase();
  663. const role = (el.getAttribute('role') || '').toLowerCase();
  664. const aria = (el.getAttribute('aria-label') || '').toLowerCase();
  665. const txt = (el.innerText || '').trim().slice(0, 60);
  666. const cls = (el.className || '').toString().toLowerCase();
  667. const isFile = tag === 'input' && type === 'file';
  668. const looksClickable =
  669. tag === 'button' || tag === 'a' || role === 'button' || el.onclick ||
  670. cls.includes('upload') || cls.includes('uploader') || cls.includes('drag') ||
  671. aria.includes('上传') || aria.includes('选择') || aria.includes('添加') ||
  672. txt.includes('上传') || txt.includes('选择') || txt.includes('添加') || txt.includes('点击上传');
  673. if (!isFile && !looksClickable) return false;
  674. const r = el.getBoundingClientRect();
  675. const visible = r.width > 5 && r.height > 5;
  676. return visible;
  677. });
  678. const limited = nodes.slice(0, 120).map(el => ({
  679. css: buildSelector(el),
  680. tag: el.tagName.toLowerCase(),
  681. type: el.getAttribute('type') || '',
  682. role: el.getAttribute('role') || '',
  683. ariaLabel: el.getAttribute('aria-label') || '',
  684. text: (el.innerText || '').trim().slice(0, 80),
  685. id: el.id || '',
  686. className: (el.className || '').toString().slice(0, 120),
  687. accept: el.getAttribute('accept') || '',
  688. }));
  689. return limited;
  690. }
  691. """)
  692. ai_selector2 = await self.ai_pick_selector_from_candidates(
  693. candidates=candidates,
  694. goal="上传视频入口",
  695. frame_name=frame_name
  696. )
  697. if ai_selector2:
  698. el2 = frame.locator(ai_selector2).first
  699. if await el2.count() > 0:
  700. print(f"[{self.platform_name}] [{frame_name}] 使用 AI 候选选择器点击上传入口: {ai_selector2}")
  701. try:
  702. async with self.page.expect_file_chooser(timeout=5000) as fc_info:
  703. await el2.click()
  704. chooser2 = await fc_info.value
  705. await chooser2.set_files(params.video_path)
  706. upload_success = True
  707. print(f"[{self.platform_name}] [{frame_name}] 通过 AI 候选选择器上传成功")
  708. return True
  709. except Exception as e:
  710. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器点击失败,尝试 set_input_files: {e}")
  711. try:
  712. await el2.set_input_files(params.video_path)
  713. upload_success = True
  714. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器 set_input_files 成功")
  715. return True
  716. except Exception as e2:
  717. print(f"[{self.platform_name}] [{frame_name}] AI 候选选择器 set_input_files 仍失败: {e2}")
  718. except Exception as e:
  719. print(f"[{self.platform_name}] [{frame_name}] 构造候选并交给 AI 失败: {e}")
  720. except Exception as e:
  721. print(f"[{self.platform_name}] [{frame_name}] AI 上传入口识别整体失败: {e}")
  722. return False
  723. # 先尝试主 frame
  724. try:
  725. await _try_set_files_in_frame(self.page.main_frame, "main")
  726. except Exception as e:
  727. print(f"[{self.platform_name}] main frame 上传尝试异常: {e}")
  728. # 再遍历所有子 frame
  729. if not upload_success:
  730. try:
  731. frames = self.page.frames
  732. print(f"[{self.platform_name}] 发现 frames: {len(frames)}")
  733. for idx, fr in enumerate(frames):
  734. if upload_success:
  735. break
  736. # main_frame 已尝试过
  737. if fr == self.page.main_frame:
  738. continue
  739. name = fr.name or f"frame-{idx}"
  740. await _try_set_files_in_frame(fr, name)
  741. except Exception as e:
  742. print(f"[{self.platform_name}] 遍历 frames 异常: {e}")
  743. if not upload_success:
  744. screenshot_base64 = await self.capture_screenshot()
  745. return PublishResult(
  746. success=False,
  747. platform=self.platform_name,
  748. error="未找到上传入口(可能在 iframe 中或页面结构已变更)",
  749. screenshot_base64=screenshot_base64,
  750. page_url=await self.get_page_url(),
  751. status='failed'
  752. )
  753. self.report_progress(20, "正在填充标题和话题...")
  754. # 添加标题和话题
  755. await self.add_title_tags(params)
  756. self.report_progress(30, "等待视频上传完成...")
  757. # 等待上传完成
  758. for _ in range(120):
  759. try:
  760. button_info = await self.page.get_by_role("button", name="发表").get_attribute('class')
  761. if "weui-desktop-btn_disabled" not in button_info:
  762. print(f"[{self.platform_name}] 视频上传完毕")
  763. # 上传封面
  764. self.report_progress(50, "正在上传封面...")
  765. await self.upload_cover(params.cover_path)
  766. break
  767. else:
  768. # 检查上传错误
  769. if await self.page.locator('div.status-msg.error').count():
  770. if await self.page.locator('div.media-status-content div.tag-inner:has-text("删除")').count():
  771. await self.handle_upload_error(params.video_path)
  772. await asyncio.sleep(3)
  773. except:
  774. await asyncio.sleep(3)
  775. self.report_progress(60, "处理视频设置...")
  776. # 添加短标题
  777. try:
  778. short_title_el = self.page.get_by_text("短标题", exact=True).locator("..").locator(
  779. "xpath=following-sibling::div").locator('span input[type="text"]')
  780. if await short_title_el.count():
  781. short_title = format_short_title(params.title)
  782. await short_title_el.fill(short_title)
  783. except:
  784. pass
  785. # 定时发布
  786. if params.publish_date:
  787. self.report_progress(70, "设置定时发布...")
  788. await self.set_schedule_time(params.publish_date)
  789. self.report_progress(80, "正在发布...")
  790. # 点击发布 - 参考 matrix
  791. for i in range(30):
  792. try:
  793. # 参考 matrix: div.form-btns button:has-text("发表")
  794. publish_btn = self.page.locator('div.form-btns button:has-text("发表")')
  795. if await publish_btn.count():
  796. print(f"[{self.platform_name}] 点击发布按钮...")
  797. await publish_btn.click()
  798. # 等待跳转到作品列表页面 - 参考 matrix
  799. await self.page.wait_for_url(
  800. "https://channels.weixin.qq.com/platform/post/list",
  801. timeout=10000
  802. )
  803. self.report_progress(100, "发布成功")
  804. print(f"[{self.platform_name}] 视频发布成功!")
  805. screenshot_base64 = await self.capture_screenshot()
  806. return PublishResult(
  807. success=True,
  808. platform=self.platform_name,
  809. message="发布成功",
  810. screenshot_base64=screenshot_base64,
  811. page_url=self.page.url,
  812. status='success'
  813. )
  814. except Exception as e:
  815. current_url = self.page.url
  816. if "https://channels.weixin.qq.com/platform/post/list" in current_url:
  817. self.report_progress(100, "发布成功")
  818. print(f"[{self.platform_name}] 视频发布成功!")
  819. screenshot_base64 = await self.capture_screenshot()
  820. return PublishResult(
  821. success=True,
  822. platform=self.platform_name,
  823. message="发布成功",
  824. screenshot_base64=screenshot_base64,
  825. page_url=current_url,
  826. status='success'
  827. )
  828. else:
  829. print(f"[{self.platform_name}] 视频正在发布中... {i+1}/30, URL: {current_url}")
  830. await asyncio.sleep(1)
  831. # 发布超时
  832. screenshot_base64 = await self.capture_screenshot()
  833. page_url = await self.get_page_url()
  834. return PublishResult(
  835. success=False,
  836. platform=self.platform_name,
  837. error="发布超时,请检查发布状态",
  838. screenshot_base64=screenshot_base64,
  839. page_url=page_url,
  840. status='need_action'
  841. )
  842. async def _get_works_fallback_dom(self, page_size: int) -> tuple:
  843. """API 失败时从当前页面 DOM 抓取作品列表(兼容新账号/不同入口)"""
  844. works: List[WorkItem] = []
  845. total = 0
  846. has_more = False
  847. try:
  848. for selector in ["div.post-feed-item", "[class*='post-feed']", "[class*='feed-item']", "div[class*='post']"]:
  849. try:
  850. await self.page.wait_for_selector(selector, timeout=8000)
  851. break
  852. except Exception:
  853. continue
  854. post_items = self.page.locator("div.post-feed-item")
  855. item_count = await post_items.count()
  856. if item_count == 0:
  857. post_items = self.page.locator("[class*='post-feed']")
  858. item_count = await post_items.count()
  859. for i in range(min(item_count, page_size)):
  860. try:
  861. item = post_items.nth(i)
  862. cover_el = item.locator("div.media img.thumb").first
  863. cover_url = await cover_el.get_attribute("src") or "" if await cover_el.count() > 0 else ""
  864. if not cover_url:
  865. cover_el = item.locator("img").first
  866. cover_url = await cover_el.get_attribute("src") or "" if await cover_el.count() > 0 else ""
  867. title_el = item.locator("div.post-title").first
  868. title = (await title_el.text_content() or "").strip() if await title_el.count() > 0 else ""
  869. time_el = item.locator("div.post-time span").first
  870. publish_time = (await time_el.text_content() or "").strip() if await time_el.count() > 0 else ""
  871. play_count = like_count = comment_count = share_count = collect_count = 0
  872. data_items = item.locator("div.post-data div.data-item")
  873. for j in range(await data_items.count()):
  874. data_item = data_items.nth(j)
  875. count_text = (await data_item.locator("span.count").text_content() or "0").strip()
  876. if await data_item.locator("span.weui-icon-outlined-eyes-on").count() > 0:
  877. play_count = self._parse_count(count_text)
  878. elif await data_item.locator("span.weui-icon-outlined-like").count() > 0:
  879. like_count = self._parse_count(count_text)
  880. elif await data_item.locator("span.weui-icon-outlined-comment").count() > 0:
  881. comment_count = self._parse_count(count_text)
  882. elif await data_item.locator("use[xlink\\:href='#icon-share']").count() > 0:
  883. share_count = self._parse_count(count_text)
  884. elif await data_item.locator("use[xlink\\:href='#icon-thumb']").count() > 0:
  885. collect_count = self._parse_count(count_text)
  886. work_id = f"weixin_{i}_{hash(title)}_{hash(publish_time)}"
  887. works.append(WorkItem(
  888. work_id=work_id,
  889. title=title or "无标题",
  890. cover_url=cover_url,
  891. duration=0,
  892. status="published",
  893. publish_time=publish_time,
  894. play_count=play_count,
  895. like_count=like_count,
  896. comment_count=comment_count,
  897. share_count=share_count,
  898. collect_count=collect_count,
  899. ))
  900. except Exception as e:
  901. print(f"[{self.platform_name}] DOM 解析作品 {i} 失败: {e}", flush=True)
  902. continue
  903. total = len(works)
  904. has_more = item_count > page_size
  905. print(f"[{self.platform_name}] DOM 回退获取 {len(works)} 条", flush=True)
  906. except Exception as e:
  907. print(f"[{self.platform_name}] DOM 回退失败: {e}", flush=True)
  908. return (works, total, has_more, "")
  909. async def get_works(self, cookies: str, page: int = 0, page_size: int = 20) -> WorksResult:
  910. """获取视频号作品列表(调用 post_list 接口)
  911. page: 页码从 0 开始,或上一页返回的 rawKeyBuff/lastBuff 字符串
  912. """
  913. # 分页:首页 currentPage=1/rawKeyBuff=null,下一页用 currentPage 递增或 rawKeyBuff
  914. if page is None or page == "" or (isinstance(page, int) and page == 0):
  915. current_page = 1
  916. raw_key_buff = None
  917. elif isinstance(page, int):
  918. current_page = page + 1
  919. raw_key_buff = None
  920. else:
  921. current_page = 1
  922. raw_key_buff = str(page)
  923. ts_ms = str(int(time.time() * 1000))
  924. print(f"\n{'='*60}")
  925. print(f"[{self.platform_name}] 获取作品列表 currentPage={current_page}, pageSize={page_size}, rawKeyBuff={raw_key_buff[:40] if raw_key_buff else 'null'}...")
  926. print(f"{'='*60}")
  927. works: List[WorkItem] = []
  928. total = 0
  929. has_more = False
  930. next_page = ""
  931. try:
  932. await self.init_browser()
  933. cookie_list = self.parse_cookies(cookies)
  934. await self.set_cookies(cookie_list)
  935. if not self.page:
  936. raise Exception("Page not initialized")
  937. await self.page.goto("https://channels.weixin.qq.com/micro/content/post/list", timeout=30000)
  938. await asyncio.sleep(3)
  939. current_url = self.page.url
  940. if "login" in current_url:
  941. raise Exception("Cookie 已过期,请重新登录")
  942. api_url = "https://channels.weixin.qq.com/micro/content/cgi-bin/mmfinderassistant-bin/post/post_list"
  943. req_body = {
  944. "pageSize": page_size,
  945. "currentPage": current_page,
  946. "userpageType": 11,
  947. "stickyOrder": True,
  948. "timestamp": ts_ms,
  949. "_log_finder_uin": "",
  950. "_log_finder_id": "",
  951. "rawKeyBuff": raw_key_buff,
  952. "pluginSessionId": None,
  953. "scene": 7,
  954. "reqScene": 7,
  955. }
  956. body_str = json.dumps(req_body)
  957. response = await self.page.evaluate("""
  958. async ([url, bodyStr]) => {
  959. try {
  960. const resp = await fetch(url, {
  961. method: 'POST',
  962. credentials: 'include',
  963. headers: {
  964. 'Content-Type': 'application/json',
  965. 'Accept': '*/*',
  966. 'Referer': 'https://channels.weixin.qq.com/micro/content/post/list'
  967. },
  968. body: bodyStr
  969. });
  970. return await resp.json();
  971. } catch (e) {
  972. return { error: e.toString() };
  973. }
  974. }
  975. """, [api_url, body_str])
  976. is_first_page = current_page == 1 and raw_key_buff is None
  977. if response.get("error"):
  978. print(f"[{self.platform_name}] API 请求失败: {response.get('error')}", flush=True)
  979. if is_first_page:
  980. works, total, has_more, next_page = await self._get_works_fallback_dom(page_size)
  981. if works:
  982. return WorksResult(success=True, platform=self.platform_name, works=works, total=total, has_more=has_more, next_page=next_page)
  983. return WorksResult(success=False, platform=self.platform_name, error=response.get("error", "API 请求失败"))
  984. err_code = response.get("errCode", -1)
  985. if err_code != 0:
  986. err_msg = response.get("errMsg", "unknown")
  987. print(f"[{self.platform_name}] API errCode={err_code}, errMsg={err_msg}, 完整响应(前800字): {json.dumps(response, ensure_ascii=False)[:800]}", flush=True)
  988. if is_first_page:
  989. works, total, has_more, next_page = await self._get_works_fallback_dom(page_size)
  990. if works:
  991. return WorksResult(success=True, platform=self.platform_name, works=works, total=total, has_more=has_more, next_page=next_page)
  992. return WorksResult(success=False, platform=self.platform_name, error=f"errCode={err_code}, errMsg={err_msg}")
  993. data = response.get("data") or {}
  994. raw_list = data.get("list") or []
  995. total = int(data.get("totalCount") or 0)
  996. has_more = bool(data.get("continueFlag", False))
  997. next_page = (data.get("lastBuff") or "").strip()
  998. print(f"[{self.platform_name}] API 响应: list_len={len(raw_list)}, totalCount={total}, continueFlag={has_more}, lastBuff={next_page[:50] if next_page else ''}...")
  999. if is_first_page and len(raw_list) == 0:
  1000. works_fb, total_fb, has_more_fb, _ = await self._get_works_fallback_dom(page_size)
  1001. if works_fb:
  1002. return WorksResult(success=True, platform=self.platform_name, works=works_fb, total=total_fb, has_more=has_more_fb, next_page="")
  1003. for item in raw_list:
  1004. try:
  1005. work_id = str(item.get("objectId") or item.get("id") or "").strip()
  1006. if not work_id:
  1007. work_id = f"weixin_{hash(item.get('createTime',0))}_{hash(item.get('desc', {}).get('description',''))}"
  1008. desc = item.get("desc") or {}
  1009. title = (desc.get("description") or "").strip() or "无标题"
  1010. cover_url = ""
  1011. duration = 0
  1012. media_list = desc.get("media") or []
  1013. if media_list and isinstance(media_list[0], dict):
  1014. m = media_list[0]
  1015. cover_url = (m.get("coverUrl") or m.get("thumbUrl") or "").strip()
  1016. duration = int(m.get("videoPlayLen") or 0)
  1017. create_ts = item.get("createTime") or 0
  1018. if isinstance(create_ts, (int, float)) and create_ts:
  1019. publish_time = datetime.fromtimestamp(create_ts).strftime("%Y-%m-%d %H:%M:%S")
  1020. else:
  1021. publish_time = str(create_ts) if create_ts else ""
  1022. read_count = int(item.get("readCount") or 0)
  1023. like_count = int(item.get("likeCount") or 0)
  1024. comment_count = int(item.get("commentCount") or 0)
  1025. forward_count = int(item.get("forwardCount") or 0)
  1026. fav_count = int(item.get("favCount") or 0)
  1027. works.append(WorkItem(
  1028. work_id=work_id,
  1029. title=title,
  1030. cover_url=cover_url,
  1031. duration=duration,
  1032. status="published",
  1033. publish_time=publish_time,
  1034. play_count=read_count,
  1035. like_count=like_count,
  1036. comment_count=comment_count,
  1037. share_count=forward_count,
  1038. collect_count=fav_count,
  1039. ))
  1040. except Exception as e:
  1041. print(f"[{self.platform_name}] 解析作品项失败: {e}", flush=True)
  1042. continue
  1043. if total == 0 and works:
  1044. total = len(works)
  1045. print(f"[{self.platform_name}] 本页获取 {len(works)} 条,totalCount={total}, next_page={bool(next_page)}")
  1046. except Exception as e:
  1047. import traceback
  1048. traceback.print_exc()
  1049. return WorksResult(success=False, platform=self.platform_name, error=str(e))
  1050. return WorksResult(success=True, platform=self.platform_name, works=works, total=total, has_more=has_more, next_page=next_page)
  1051. async def get_comments(self, cookies: str, work_id: str, cursor: str = "") -> CommentsResult:
  1052. """获取视频号作品评论"""
  1053. print(f"\n{'='*60}")
  1054. print(f"[{self.platform_name}] 获取作品评论")
  1055. print(f"[{self.platform_name}] work_id={work_id}")
  1056. print(f"{'='*60}")
  1057. comments: List[CommentItem] = []
  1058. total = 0
  1059. has_more = False
  1060. try:
  1061. await self.init_browser()
  1062. cookie_list = self.parse_cookies(cookies)
  1063. await self.set_cookies(cookie_list)
  1064. if not self.page:
  1065. raise Exception("Page not initialized")
  1066. # 访问评论管理页面
  1067. await self.page.goto("https://channels.weixin.qq.com/platform/interaction/comment")
  1068. await asyncio.sleep(3)
  1069. # 检查登录状态
  1070. current_url = self.page.url
  1071. if "login" in current_url:
  1072. raise Exception("Cookie 已过期,请重新登录")
  1073. # 等待左侧作品列表加载
  1074. try:
  1075. await self.page.wait_for_selector('div.comment-feed-wrap', timeout=15000)
  1076. except:
  1077. print(f"[{self.platform_name}] 未找到作品列表")
  1078. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  1079. print(f"[{self.platform_name}] 查找 work_id={work_id} 对应的作品")
  1080. # 点击左侧作品项(根据 work_id 匹配)
  1081. feed_items = self.page.locator('div.comment-feed-wrap')
  1082. item_count = await feed_items.count()
  1083. print(f"[{self.platform_name}] 左侧共 {item_count} 个作品")
  1084. clicked = False
  1085. for i in range(item_count):
  1086. feed = feed_items.nth(i)
  1087. title_el = feed.locator('div.feed-title').first
  1088. if await title_el.count() > 0:
  1089. title_text = await title_el.text_content() or ''
  1090. title_text = title_text.strip()
  1091. # 检查是否包含 work_id(标题)
  1092. if work_id in title_text or title_text in work_id:
  1093. print(f"[{self.platform_name}] 找到匹配作品: {title_text}")
  1094. await feed.click()
  1095. await asyncio.sleep(2)
  1096. clicked = True
  1097. break
  1098. if not clicked:
  1099. # 如果没找到匹配的,点击第一个
  1100. print(f"[{self.platform_name}] 未找到匹配作品,点击第一个")
  1101. if item_count > 0:
  1102. await feed_items.nth(0).click()
  1103. await asyncio.sleep(2)
  1104. else:
  1105. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  1106. # 等待右侧评论详情加载
  1107. try:
  1108. await self.page.wait_for_selector('div.comment-item', timeout=5000)
  1109. except:
  1110. print(f"[{self.platform_name}] 该作品暂无评论")
  1111. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=[], total=0, has_more=False)
  1112. # 获取评论总数
  1113. total_text_el = self.page.locator('div.comment-count__tips')
  1114. if await total_text_el.count() > 0:
  1115. total_text = await total_text_el.text_content() or ''
  1116. # 提取数字(如 "共 1 条评论")
  1117. import re
  1118. match = re.search(r'(\d+)', total_text)
  1119. if match:
  1120. total = int(match.group(1))
  1121. print(f"[{self.platform_name}] 评论总数: {total}")
  1122. # 获取右侧评论列表
  1123. comment_items = self.page.locator('div.comment-item')
  1124. item_count = await comment_items.count()
  1125. print(f"[{self.platform_name}] 当前加载 {item_count} 条评论")
  1126. for i in range(item_count):
  1127. try:
  1128. item = comment_items.nth(i)
  1129. # 获取作者昵称(加 .first 防 strict mode)
  1130. author_name = ''
  1131. name_el = item.locator('span.comment-user-name').first
  1132. if await name_el.count() > 0:
  1133. author_name = await name_el.text_content() or ''
  1134. author_name = author_name.strip()
  1135. # 获取头像
  1136. author_avatar = ''
  1137. avatar_el = item.locator('img.comment-avatar').first
  1138. if await avatar_el.count() > 0:
  1139. author_avatar = await avatar_el.get_attribute('src') or ''
  1140. # 获取评论内容(加 .first 防 strict mode)
  1141. content = ''
  1142. content_el = item.locator('span.comment-content').first
  1143. if await content_el.count() > 0:
  1144. content = await content_el.text_content() or ''
  1145. content = content.strip()
  1146. # 获取评论时间(加 .first 防 strict mode)
  1147. create_time = ''
  1148. time_el = item.locator('span.comment-time').first
  1149. if await time_el.count() > 0:
  1150. create_time = await time_el.text_content() or ''
  1151. create_time = create_time.strip()
  1152. if not content:
  1153. continue
  1154. # 生成评论 ID
  1155. comment_id = f"weixin_comment_{i}_{abs(hash(content))}"
  1156. comments.append(CommentItem(
  1157. comment_id=comment_id,
  1158. work_id=work_id,
  1159. content=content,
  1160. author_id='',
  1161. author_name=author_name,
  1162. author_avatar=author_avatar,
  1163. like_count=0,
  1164. reply_count=0,
  1165. create_time=create_time,
  1166. ))
  1167. print(f"[{self.platform_name}] 评论 {i+1}: {author_name} - {content[:20]}...")
  1168. except Exception as e:
  1169. print(f"[{self.platform_name}] 解析评论 {i} 失败: {e}")
  1170. continue
  1171. print(f"[{self.platform_name}] 成功获取 {len(comments)} 条评论")
  1172. except Exception as e:
  1173. import traceback
  1174. traceback.print_exc()
  1175. return CommentsResult(success=False, platform=self.platform_name, work_id=work_id, error=str(e))
  1176. return CommentsResult(success=True, platform=self.platform_name, work_id=work_id, comments=comments, total=total, has_more=has_more)
  1177. async def auto_reply_private_messages(self, cookies: str) -> dict:
  1178. """自动回复私信 - 集成自 pw3.py"""
  1179. print(f"\n{'='*60}")
  1180. print(f"[{self.platform_name}] 开始自动回复私信")
  1181. print(f"{'='*60}")
  1182. try:
  1183. await self.init_browser()
  1184. cookie_list = self.parse_cookies(cookies)
  1185. await self.set_cookies(cookie_list)
  1186. if not self.page:
  1187. raise Exception("Page not initialized")
  1188. # 访问私信页面
  1189. await self.page.goto("https://channels.weixin.qq.com/platform/private_msg", timeout=30000)
  1190. await asyncio.sleep(3)
  1191. # 检查登录状态
  1192. current_url = self.page.url
  1193. print(f"[{self.platform_name}] 当前 URL: {current_url}")
  1194. if "login" in current_url:
  1195. raise Exception("Cookie 已过期,请重新登录")
  1196. # 等待私信页面加载(使用多个选择器容错)
  1197. try:
  1198. await self.page.wait_for_selector('.private-msg-list-header', timeout=15000)
  1199. except:
  1200. # 尝试其他选择器
  1201. try:
  1202. await self.page.wait_for_selector('.weui-desktop-tab__navs__inner', timeout=10000)
  1203. print(f"[{self.platform_name}] 使用备用选择器加载成功")
  1204. except:
  1205. # 截图调试
  1206. screenshot_path = f"weixin_private_msg_{int(asyncio.get_event_loop().time())}.png"
  1207. await self.page.screenshot(path=screenshot_path)
  1208. print(f"[{self.platform_name}] 页面加载失败,截图: {screenshot_path}")
  1209. raise Exception(f"私信页面加载超时,当前 URL: {current_url}")
  1210. print(f"[{self.platform_name}] 私信页面加载完成")
  1211. # 处理两个 tab
  1212. total_replied = 0
  1213. for tab_name in ["打招呼消息", "私信"]:
  1214. replied_count = await self._process_tab_sessions(tab_name)
  1215. total_replied += replied_count
  1216. print(f"[{self.platform_name}] 自动回复完成,共回复 {total_replied} 条消息")
  1217. return {
  1218. 'success': True,
  1219. 'platform': self.platform_name,
  1220. 'replied_count': total_replied,
  1221. 'message': f'成功回复 {total_replied} 条私信'
  1222. }
  1223. except Exception as e:
  1224. import traceback
  1225. traceback.print_exc()
  1226. return {
  1227. 'success': False,
  1228. 'platform': self.platform_name,
  1229. 'error': str(e)
  1230. }
  1231. async def _process_tab_sessions(self, tab_name: str) -> int:
  1232. """处理指定 tab 下的所有会话"""
  1233. print(f"\n🔄 正在处理「{tab_name}」中的所有会话...")
  1234. if not self.page:
  1235. return 0
  1236. replied_count = 0
  1237. try:
  1238. # 点击 tab
  1239. if tab_name == "私信":
  1240. tab_link = self.page.locator('.weui-desktop-tab__navs__inner li').first.locator('a')
  1241. elif tab_name == "打招呼消息":
  1242. tab_link = self.page.locator('.weui-desktop-tab__navs__inner li').nth(1).locator('a')
  1243. else:
  1244. return 0
  1245. if await tab_link.is_visible():
  1246. await tab_link.click()
  1247. print(f" ➤ 已点击「{tab_name}」tab")
  1248. else:
  1249. print(f" ❌ 「{tab_name}」tab 不可见")
  1250. return 0
  1251. # 等待会话列表加载
  1252. try:
  1253. await self.page.wait_for_function("""
  1254. () => {
  1255. const hasSession = document.querySelectorAll('.session-wrap').length > 0;
  1256. const hasEmpty = !!document.querySelector('.empty-text');
  1257. return hasSession || hasEmpty;
  1258. }
  1259. """, timeout=8000)
  1260. print(" ✅ 会话列表区域已加载")
  1261. except:
  1262. print(" ⚠️ 等待会话列表超时,继续尝试读取...")
  1263. # 获取会话
  1264. session_wraps = self.page.locator('.session-wrap')
  1265. session_count = await session_wraps.count()
  1266. print(f" 💬 共找到 {session_count} 个会话")
  1267. if session_count == 0:
  1268. return 0
  1269. # 遍历每个会话
  1270. for idx in range(session_count):
  1271. try:
  1272. current_sessions = self.page.locator('.session-wrap')
  1273. if idx >= await current_sessions.count():
  1274. break
  1275. session = current_sessions.nth(idx)
  1276. user_name = await session.locator('.name').inner_text()
  1277. last_preview = await session.locator('.feed-info').inner_text()
  1278. print(f"\n ➤ [{idx+1}/{session_count}] 正在处理: {user_name} | 最后消息: {last_preview}")
  1279. await session.click()
  1280. await asyncio.sleep(2)
  1281. # 提取聊天历史
  1282. history = await self._extract_chat_history()
  1283. need_reply = (not history) or (not history[-1]["is_author"])
  1284. if need_reply:
  1285. reply_text = await self._generate_reply_with_ai(history)
  1286. if reply_text=="":
  1287. reply_text = self._generate_reply(history)
  1288. # # 生成回复
  1289. # if history and history[-1]["is_author"]:
  1290. # reply_text = await self._generate_reply_with_ai(history)
  1291. # else:
  1292. # reply_text = self._generate_reply(history)
  1293. if reply_text:
  1294. print(f" 📝 回复内容: {reply_text}")
  1295. try:
  1296. textarea = self.page.locator('.edit_area').first
  1297. send_btn = self.page.locator('button:has-text("发送")').first
  1298. if await textarea.is_visible() and await send_btn.is_visible():
  1299. await textarea.fill(reply_text)
  1300. await asyncio.sleep(0.5)
  1301. await send_btn.click()
  1302. print(" ✅ 已发送")
  1303. replied_count += 1
  1304. await asyncio.sleep(1.5)
  1305. else:
  1306. print(" ❌ 输入框或发送按钮不可见")
  1307. except Exception as e:
  1308. print(f" ❌ 发送失败: {e}")
  1309. else:
  1310. print(" ➤ 无需回复")
  1311. else:
  1312. print(" ➤ 最后一条是我发的,跳过回复")
  1313. except Exception as e:
  1314. print(f" ❌ 处理会话 {idx+1} 时出错: {e}")
  1315. continue
  1316. except Exception as e:
  1317. print(f"❌ 处理「{tab_name}」失败: {e}")
  1318. return replied_count
  1319. async def _extract_chat_history(self) -> list:
  1320. """精准提取聊天记录,区分作者(自己)和用户"""
  1321. if not self.page:
  1322. return []
  1323. history = []
  1324. message_wrappers = self.page.locator('.session-content-wrapper > div:not(.footer) > .text-wrapper')
  1325. count = await message_wrappers.count()
  1326. for i in range(count):
  1327. try:
  1328. wrapper = message_wrappers.nth(i)
  1329. # 判断方向
  1330. is_right = await wrapper.locator('.content-right').count() > 0
  1331. is_left = await wrapper.locator('.content-left').count() > 0
  1332. if not (is_left or is_right):
  1333. continue
  1334. # 提取消息文本
  1335. pre_el = wrapper.locator('pre.message-plain')
  1336. content = ''
  1337. if await pre_el.count() > 0:
  1338. content = await pre_el.inner_text()
  1339. content = content.strip()
  1340. if not content:
  1341. continue
  1342. # 获取头像
  1343. avatar_img = wrapper.locator('.avatar').first
  1344. avatar_src = ''
  1345. if await avatar_img.count() > 0:
  1346. avatar_src = await avatar_img.get_attribute("src") or ''
  1347. # 右侧 = 作者(自己)
  1348. is_author = is_right
  1349. # 获取用户名
  1350. if is_left:
  1351. name_el = wrapper.locator('.profile .name')
  1352. author_name = '用户'
  1353. if await name_el.count() > 0:
  1354. author_name = await name_el.inner_text()
  1355. else:
  1356. author_name = "我"
  1357. history.append({
  1358. "author": author_name,
  1359. "content": content,
  1360. "is_author": is_author,
  1361. "avatar": avatar_src
  1362. })
  1363. except Exception as e:
  1364. print(f" ⚠️ 解析第 {i+1} 条消息失败: {e}")
  1365. continue
  1366. return history
  1367. async def _generate_reply_with_ai(self, chat_history: list) -> str:
  1368. """使用 AI 生成智能回复"""
  1369. import requests
  1370. import json
  1371. try:
  1372. # 获取 AI 配置
  1373. ai_api_key = os.environ.get('DASHSCOPE_API_KEY', '')
  1374. ai_base_url = os.environ.get('DASHSCOPE_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
  1375. ai_model = os.environ.get('AI_MODEL', 'qwen-plus')
  1376. if not ai_api_key:
  1377. print("⚠️ 未配置 AI API Key,使用规则回复")
  1378. return self._generate_reply(chat_history)
  1379. # 构建对话上下文
  1380. messages = [{"role": "system", "content": "你是一个友好的微信视频号创作者助手,负责回复粉丝私信。请保持简洁、友好、专业的语气。回复长度不超过20字。"}]
  1381. for msg in chat_history:
  1382. role = "assistant" if msg["is_author"] else "user"
  1383. messages.append({
  1384. "role": role,
  1385. "content": msg["content"]
  1386. })
  1387. # 调用 AI API
  1388. headers = {
  1389. 'Authorization': f'Bearer {ai_api_key}',
  1390. 'Content-Type': 'application/json'
  1391. }
  1392. payload = {
  1393. "model": ai_model,
  1394. "messages": messages,
  1395. "max_tokens": 150,
  1396. "temperature": 0.8
  1397. }
  1398. print(" 🤖 正在调用 AI 生成回复...")
  1399. response = requests.post(
  1400. f"{ai_base_url}/chat/completions",
  1401. headers=headers,
  1402. json=payload,
  1403. timeout=30
  1404. )
  1405. if response.status_code != 200:
  1406. print(f" ⚠️ AI API 返回错误 {response.status_code},使用规则回复")
  1407. return self._generate_reply(chat_history)
  1408. result = response.json()
  1409. ai_reply = result.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
  1410. if ai_reply:
  1411. print(f" ✅ AI 生成回复: {ai_reply}")
  1412. return ai_reply
  1413. else:
  1414. print(" ⚠️ AI 返回空内容,使用规则回复")
  1415. return self._generate_reply(chat_history)
  1416. except Exception as e:
  1417. print(f" ⚠️ AI 回复生成失败: {e},使用规则回复")
  1418. return self._generate_reply(chat_history)
  1419. def _generate_reply(self, chat_history: list) -> str:
  1420. """根据完整聊天历史生成回复(规则回复方式)"""
  1421. if not chat_history:
  1422. return "你好!感谢联系~"
  1423. # 检查最后一条是否是作者发的
  1424. if chat_history[-1]["is_author"]:
  1425. return "" # 不回复
  1426. # 找最后一条用户消息
  1427. last_user_msg = chat_history[-1]["content"]
  1428. # 简单规则回复
  1429. if "谢谢" in last_user_msg or "感谢" in last_user_msg:
  1430. return "不客气!欢迎常来交流~"
  1431. elif "你好" in last_user_msg or "在吗" in last_user_msg:
  1432. return "你好!请问有什么可以帮您的?"
  1433. elif "视频" in last_user_msg or "怎么拍" in last_user_msg:
  1434. return "视频是用手机拍摄的,注意光线和稳定哦!"
  1435. else:
  1436. return "收到!我会认真阅读您的留言~"