app.py 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 多平台视频发布服务 - 统一入口
  5. 支持平台: 抖音、小红书、视频号、快手
  6. 参考项目: matrix (https://github.com/kebenxiaoming/matrix)
  7. 使用方式:
  8. python app.py # 启动 HTTP 服务 (端口 5005)
  9. python app.py --port 8080 # 指定端口
  10. python app.py --headless false # 显示浏览器窗口
  11. """
  12. import asyncio
  13. import os
  14. import sys
  15. import argparse
  16. # 禁用输出缓冲,确保 print 立即输出
  17. os.environ['PYTHONUNBUFFERED'] = '1'
  18. # 修复 Windows 终端中文输出乱码
  19. if sys.platform == 'win32':
  20. import io
  21. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace', line_buffering=True)
  22. sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace', line_buffering=True)
  23. # 设置环境变量
  24. os.environ['PYTHONIOENCODING'] = 'utf-8'
  25. import traceback
  26. import requests
  27. from datetime import datetime, date
  28. from pathlib import Path
  29. # 确保当前目录在 Python 路径中
  30. CURRENT_DIR = Path(__file__).parent.resolve()
  31. if str(CURRENT_DIR) not in sys.path:
  32. sys.path.insert(0, str(CURRENT_DIR))
  33. # 从 server/.env 文件加载环境变量
  34. def load_env_file():
  35. """从 server/.env 文件加载环境变量"""
  36. env_path = CURRENT_DIR.parent / '.env'
  37. if env_path.exists():
  38. print(f"[Config] Loading env from: {env_path}")
  39. with open(env_path, 'r', encoding='utf-8') as f:
  40. for line in f:
  41. line = line.strip()
  42. if line and not line.startswith('#') and '=' in line:
  43. key, value = line.split('=', 1)
  44. key = key.strip()
  45. value = value.strip()
  46. # 移除引号
  47. if value.startswith('"') and value.endswith('"'):
  48. value = value[1:-1]
  49. elif value.startswith("'") and value.endswith("'"):
  50. value = value[1:-1]
  51. # 只在环境变量未设置时加载
  52. if key not in os.environ:
  53. os.environ[key] = value
  54. print(f"[Config] Loaded: {key}=***" if 'PASSWORD' in key or 'SECRET' in key else f"[Config] Loaded: {key}={value}")
  55. else:
  56. print(f"[Config] .env file not found: {env_path}")
  57. # 加载环境变量
  58. load_env_file()
  59. from flask import Flask, request, jsonify
  60. from flask_cors import CORS
  61. from platforms import get_publisher, PLATFORM_MAP
  62. from platforms.base import PublishParams
  63. from platforms.weixin import WeixinPublisher
  64. def parse_datetime(date_str: str):
  65. """解析日期时间字符串"""
  66. if not date_str:
  67. return None
  68. formats = [
  69. "%Y-%m-%d %H:%M:%S",
  70. "%Y-%m-%d %H:%M",
  71. "%Y/%m/%d %H:%M:%S",
  72. "%Y/%m/%d %H:%M",
  73. "%Y-%m-%dT%H:%M:%S",
  74. "%Y-%m-%dT%H:%M:%SZ",
  75. ]
  76. for fmt in formats:
  77. try:
  78. return datetime.strptime(date_str, fmt)
  79. except ValueError:
  80. continue
  81. return None
  82. def validate_video_file(video_path: str) -> bool:
  83. """验证视频文件是否有效"""
  84. if not video_path:
  85. return False
  86. if not os.path.exists(video_path):
  87. return False
  88. if not os.path.isfile(video_path):
  89. return False
  90. valid_extensions = ['.mp4', '.mov', '.avi', '.mkv', '.flv', '.wmv', '.webm']
  91. ext = os.path.splitext(video_path)[1].lower()
  92. if ext not in valid_extensions:
  93. return False
  94. if os.path.getsize(video_path) < 1024:
  95. return False
  96. return True
  97. # 创建 Flask 应用
  98. app = Flask(__name__)
  99. CORS(app)
  100. # 配置日志以显示所有 HTTP 请求
  101. import logging
  102. logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
  103. # 让 werkzeug 日志显示
  104. werkzeug_logger = logging.getLogger('werkzeug')
  105. werkzeug_logger.setLevel(logging.INFO)
  106. # 添加 StreamHandler 确保输出到控制台
  107. handler = logging.StreamHandler(sys.stdout)
  108. handler.setLevel(logging.DEBUG)
  109. werkzeug_logger.addHandler(handler)
  110. # 添加请求钩子,打印所有收到的请求
  111. @app.before_request
  112. def log_request_info():
  113. """在处理每个请求前打印详细信息"""
  114. print(f"\n{'='*60}", flush=True)
  115. print(f"[HTTP Request] {request.method} {request.path}", flush=True)
  116. print(f"[HTTP Request] From: {request.remote_addr}", flush=True)
  117. if request.content_type and 'json' in request.content_type:
  118. try:
  119. data = request.get_json(silent=True)
  120. if data:
  121. # 打印部分参数,避免太长
  122. keys = list(data.keys()) if data else []
  123. print(f"[HTTP Request] JSON keys: {keys}", flush=True)
  124. except:
  125. pass
  126. print(f"{'='*60}\n", flush=True)
  127. # 全局配置
  128. HEADLESS_MODE = os.environ.get('HEADLESS', 'true').lower() == 'true'
  129. print(f"[Config] HEADLESS env value: '{os.environ.get('HEADLESS', 'NOT SET')}'", flush=True)
  130. print(f"[Config] HEADLESS_MODE: {HEADLESS_MODE}", flush=True)
  131. # Node.js API 配置
  132. NODEJS_API_BASE_URL = os.environ.get('NODEJS_API_URL', 'http://localhost:3000')
  133. INTERNAL_API_KEY = os.environ.get('INTERNAL_API_KEY', 'internal-api-key-default')
  134. print(f"[API Config] Node.js API: {NODEJS_API_BASE_URL}", flush=True)
  135. class NodeApiError(Exception):
  136. """用于把 Node 内部接口的错误状态码/内容透传给调用方。"""
  137. def __init__(self, status_code: int, payload: dict):
  138. super().__init__(payload.get("error") or payload.get("message") or "Node API error")
  139. self.status_code = status_code
  140. self.payload = payload
  141. def call_nodejs_api(method: str, endpoint: str, data: dict = None, params: dict = None) -> dict:
  142. """调用 Node.js 内部 API"""
  143. url = f"{NODEJS_API_BASE_URL}/api/internal{endpoint}"
  144. headers = {
  145. 'Content-Type': 'application/json',
  146. 'X-Internal-API-Key': INTERNAL_API_KEY,
  147. }
  148. try:
  149. if method.upper() == 'GET':
  150. response = requests.get(url, headers=headers, params=params, timeout=30)
  151. elif method.upper() == 'POST':
  152. response = requests.post(url, headers=headers, json=data, timeout=30)
  153. else:
  154. raise ValueError(f"Unsupported HTTP method: {method}")
  155. # 兼容 Node 可能返回非 JSON 的情况
  156. try:
  157. payload = response.json()
  158. except Exception:
  159. payload = {
  160. "success": False,
  161. "error": "Node.js API 返回非 JSON 响应",
  162. "status": response.status_code,
  163. "text": (response.text or "")[:2000],
  164. "url": url,
  165. "endpoint": endpoint,
  166. }
  167. if response.status_code >= 400:
  168. # 把真实状态码/返回体抛出去,由路由决定如何返回给前端
  169. if isinstance(payload, dict):
  170. payload.setdefault("success", False)
  171. payload.setdefault("status", response.status_code)
  172. payload.setdefault("url", url)
  173. payload.setdefault("endpoint", endpoint)
  174. raise NodeApiError(response.status_code, payload if isinstance(payload, dict) else {
  175. "success": False,
  176. "error": "Node.js API 调用失败",
  177. "status": response.status_code,
  178. "data": payload,
  179. "url": url,
  180. "endpoint": endpoint,
  181. })
  182. return payload
  183. except requests.exceptions.RequestException as e:
  184. # 连接失败/超时等(此时通常拿不到 response)
  185. print(f"[API Error] 调用 Node.js API 失败: {e}", flush=True)
  186. raise NodeApiError(502, {
  187. "success": False,
  188. "error": f"无法连接 Node.js API: {str(e)}",
  189. "status": 502,
  190. "url": url,
  191. "endpoint": endpoint,
  192. })
  193. # ==================== 签名相关(小红书专用) ====================
  194. @app.route("/sign", methods=["POST"])
  195. def sign_endpoint():
  196. """小红书签名接口"""
  197. try:
  198. from platforms.xiaohongshu import XiaohongshuPublisher
  199. data = request.json
  200. publisher = XiaohongshuPublisher(headless=True)
  201. result = asyncio.run(publisher.get_sign(
  202. data.get("uri", ""),
  203. data.get("data"),
  204. data.get("a1", ""),
  205. data.get("web_session", "")
  206. ))
  207. return jsonify(result)
  208. except Exception as e:
  209. traceback.print_exc()
  210. return jsonify({"error": str(e)}), 500
  211. # ==================== 统一发布接口 ====================
  212. @app.route("/publish", methods=["POST"])
  213. def publish_video():
  214. """
  215. 统一发布接口
  216. 请求体:
  217. {
  218. "platform": "douyin", # douyin | xiaohongshu | weixin | kuaishou
  219. "cookie": "cookie字符串或JSON",
  220. "title": "视频标题",
  221. "description": "视频描述(可选)",
  222. "video_path": "视频文件绝对路径",
  223. "cover_path": "封面图片绝对路径(可选)",
  224. "tags": ["话题1", "话题2"],
  225. "post_time": "定时发布时间(可选,格式:2024-01-20 12:00:00)",
  226. "location": "位置(可选,默认:重庆市)"
  227. }
  228. 响应:
  229. {
  230. "success": true,
  231. "platform": "douyin",
  232. "video_id": "xxx",
  233. "video_url": "xxx",
  234. "message": "发布成功"
  235. }
  236. """
  237. try:
  238. data = request.json
  239. # 获取参数
  240. platform = data.get("platform", "").lower()
  241. cookie_str = data.get("cookie", "")
  242. title = data.get("title", "")
  243. description = data.get("description", "")
  244. video_path = data.get("video_path", "")
  245. cover_path = data.get("cover_path")
  246. tags = data.get("tags", [])
  247. post_time = data.get("post_time")
  248. location = data.get("location", "重庆市")
  249. # 调试日志
  250. print(f"[Publish] 收到请求: platform={platform}, title={title}, video_path={video_path}")
  251. # 参数验证
  252. if not platform:
  253. print("[Publish] 错误: 缺少 platform 参数")
  254. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  255. if platform not in PLATFORM_MAP:
  256. print(f"[Publish] 错误: 不支持的平台 {platform}")
  257. return jsonify({
  258. "success": False,
  259. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  260. }), 400
  261. if not cookie_str:
  262. print("[Publish] 错误: 缺少 cookie 参数")
  263. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  264. if not title:
  265. print("[Publish] 错误: 缺少 title 参数")
  266. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  267. if not video_path:
  268. print("[Publish] 错误: 缺少 video_path 参数")
  269. return jsonify({"success": False, "error": "缺少 video_path 参数"}), 400
  270. # 视频文件验证(增加详细信息)
  271. if not os.path.exists(video_path):
  272. print(f"[Publish] 错误: 视频文件不存在: {video_path}")
  273. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  274. if not os.path.isfile(video_path):
  275. print(f"[Publish] 错误: 路径不是文件: {video_path}")
  276. return jsonify({"success": False, "error": f"路径不是文件: {video_path}"}), 400
  277. # 解析发布时间
  278. publish_date = parse_datetime(post_time) if post_time else None
  279. # 创建发布参数
  280. params = PublishParams(
  281. title=title,
  282. video_path=video_path,
  283. description=description,
  284. cover_path=cover_path,
  285. tags=tags,
  286. publish_date=publish_date,
  287. location=location
  288. )
  289. print("=" * 60)
  290. print(f"[Publish] 平台: {platform}")
  291. print(f"[Publish] 标题: {title}")
  292. print(f"[Publish] 视频: {video_path}")
  293. print(f"[Publish] 封面: {cover_path}")
  294. print(f"[Publish] 话题: {tags}")
  295. print(f"[Publish] 定时: {publish_date}")
  296. print("=" * 60)
  297. # 获取对应平台的发布器
  298. PublisherClass = get_publisher(platform)
  299. publisher = PublisherClass(headless=HEADLESS_MODE)
  300. # 执行发布
  301. result = asyncio.run(publisher.run(cookie_str, params))
  302. response_data = {
  303. "success": result.success,
  304. "platform": result.platform,
  305. "video_id": result.video_id,
  306. "video_url": result.video_url,
  307. "message": result.message,
  308. "error": result.error,
  309. "need_captcha": result.need_captcha,
  310. "captcha_type": result.captcha_type,
  311. "screenshot_base64": result.screenshot_base64,
  312. "page_url": result.page_url,
  313. "status": result.status
  314. }
  315. # 如果需要验证码,打印明确的日志
  316. if result.need_captcha:
  317. print(f"[Publish] 需要验证码: type={result.captcha_type}")
  318. return jsonify(response_data)
  319. except Exception as e:
  320. traceback.print_exc()
  321. return jsonify({"success": False, "error": str(e)}), 500
  322. # ==================== AI 辅助发布接口 ====================
  323. # 存储活跃的发布会话
  324. active_publish_sessions = {}
  325. @app.route("/publish/ai-assisted", methods=["POST"])
  326. def publish_ai_assisted():
  327. """
  328. AI 辅助发布接口
  329. 与普通发布接口的区别:
  330. 1. 发布过程中会返回截图供 AI 分析
  331. 2. 如果检测到需要验证码,返回截图和状态,等待外部处理
  332. 3. 支持继续发布(输入验证码后)
  333. 请求体:
  334. {
  335. "platform": "douyin",
  336. "cookie": "cookie字符串",
  337. "title": "视频标题",
  338. "video_path": "视频文件路径",
  339. ...
  340. "return_screenshot": true // 是否返回截图
  341. }
  342. 响应:
  343. {
  344. "success": true/false,
  345. "status": "success|failed|need_captcha|processing",
  346. "screenshot_base64": "...", // 当前页面截图
  347. "page_url": "...",
  348. ...
  349. }
  350. """
  351. # 立即打印请求日志,确保能看到
  352. print("\n" + "!" * 60, flush=True)
  353. print("!!! [AI-Assisted Publish] 收到请求 !!!", flush=True)
  354. print("!" * 60 + "\n", flush=True)
  355. try:
  356. data = request.json
  357. print(f"[AI-Assisted Publish] 请求数据: platform={data.get('platform')}, title={data.get('title')}", flush=True)
  358. # 获取参数
  359. platform = data.get("platform", "").lower()
  360. cookie_str = data.get("cookie", "")
  361. title = data.get("title", "")
  362. description = data.get("description", "")
  363. video_path = data.get("video_path", "")
  364. cover_path = data.get("cover_path")
  365. tags = data.get("tags", [])
  366. post_time = data.get("post_time")
  367. location = data.get("location", "重庆市")
  368. return_screenshot = data.get("return_screenshot", True)
  369. # 支持请求级别的 headless 参数,用于验证码场景下的有头浏览器模式
  370. headless = data.get("headless", HEADLESS_MODE)
  371. if isinstance(headless, str):
  372. headless = headless.lower() == 'true'
  373. # 参数验证
  374. if not platform:
  375. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  376. if platform not in PLATFORM_MAP:
  377. return jsonify({"success": False, "error": f"不支持的平台: {platform}"}), 400
  378. if not cookie_str:
  379. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  380. if not title:
  381. return jsonify({"success": False, "error": "缺少 title 参数"}), 400
  382. if not video_path or not os.path.exists(video_path):
  383. return jsonify({"success": False, "error": f"视频文件不存在: {video_path}"}), 400
  384. # 解析发布时间
  385. publish_date = parse_datetime(post_time) if post_time else None
  386. # 创建发布参数
  387. params = PublishParams(
  388. title=title,
  389. video_path=video_path,
  390. description=description,
  391. cover_path=cover_path,
  392. tags=tags,
  393. publish_date=publish_date,
  394. location=location
  395. )
  396. print("=" * 60)
  397. print(f"[AI Publish] 平台: {platform}")
  398. print(f"[AI Publish] 标题: {title}")
  399. print(f"[AI Publish] 视频: {video_path}")
  400. print(f"[AI Publish] Headless: {headless}")
  401. print("=" * 60)
  402. # 获取对应平台的发布器
  403. PublisherClass = get_publisher(platform)
  404. publisher = PublisherClass(headless=headless) # 使用请求参数中的 headless 值
  405. try:
  406. publisher.user_id = int(data.get("user_id")) if data.get("user_id") is not None else None
  407. except Exception:
  408. publisher.user_id = None
  409. try:
  410. publisher.publish_task_id = int(data.get("publish_task_id")) if data.get("publish_task_id") is not None else None
  411. except Exception:
  412. publisher.publish_task_id = None
  413. try:
  414. publisher.publish_account_id = int(data.get("publish_account_id")) if data.get("publish_account_id") is not None else None
  415. except Exception:
  416. publisher.publish_account_id = None
  417. # 执行发布
  418. result = asyncio.run(publisher.run(cookie_str, params))
  419. response_data = {
  420. "success": result.success,
  421. "platform": result.platform,
  422. "video_id": result.video_id,
  423. "video_url": result.video_url,
  424. "message": result.message,
  425. "error": result.error,
  426. "need_captcha": result.need_captcha,
  427. "captcha_type": result.captcha_type,
  428. "status": result.status or ("success" if result.success else "failed"),
  429. "page_url": result.page_url
  430. }
  431. # 如果请求返回截图
  432. if return_screenshot and result.screenshot_base64:
  433. response_data["screenshot_base64"] = result.screenshot_base64
  434. return jsonify(response_data)
  435. except Exception as e:
  436. traceback.print_exc()
  437. return jsonify({"success": False, "error": str(e), "status": "error"}), 500
  438. # ==================== 批量发布接口 ====================
  439. @app.route("/publish/batch", methods=["POST"])
  440. def publish_batch():
  441. """
  442. 批量发布接口 - 发布到多个平台
  443. 请求体:
  444. {
  445. "platforms": ["douyin", "xiaohongshu"],
  446. "cookies": {
  447. "douyin": "cookie字符串",
  448. "xiaohongshu": "cookie字符串"
  449. },
  450. "title": "视频标题",
  451. "video_path": "视频文件绝对路径",
  452. ...
  453. }
  454. """
  455. try:
  456. data = request.json
  457. platforms = data.get("platforms", [])
  458. cookies = data.get("cookies", {})
  459. if not platforms:
  460. return jsonify({"success": False, "error": "缺少 platforms 参数"}), 400
  461. results = []
  462. for platform in platforms:
  463. platform = platform.lower()
  464. cookie_str = cookies.get(platform, "")
  465. if not cookie_str:
  466. results.append({
  467. "platform": platform,
  468. "success": False,
  469. "error": f"缺少 {platform} 的 cookie"
  470. })
  471. continue
  472. try:
  473. # 创建参数
  474. params = PublishParams(
  475. title=data.get("title", ""),
  476. video_path=data.get("video_path", ""),
  477. description=data.get("description", ""),
  478. cover_path=data.get("cover_path"),
  479. tags=data.get("tags", []),
  480. publish_date=parse_datetime(data.get("post_time")),
  481. location=data.get("location", "重庆市")
  482. )
  483. # 发布
  484. PublisherClass = get_publisher(platform)
  485. publisher = PublisherClass(headless=HEADLESS_MODE)
  486. result = asyncio.run(publisher.run(cookie_str, params))
  487. results.append({
  488. "platform": result.platform,
  489. "success": result.success,
  490. "video_id": result.video_id,
  491. "message": result.message,
  492. "error": result.error
  493. })
  494. except Exception as e:
  495. results.append({
  496. "platform": platform,
  497. "success": False,
  498. "error": str(e)
  499. })
  500. # 统计成功/失败数量
  501. success_count = sum(1 for r in results if r.get("success"))
  502. return jsonify({
  503. "success": success_count > 0,
  504. "total": len(platforms),
  505. "success_count": success_count,
  506. "fail_count": len(platforms) - success_count,
  507. "results": results
  508. })
  509. except Exception as e:
  510. traceback.print_exc()
  511. return jsonify({"success": False, "error": str(e)}), 500
  512. # ==================== Cookie 验证接口 ====================
  513. @app.route("/check_cookie", methods=["POST"])
  514. def check_cookie():
  515. """检查 cookie 是否有效"""
  516. try:
  517. data = request.json
  518. platform = data.get("platform", "").lower()
  519. cookie_str = data.get("cookie", "")
  520. if not cookie_str:
  521. return jsonify({"valid": False, "error": "缺少 cookie 参数"}), 400
  522. # 目前只支持小红书的 cookie 验证
  523. if platform == "xiaohongshu":
  524. try:
  525. from platforms.xiaohongshu import XiaohongshuPublisher, XHS_SDK_AVAILABLE
  526. if XHS_SDK_AVAILABLE:
  527. from xhs import XhsClient
  528. publisher = XiaohongshuPublisher()
  529. xhs_client = XhsClient(cookie_str, sign=publisher.sign_sync)
  530. info = xhs_client.get_self_info()
  531. if info:
  532. return jsonify({
  533. "valid": True,
  534. "user_info": {
  535. "user_id": info.get("user_id"),
  536. "nickname": info.get("nickname"),
  537. "avatar": info.get("images")
  538. }
  539. })
  540. except Exception as e:
  541. return jsonify({"valid": False, "error": str(e)})
  542. # 其他平台返回格式正确但未验证
  543. return jsonify({
  544. "valid": True,
  545. "message": "Cookie 格式正确,但未进行在线验证"
  546. })
  547. except Exception as e:
  548. traceback.print_exc()
  549. return jsonify({"valid": False, "error": str(e)})
  550. # ==================== 获取作品列表接口 ====================
  551. @app.route("/works", methods=["POST"])
  552. def get_works():
  553. """
  554. 获取作品列表
  555. 请求体:
  556. {
  557. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  558. "cookie": "cookie字符串或JSON",
  559. "page": 0, # 页码(从0开始,可选,默认0)
  560. "page_size": 20 # 每页数量(可选,默认20)
  561. }
  562. 响应:
  563. {
  564. "success": true,
  565. "platform": "douyin",
  566. "works": [...],
  567. "total": 100,
  568. "has_more": true
  569. }
  570. """
  571. try:
  572. data = request.json
  573. platform = data.get("platform", "").lower()
  574. cookie_str = data.get("cookie", "")
  575. page = data.get("page", 0)
  576. page_size = data.get("page_size", 20)
  577. auto_paging = bool(data.get("auto_paging", False))
  578. print(f"[Works] 收到请求: platform={platform}, page={page}, page_size={page_size}, auto_paging={auto_paging}")
  579. if not platform:
  580. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  581. if platform not in PLATFORM_MAP:
  582. return jsonify({
  583. "success": False,
  584. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  585. }), 400
  586. if not cookie_str:
  587. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  588. # 获取对应平台的发布器
  589. PublisherClass = get_publisher(platform)
  590. publisher = PublisherClass(headless=HEADLESS_MODE)
  591. # 执行获取作品
  592. if platform == "xiaohongshu" and auto_paging and hasattr(publisher, "get_all_works"):
  593. result = asyncio.run(publisher.get_all_works(cookie_str))
  594. else:
  595. result = asyncio.run(publisher.run_get_works(cookie_str, page, page_size))
  596. return jsonify(result.to_dict())
  597. except Exception as e:
  598. traceback.print_exc()
  599. return jsonify({"success": False, "error": str(e)}), 500
  600. # ==================== 保存作品日统计数据接口 ====================
  601. @app.route("/work_day_statistics", methods=["POST"])
  602. def save_work_day_statistics():
  603. """
  604. 保存作品每日统计数据
  605. 当天的数据走更新流,日期变化走新增流
  606. 请求体:
  607. {
  608. "statistics": [
  609. {
  610. "work_id": 1,
  611. "fans_count": 1000,
  612. "play_count": 5000,
  613. "like_count": 200,
  614. "comment_count": 50,
  615. "share_count": 30,
  616. "collect_count": 100
  617. },
  618. ...
  619. ]
  620. }
  621. 响应:
  622. {
  623. "success": true,
  624. "inserted": 5,
  625. "updated": 3,
  626. "message": "保存成功"
  627. }
  628. """
  629. print("=" * 60, flush=True)
  630. print("[DEBUG] ===== 进入 save_work_day_statistics 方法 =====", flush=True)
  631. print(f"[DEBUG] 请求方法: {request.method}", flush=True)
  632. print(f"[DEBUG] 请求数据: {request.json}", flush=True)
  633. print("=" * 60, flush=True)
  634. try:
  635. data = request.json
  636. statistics_list = data.get("statistics", [])
  637. if not statistics_list:
  638. return jsonify({"success": False, "error": "缺少 statistics 参数"}), 400
  639. print(f"[WorkDayStatistics] 收到请求: {len(statistics_list)} 条统计数据")
  640. # 调用 Node.js API 保存数据
  641. result = call_nodejs_api('POST', '/work-day-statistics', {
  642. 'statistics': statistics_list
  643. })
  644. print(f"[WorkDayStatistics] 完成: 新增 {result.get('inserted', 0)} 条, 更新 {result.get('updated', 0)} 条")
  645. return jsonify(result)
  646. except Exception as e:
  647. traceback.print_exc()
  648. return jsonify({"success": False, "error": str(e)}), 500
  649. @app.route("/work_day_statistics/trend", methods=["GET"])
  650. def get_statistics_trend():
  651. """
  652. 获取数据趋势(用于 Dashboard 数据看板 和 数据分析页面)
  653. 查询参数:
  654. user_id: 用户ID (必填)
  655. days: 天数 (可选,默认7天,最大30天) - 与 start_date/end_date 二选一
  656. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  657. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  658. account_id: 账号ID (可选,不填则查询所有账号)
  659. 响应:
  660. {
  661. "success": true,
  662. "data": {
  663. "dates": ["01-16", "01-17", "01-18", ...],
  664. "fans": [100, 120, 130, ...],
  665. "views": [1000, 1200, 1500, ...],
  666. "likes": [50, 60, 70, ...],
  667. "comments": [10, 12, 15, ...],
  668. "shares": [5, 6, 8, ...],
  669. "collects": [20, 25, 30, ...]
  670. }
  671. }
  672. """
  673. try:
  674. user_id = request.args.get("user_id")
  675. days = request.args.get("days")
  676. start_date = request.args.get("start_date")
  677. end_date = request.args.get("end_date")
  678. account_id = request.args.get("account_id")
  679. if not user_id:
  680. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  681. # 调用 Node.js API 获取数据
  682. params = {"user_id": user_id}
  683. if days:
  684. params["days"] = days
  685. if start_date:
  686. params["start_date"] = start_date
  687. if end_date:
  688. params["end_date"] = end_date
  689. if account_id:
  690. params["account_id"] = account_id
  691. result = call_nodejs_api('GET', '/work-day-statistics/trend', params=params)
  692. return jsonify(result)
  693. except Exception as e:
  694. traceback.print_exc()
  695. return jsonify({"success": False, "error": str(e)}), 500
  696. @app.route("/work_day_statistics/platforms", methods=["GET"])
  697. def get_statistics_by_platform():
  698. """
  699. 按平台分组获取统计数据(用于数据分析页面的平台对比)
  700. 数据来源:
  701. - 粉丝数:从 platform_accounts 表获取(账号级别数据)
  702. - 播放量/点赞/评论/收藏:从 work_day_statistics 表按平台汇总
  703. - 粉丝增量:通过比较区间内最早和最新的粉丝数计算
  704. 查询参数:
  705. user_id: 用户ID (必填)
  706. days: 天数 (可选,默认30天,最大30天) - 与 start_date/end_date 二选一
  707. start_date: 开始日期 (可选,格式 YYYY-MM-DD)
  708. end_date: 结束日期 (可选,格式 YYYY-MM-DD)
  709. 响应:
  710. {
  711. "success": true,
  712. "data": [
  713. {
  714. "platform": "douyin",
  715. "fansCount": 1000,
  716. "fansIncrease": 50,
  717. "viewsCount": 5000,
  718. "likesCount": 200,
  719. "commentsCount": 30,
  720. "collectsCount": 100
  721. },
  722. ...
  723. ]
  724. }
  725. """
  726. try:
  727. user_id = request.args.get("user_id")
  728. days = request.args.get("days")
  729. start_date = request.args.get("start_date")
  730. end_date = request.args.get("end_date")
  731. if not user_id:
  732. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  733. # 调用 Node.js API 获取数据
  734. params = {"user_id": user_id}
  735. if days:
  736. params["days"] = days
  737. if start_date:
  738. params["start_date"] = start_date
  739. if end_date:
  740. params["end_date"] = end_date
  741. result = call_nodejs_api('GET', '/work-day-statistics/platforms', params=params)
  742. print(f"[PlatformStats] 返回 {len(result.get('data', []))} 个平台的数据")
  743. return jsonify(result)
  744. except Exception as e:
  745. traceback.print_exc()
  746. return jsonify({"success": False, "error": str(e)}), 500
  747. @app.route("/work_day_statistics/batch", methods=["POST"])
  748. def get_work_statistics_history():
  749. """
  750. 批量获取作品的历史统计数据
  751. 请求体:
  752. {
  753. "work_ids": [1, 2, 3],
  754. "start_date": "2025-01-01", # 可选
  755. "end_date": "2025-01-21" # 可选
  756. }
  757. 响应:
  758. {
  759. "success": true,
  760. "data": {
  761. "1": [
  762. {"record_date": "2025-01-20", "play_count": 100, ...},
  763. {"record_date": "2025-01-21", "play_count": 150, ...}
  764. ],
  765. ...
  766. }
  767. }
  768. """
  769. try:
  770. data = request.json
  771. work_ids = data.get("work_ids", [])
  772. start_date = data.get("start_date")
  773. end_date = data.get("end_date")
  774. if not work_ids:
  775. return jsonify({"success": False, "error": "缺少 work_ids 参数"}), 400
  776. # 调用 Node.js API 获取数据
  777. request_data = {"work_ids": work_ids}
  778. if start_date:
  779. request_data["start_date"] = start_date
  780. if end_date:
  781. request_data["end_date"] = end_date
  782. result = call_nodejs_api('POST', '/work-day-statistics/batch', data=request_data)
  783. return jsonify(result)
  784. except Exception as e:
  785. traceback.print_exc()
  786. return jsonify({"success": False, "error": str(e)}), 500
  787. @app.route("/work_day_statistics/overview", methods=["GET"])
  788. def get_overview():
  789. """
  790. 获取数据总览(账号列表和汇总统计)
  791. 查询参数:
  792. user_id: 用户ID (必填)
  793. 响应:
  794. {
  795. "success": true,
  796. "data": {
  797. "accounts": [
  798. {
  799. "id": 1,
  800. "nickname": "账号名称",
  801. "username": "账号ID",
  802. "avatarUrl": "头像URL",
  803. "platform": "douyin",
  804. "groupId": 1,
  805. "fansCount": 1000,
  806. "totalIncome": null,
  807. "yesterdayIncome": null,
  808. "totalViews": 5000,
  809. "yesterdayViews": 100,
  810. "yesterdayComments": 10,
  811. "yesterdayLikes": 50,
  812. "yesterdayFansIncrease": 5,
  813. "updateTime": "2025-01-26T10:00:00Z",
  814. "status": "active"
  815. },
  816. ...
  817. ],
  818. "summary": {
  819. "totalAccounts": 5,
  820. "totalIncome": 0,
  821. "yesterdayIncome": 0,
  822. "totalViews": 10000,
  823. "yesterdayViews": 200,
  824. "totalFans": 5000,
  825. "yesterdayComments": 20,
  826. "yesterdayLikes": 100,
  827. "yesterdayFansIncrease": 10
  828. }
  829. }
  830. }
  831. """
  832. try:
  833. user_id = request.args.get("user_id")
  834. if not user_id:
  835. return jsonify({"success": False, "error": "缺少 user_id 参数"}), 400
  836. # 调用 Node.js API 获取数据
  837. params = {"user_id": user_id}
  838. result = call_nodejs_api('GET', '/work-day-statistics/overview', params=params)
  839. return jsonify(result)
  840. except NodeApiError as e:
  841. # 透传 Node 的真实状态码/错误内容,避免所有错误都变成 500
  842. return jsonify(e.payload), e.status_code
  843. except Exception as e:
  844. traceback.print_exc()
  845. return jsonify({"success": False, "error": str(e)}), 500
  846. # ==================== 获取评论列表接口 ====================
  847. @app.route("/comments", methods=["POST"])
  848. def get_comments():
  849. """
  850. 获取作品评论
  851. 请求体:
  852. {
  853. "platform": "douyin", # douyin | xiaohongshu | kuaishou
  854. "cookie": "cookie字符串或JSON",
  855. "work_id": "作品ID",
  856. "cursor": "" # 分页游标(可选)
  857. }
  858. 响应:
  859. {
  860. "success": true,
  861. "platform": "douyin",
  862. "work_id": "xxx",
  863. "comments": [...],
  864. "total": 50,
  865. "has_more": true,
  866. "cursor": "xxx"
  867. }
  868. """
  869. try:
  870. data = request.json
  871. platform = data.get("platform", "").lower()
  872. cookie_str = data.get("cookie", "")
  873. work_id = data.get("work_id", "")
  874. cursor = data.get("cursor", "")
  875. print(f"[Comments] 收到请求: platform={platform}, work_id={work_id}")
  876. if not platform:
  877. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  878. if platform not in PLATFORM_MAP:
  879. return jsonify({
  880. "success": False,
  881. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  882. }), 400
  883. if not cookie_str:
  884. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  885. if not work_id:
  886. return jsonify({"success": False, "error": "缺少 work_id 参数"}), 400
  887. # 获取对应平台的发布器
  888. PublisherClass = get_publisher(platform)
  889. publisher = PublisherClass(headless=HEADLESS_MODE)
  890. # 执行获取评论
  891. result = asyncio.run(publisher.run_get_comments(cookie_str, work_id, cursor))
  892. result_dict = result.to_dict()
  893. # 添加 cursor 到响应
  894. if hasattr(result, '__dict__') and 'cursor' in result.__dict__:
  895. result_dict['cursor'] = result.__dict__['cursor']
  896. return jsonify(result_dict)
  897. except Exception as e:
  898. traceback.print_exc()
  899. return jsonify({"success": False, "error": str(e)}), 500
  900. # ==================== 获取所有作品评论接口 ====================
  901. @app.route("/all_comments", methods=["POST"])
  902. def get_all_comments():
  903. """
  904. 获取所有作品的评论(一次性获取)
  905. 请求体:
  906. {
  907. "platform": "douyin", # douyin | xiaohongshu
  908. "cookie": "cookie字符串或JSON"
  909. }
  910. 响应:
  911. {
  912. "success": true,
  913. "platform": "douyin",
  914. "work_comments": [
  915. {
  916. "work_id": "xxx",
  917. "title": "作品标题",
  918. "cover_url": "封面URL",
  919. "comments": [...]
  920. }
  921. ],
  922. "total": 5
  923. }
  924. """
  925. try:
  926. data = request.json
  927. platform = data.get("platform", "").lower()
  928. cookie_str = data.get("cookie", "")
  929. print(f"[AllComments] 收到请求: platform={platform}")
  930. if not platform:
  931. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  932. if platform not in ['douyin', 'xiaohongshu']:
  933. return jsonify({
  934. "success": False,
  935. "error": f"该接口只支持 douyin 和 xiaohongshu 平台"
  936. }), 400
  937. if not cookie_str:
  938. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  939. # 获取对应平台的发布器
  940. PublisherClass = get_publisher(platform)
  941. publisher = PublisherClass(headless=HEADLESS_MODE)
  942. # 执行获取所有评论
  943. result = asyncio.run(publisher.get_all_comments(cookie_str))
  944. return jsonify(result)
  945. except Exception as e:
  946. traceback.print_exc()
  947. return jsonify({"success": False, "error": str(e)}), 500
  948. # ==================== 登录状态检查接口 ====================
  949. @app.route("/check_login", methods=["POST"])
  950. def check_login():
  951. """
  952. 检查 Cookie 登录状态(通过浏览器访问后台页面检测)
  953. 请求体:
  954. {
  955. "platform": "douyin", # douyin | xiaohongshu | kuaishou | weixin
  956. "cookie": "cookie字符串或JSON"
  957. }
  958. 响应:
  959. {
  960. "success": true,
  961. "valid": true, # Cookie 是否有效
  962. "need_login": false, # 是否需要重新登录
  963. "message": "登录状态有效"
  964. }
  965. """
  966. try:
  967. data = request.json
  968. platform = data.get("platform", "").lower()
  969. cookie_str = data.get("cookie", "")
  970. print(f"[CheckLogin] 收到请求: platform={platform}")
  971. if not platform:
  972. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  973. if platform not in PLATFORM_MAP:
  974. return jsonify({
  975. "success": False,
  976. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  977. }), 400
  978. if not cookie_str:
  979. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  980. # 获取对应平台的发布器
  981. PublisherClass = get_publisher(platform)
  982. publisher = PublisherClass(headless=HEADLESS_MODE)
  983. # 执行登录检查
  984. result = asyncio.run(publisher.check_login_status(cookie_str))
  985. return jsonify(result)
  986. except Exception as e:
  987. traceback.print_exc()
  988. return jsonify({
  989. "success": False,
  990. "valid": False,
  991. "need_login": True,
  992. "error": str(e)
  993. }), 500
  994. # ==================== 获取账号信息接口 ====================
  995. @app.route("/account_info", methods=["POST"])
  996. def get_account_info():
  997. """
  998. 获取账号信息
  999. 请求体:
  1000. {
  1001. "platform": "baijiahao", # 平台
  1002. "cookie": "cookie字符串或JSON"
  1003. }
  1004. 响应:
  1005. {
  1006. "success": true,
  1007. "account_id": "xxx",
  1008. "account_name": "用户名",
  1009. "avatar_url": "头像URL",
  1010. "fans_count": 0,
  1011. "works_count": 0
  1012. }
  1013. """
  1014. try:
  1015. data = request.json
  1016. platform = data.get("platform", "").lower()
  1017. cookie_str = data.get("cookie", "")
  1018. print(f"[AccountInfo] 收到请求: platform={platform}")
  1019. if not platform:
  1020. return jsonify({"success": False, "error": "缺少 platform 参数"}), 400
  1021. if platform not in PLATFORM_MAP:
  1022. return jsonify({
  1023. "success": False,
  1024. "error": f"不支持的平台: {platform},支持: {list(PLATFORM_MAP.keys())}"
  1025. }), 400
  1026. if not cookie_str:
  1027. return jsonify({"success": False, "error": "缺少 cookie 参数"}), 400
  1028. # 获取对应平台的发布器
  1029. PublisherClass = get_publisher(platform)
  1030. publisher = PublisherClass(headless=HEADLESS_MODE)
  1031. # 检查是否有 get_account_info 方法
  1032. if hasattr(publisher, 'get_account_info'):
  1033. result = asyncio.run(publisher.get_account_info(cookie_str))
  1034. return jsonify(result)
  1035. else:
  1036. return jsonify({
  1037. "success": False,
  1038. "error": f"平台 {platform} 不支持获取账号信息"
  1039. }), 400
  1040. except Exception as e:
  1041. traceback.print_exc()
  1042. return jsonify({"success": False, "error": str(e)}), 500
  1043. # ==================== 健康检查 ====================
  1044. @app.route("/health", methods=["GET"])
  1045. def health_check():
  1046. """健康检查"""
  1047. # 检查 xhs SDK 是否可用
  1048. xhs_available = False
  1049. try:
  1050. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1051. xhs_available = XHS_SDK_AVAILABLE
  1052. except:
  1053. pass
  1054. return jsonify({
  1055. "status": "ok",
  1056. "xhs_sdk": xhs_available,
  1057. "supported_platforms": list(PLATFORM_MAP.keys()),
  1058. "headless_mode": HEADLESS_MODE
  1059. })
  1060. @app.route("/", methods=["GET"])
  1061. def index():
  1062. """首页"""
  1063. return jsonify({
  1064. "name": "多平台视频发布服务",
  1065. "version": "1.2.0",
  1066. "endpoints": {
  1067. "GET /": "服务信息",
  1068. "GET /health": "健康检查",
  1069. "POST /publish": "发布视频",
  1070. "POST /publish/batch": "批量发布",
  1071. "POST /works": "获取作品列表",
  1072. "POST /comments": "获取作品评论",
  1073. "POST /all_comments": "获取所有作品评论",
  1074. "POST /work_day_statistics": "保存作品每日统计数据",
  1075. "POST /work_day_statistics/batch": "获取作品历史统计数据",
  1076. "POST /check_cookie": "检查 Cookie",
  1077. "POST /sign": "小红书签名"
  1078. },
  1079. "supported_platforms": list(PLATFORM_MAP.keys())
  1080. })
  1081. # ==================== 命令行启动 ====================
  1082. def main():
  1083. parser = argparse.ArgumentParser(description='多平台视频发布服务')
  1084. parser.add_argument('--port', type=int, default=5005, help='服务端口 (默认: 5005)')
  1085. # 从环境变量读取 HOST,默认仅本地访问
  1086. default_host = os.environ.get('PYTHON_HOST', os.environ.get('HOST', '127.0.0.1'))
  1087. parser.add_argument('--host', type=str, default=default_host, help='监听地址 (默认: 127.0.0.1,可通过 HOST 环境变量配置)')
  1088. parser.add_argument('--headless', type=str, default='true', help='是否无头模式 (默认: true)')
  1089. parser.add_argument('--debug', action='store_true', help='调试模式')
  1090. args = parser.parse_args()
  1091. global HEADLESS_MODE
  1092. HEADLESS_MODE = args.headless.lower() == 'true'
  1093. # 检查 xhs SDK
  1094. xhs_status = "未安装"
  1095. try:
  1096. from platforms.xiaohongshu import XHS_SDK_AVAILABLE
  1097. xhs_status = "已安装" if XHS_SDK_AVAILABLE else "未安装"
  1098. except:
  1099. pass
  1100. print("=" * 60)
  1101. print("多平台视频发布服务")
  1102. print("=" * 60)
  1103. print(f"XHS SDK: {xhs_status}")
  1104. print(f"Headless 模式: {HEADLESS_MODE}")
  1105. print(f"支持平台: {', '.join(PLATFORM_MAP.keys())}")
  1106. print("=" * 60)
  1107. print(f"启动服务: http://{args.host}:{args.port}")
  1108. print("=" * 60)
  1109. # 启用 debug 模式以获取详细日志,使用 use_reloader=False 避免重复启动
  1110. app.run(host=args.host, port=args.port, debug=True, threaded=True, use_reloader=False)
  1111. @app.route('/auto-reply', methods=['POST'])
  1112. def auto_reply():
  1113. """
  1114. 微信视频号自动回复私信
  1115. POST /auto-reply
  1116. Body: {
  1117. "platform": "weixin",
  1118. "cookie": "..."
  1119. }
  1120. """
  1121. try:
  1122. data = request.json
  1123. platform = data.get('platform', '').lower()
  1124. cookie = data.get('cookie', '')
  1125. if platform != 'weixin':
  1126. return jsonify({
  1127. 'success': False,
  1128. 'error': '只支持微信视频号平台'
  1129. }), 400
  1130. if not cookie:
  1131. return jsonify({
  1132. 'success': False,
  1133. 'error': '缺少 Cookie'
  1134. }), 400
  1135. print(f"[API] 接收自动回复请求: platform={platform}")
  1136. # 创建 Publisher 实例
  1137. publisher = WeixinPublisher(headless=HEADLESS_MODE)
  1138. # 执行自动回复
  1139. loop = asyncio.new_event_loop()
  1140. asyncio.set_event_loop(loop)
  1141. result = loop.run_until_complete(publisher.auto_reply_private_messages(cookie))
  1142. loop.close()
  1143. print(f"[API] 自动回复结果: {result}")
  1144. return jsonify(result)
  1145. except Exception as e:
  1146. print(f"[API] 自动回复异常: {e}")
  1147. traceback.print_exc()
  1148. return jsonify({
  1149. 'success': False,
  1150. 'error': str(e)
  1151. }), 500
  1152. if __name__ == '__main__':
  1153. main()