cli.py
24.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
"""统一 CLI 入口,对应 Go MCP 工具的 13 个子命令。
全局选项: --host, --port, --account
输出: JSON(ensure_ascii=False)
退出码: 0=成功, 1=未登录, 2=错误
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
# Windows 控制台默认编码(如 cp1252)不支持中文,强制 UTF-8
if sys.stdout and hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if sys.stderr and hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("xhs-cli")
def _output(data: dict, exit_code: int = 0) -> None:
"""输出 JSON 并退出。"""
print(json.dumps(data, ensure_ascii=False, indent=2))
sys.exit(exit_code)
def _connect(args: argparse.Namespace):
"""连接到 Chrome 并返回 (browser, page)。"""
from chrome_launcher import ensure_chrome
from xhs.cdp import Browser
if not ensure_chrome(port=args.port):
_output(
{"success": False, "error": "无法启动 Chrome,请检查 Chrome 是否已安装"},
exit_code=2,
)
browser = Browser(host=args.host, port=args.port)
browser.connect()
page = browser.new_page()
return browser, page
def _connect_existing(args: argparse.Namespace):
"""连接到 Chrome 并复用已有页面(用于分步发布的后续步骤)。"""
from chrome_launcher import ensure_chrome
from xhs.cdp import Browser
if not ensure_chrome(port=args.port):
_output(
{"success": False, "error": "无法连接到 Chrome"},
exit_code=2,
)
browser = Browser(host=args.host, port=args.port)
browser.connect()
page = browser.get_existing_page()
if not page:
_output(
{"success": False, "error": "未找到已打开的页面,请先执行前置步骤"},
exit_code=2,
)
return browser, page
def _headless_fallback(port: int) -> None:
"""Headless 模式未登录时自动降级到有窗口模式。"""
from chrome_launcher import restart_chrome
logger.info("Headless 模式未登录,切换到有窗口模式...")
restart_chrome(port=port, headless=False)
_output(
{
"success": False,
"error": "未登录",
"action": "switched_to_headed",
"message": "已切换到有窗口模式,请在浏览器中扫码登录",
},
exit_code=1,
)
# ========== 子命令实现 ==========
def cmd_check_login(args: argparse.Namespace) -> None:
"""检查登录状态。"""
from xhs.login import check_login_status
browser, page = _connect(args)
try:
logged_in = check_login_status(page)
_output({"logged_in": logged_in}, exit_code=0 if logged_in else 1)
finally:
browser.close_page(page)
browser.close()
def cmd_login(args: argparse.Namespace) -> None:
"""获取登录二维码并等待扫码。"""
from xhs.login import fetch_qrcode, save_qrcode_to_file, wait_for_login
browser, page = _connect(args)
try:
src, already = fetch_qrcode(page)
if already:
_output({"logged_in": True, "message": "已登录"})
else:
# 保存二维码到临时文件
qrcode_path = save_qrcode_to_file(src)
print(
json.dumps(
{
"qrcode_path": qrcode_path,
"message": "请扫码登录,二维码已保存到文件",
},
ensure_ascii=False,
)
)
success = wait_for_login(page, timeout=120)
_output(
{"logged_in": success, "message": "登录成功" if success else "登录超时"},
exit_code=0 if success else 2,
)
finally:
browser.close_page(page)
browser.close()
def cmd_delete_cookies(args: argparse.Namespace) -> None:
"""删除 cookies。"""
from xhs.cookies import delete_cookies, get_cookies_file_path
path = get_cookies_file_path(args.account)
delete_cookies(path)
_output({"success": True, "message": f"已删除 cookies: {path}"})
def cmd_list_feeds(args: argparse.Namespace) -> None:
"""获取首页 Feed 列表。"""
from xhs.feeds import list_feeds
browser, page = _connect(args)
try:
feeds = list_feeds(page)
_output({"feeds": [f.to_dict() for f in feeds], "count": len(feeds)})
finally:
browser.close_page(page)
browser.close()
def cmd_search_feeds(args: argparse.Namespace) -> None:
"""搜索 Feeds。"""
from xhs.search import search_feeds
from xhs.types import FilterOption
filter_opt = FilterOption(
sort_by=args.sort_by or "",
note_type=args.note_type or "",
publish_time=args.publish_time or "",
search_scope=args.search_scope or "",
location=args.location or "",
)
browser, page = _connect(args)
try:
feeds = search_feeds(page, args.keyword, filter_opt)
_output({"feeds": [f.to_dict() for f in feeds], "count": len(feeds)})
finally:
browser.close_page(page)
browser.close()
def cmd_get_feed_detail(args: argparse.Namespace) -> None:
"""获取 Feed 详情。"""
from xhs.feed_detail import get_feed_detail
from xhs.types import CommentLoadConfig
config = CommentLoadConfig(
click_more_replies=args.click_more_replies,
max_replies_threshold=args.max_replies_threshold,
max_comment_items=args.max_comment_items,
scroll_speed=args.scroll_speed,
)
browser, page = _connect(args)
try:
detail = get_feed_detail(
page,
args.feed_id,
args.xsec_token,
load_all_comments=args.load_all_comments,
config=config,
)
_output(detail.to_dict())
finally:
browser.close_page(page)
browser.close()
def cmd_user_profile(args: argparse.Namespace) -> None:
"""获取用户主页。"""
from xhs.user_profile import get_user_profile
browser, page = _connect(args)
try:
profile = get_user_profile(page, args.user_id, args.xsec_token)
_output(profile.to_dict())
finally:
browser.close_page(page)
browser.close()
def cmd_post_comment(args: argparse.Namespace) -> None:
"""发表评论。"""
from xhs.comment import post_comment
browser, page = _connect(args)
try:
post_comment(page, args.feed_id, args.xsec_token, args.content)
_output({"success": True, "message": "评论发送成功"})
finally:
browser.close_page(page)
browser.close()
def cmd_reply_comment(args: argparse.Namespace) -> None:
"""回复评论。"""
from xhs.comment import reply_comment
browser, page = _connect(args)
try:
reply_comment(
page,
args.feed_id,
args.xsec_token,
args.content,
comment_id=args.comment_id or "",
user_id=args.user_id or "",
)
_output({"success": True, "message": "回复成功"})
finally:
browser.close_page(page)
browser.close()
def cmd_like_feed(args: argparse.Namespace) -> None:
"""点赞/取消点赞。"""
from xhs.like_favorite import like_feed, unlike_feed
browser, page = _connect(args)
try:
if args.unlike:
result = unlike_feed(page, args.feed_id, args.xsec_token)
else:
result = like_feed(page, args.feed_id, args.xsec_token)
_output(result.to_dict())
finally:
browser.close_page(page)
browser.close()
def cmd_favorite_feed(args: argparse.Namespace) -> None:
"""收藏/取消收藏。"""
from xhs.like_favorite import favorite_feed, unfavorite_feed
browser, page = _connect(args)
try:
if args.unfavorite:
result = unfavorite_feed(page, args.feed_id, args.xsec_token)
else:
result = favorite_feed(page, args.feed_id, args.xsec_token)
_output(result.to_dict())
finally:
browser.close_page(page)
browser.close()
def cmd_publish(args: argparse.Namespace) -> None:
"""发布图文内容。"""
from image_downloader import process_images
from xhs.login import check_login_status
from xhs.publish import publish_image_content
from xhs.types import PublishImageContent
# 读取标题和正文
with open(args.title_file, encoding="utf-8") as f:
title = f.read().strip()
with open(args.content_file, encoding="utf-8") as f:
content = f.read().strip()
# 处理图片
image_paths = process_images(args.images) if args.images else []
if not image_paths:
_output({"success": False, "error": "没有有效的图片"}, exit_code=2)
browser, page = _connect(args)
try:
# headless 模式登录检查 + 自动降级
headless = getattr(args, "headless", False)
if headless and not check_login_status(page):
browser.close_page(page)
browser.close()
_headless_fallback(args.port)
return
publish_image_content(
page,
PublishImageContent(
title=title,
content=content,
tags=args.tags or [],
image_paths=image_paths,
schedule_time=args.schedule_at,
is_original=args.original,
visibility=args.visibility or "",
),
)
_output({"success": True, "title": title, "images": len(image_paths), "status": "发布完成"})
finally:
browser.close_page(page)
browser.close()
def cmd_fill_publish(args: argparse.Namespace) -> None:
"""只填写图文表单,不发布。"""
from image_downloader import process_images
from xhs.publish import fill_publish_form
from xhs.types import PublishImageContent
with open(args.title_file, encoding="utf-8") as f:
title = f.read().strip()
with open(args.content_file, encoding="utf-8") as f:
content = f.read().strip()
image_paths = process_images(args.images) if args.images else []
if not image_paths:
_output({"success": False, "error": "没有有效的图片"}, exit_code=2)
browser, page = _connect(args)
try:
fill_publish_form(
page,
PublishImageContent(
title=title,
content=content,
tags=args.tags or [],
image_paths=image_paths,
schedule_time=args.schedule_at,
is_original=args.original,
visibility=args.visibility or "",
),
)
_output(
{
"success": True,
"title": title,
"images": len(image_paths),
"status": "表单已填写,等待确认发布",
}
)
finally:
# 不关闭页面,让用户在浏览器中预览
browser.close()
def cmd_fill_publish_video(args: argparse.Namespace) -> None:
"""只填写视频表单,不发布。"""
from xhs.publish_video import fill_publish_video_form
from xhs.types import PublishVideoContent
with open(args.title_file, encoding="utf-8") as f:
title = f.read().strip()
with open(args.content_file, encoding="utf-8") as f:
content = f.read().strip()
browser, page = _connect(args)
try:
fill_publish_video_form(
page,
PublishVideoContent(
title=title,
content=content,
tags=args.tags or [],
video_path=args.video,
schedule_time=args.schedule_at,
visibility=args.visibility or "",
),
)
_output(
{
"success": True,
"title": title,
"video": args.video,
"status": "视频表单已填写,等待确认发布",
}
)
finally:
# 不关闭页面,让用户在浏览器中预览
browser.close()
def cmd_click_publish(args: argparse.Namespace) -> None:
"""点击发布按钮(在用户确认后调用)。复用已有的发布页 tab。"""
from xhs.publish import click_publish_button
browser, page = _connect_existing(args)
try:
click_publish_button(page)
_output({"success": True, "status": "发布完成"})
finally:
browser.close_page(page)
browser.close()
def cmd_long_article(args: argparse.Namespace) -> None:
"""长文模式:填写内容 + 一键排版,返回模板列表。"""
from xhs.publish_long_article import publish_long_article
with open(args.title_file, encoding="utf-8") as f:
title = f.read().strip()
with open(args.content_file, encoding="utf-8") as f:
content = f.read().strip()
browser, page = _connect(args)
try:
template_names = publish_long_article(
page,
title=title,
content=content,
image_paths=args.images,
)
_output(
{
"success": True,
"templates": template_names,
"status": "长文已填写,请选择模板",
}
)
finally:
# 不关闭页面,后续 select-template / next-step 需要复用
browser.close()
def cmd_select_template(args: argparse.Namespace) -> None:
"""选择排版模板。复用已有的长文编辑页 tab。"""
from xhs.publish_long_article import select_template
browser, page = _connect_existing(args)
try:
selected = select_template(page, args.name)
if selected:
_output({"success": True, "template": args.name, "status": "模板已选择"})
else:
_output(
{"success": False, "error": f"未找到模板: {args.name}"},
exit_code=2,
)
finally:
# 不关闭页面,后续 next-step 需要复用
browser.close()
def cmd_next_step(args: argparse.Namespace) -> None:
"""点击下一步 + 填写发布页描述。复用已有的长文编辑页 tab。"""
from xhs.publish_long_article import click_next_and_fill_description
with open(args.content_file, encoding="utf-8") as f:
description = f.read().strip()
browser, page = _connect_existing(args)
try:
click_next_and_fill_description(page, description)
_output({"success": True, "status": "已进入发布页,等待确认发布"})
finally:
# 不关闭页面,等待 click-publish
browser.close()
def cmd_publish_video(args: argparse.Namespace) -> None:
"""发布视频内容。"""
from xhs.login import check_login_status
from xhs.publish_video import publish_video_content
from xhs.types import PublishVideoContent
with open(args.title_file, encoding="utf-8") as f:
title = f.read().strip()
with open(args.content_file, encoding="utf-8") as f:
content = f.read().strip()
browser, page = _connect(args)
try:
# headless 模式登录检查 + 自动降级
headless = getattr(args, "headless", False)
if headless and not check_login_status(page):
browser.close_page(page)
browser.close()
_headless_fallback(args.port)
return
publish_video_content(
page,
PublishVideoContent(
title=title,
content=content,
tags=args.tags or [],
video_path=args.video,
schedule_time=args.schedule_at,
visibility=args.visibility or "",
),
)
_output({"success": True, "title": title, "video": args.video, "status": "发布完成"})
finally:
browser.close_page(page)
browser.close()
# ========== 参数解析 ==========
def build_parser() -> argparse.ArgumentParser:
"""构建 CLI 参数解析器。"""
parser = argparse.ArgumentParser(
prog="xhs-cli",
description="小红书自动化 CLI",
)
# 全局选项
parser.add_argument("--host", default="127.0.0.1", help="Chrome 调试主机 (default: 127.0.0.1)")
parser.add_argument("--port", type=int, default=9222, help="Chrome 调试端口 (default: 9222)")
parser.add_argument("--account", default="", help="账号名称")
subparsers = parser.add_subparsers(dest="command", required=True)
# check-login
sub = subparsers.add_parser("check-login", help="检查登录状态")
sub.set_defaults(func=cmd_check_login)
# login
sub = subparsers.add_parser("login", help="登录(扫码)")
sub.set_defaults(func=cmd_login)
# delete-cookies
sub = subparsers.add_parser("delete-cookies", help="删除 cookies")
sub.set_defaults(func=cmd_delete_cookies)
# list-feeds
sub = subparsers.add_parser("list-feeds", help="获取首页 Feed 列表")
sub.set_defaults(func=cmd_list_feeds)
# search-feeds
sub = subparsers.add_parser("search-feeds", help="搜索 Feeds")
sub.add_argument("--keyword", required=True, help="搜索关键词")
sub.add_argument("--sort-by", help="排序: 综合|最新|最多点赞|最多评论|最多收藏")
sub.add_argument("--note-type", help="类型: 不限|视频|图文")
sub.add_argument("--publish-time", help="时间: 不限|一天内|一周内|半年内")
sub.add_argument("--search-scope", help="范围: 不限|已看过|未看过|已关注")
sub.add_argument("--location", help="位置: 不限|同城|附近")
sub.set_defaults(func=cmd_search_feeds)
# get-feed-detail
sub = subparsers.add_parser("get-feed-detail", help="获取 Feed 详情")
sub.add_argument("--feed-id", required=True, help="Feed ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.add_argument("--load-all-comments", action="store_true", help="加载全部评论")
sub.add_argument("--click-more-replies", action="store_true", help="点击展开更多回复")
sub.add_argument("--max-replies-threshold", type=int, default=10, help="展开回复数阈值")
sub.add_argument("--max-comment-items", type=int, default=0, help="最大评论数 (0=不限)")
sub.add_argument("--scroll-speed", default="normal", help="滚动速度: slow|normal|fast")
sub.set_defaults(func=cmd_get_feed_detail)
# user-profile
sub = subparsers.add_parser("user-profile", help="获取用户主页")
sub.add_argument("--user-id", required=True, help="用户 ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.set_defaults(func=cmd_user_profile)
# post-comment
sub = subparsers.add_parser("post-comment", help="发表评论")
sub.add_argument("--feed-id", required=True, help="Feed ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.add_argument("--content", required=True, help="评论内容")
sub.set_defaults(func=cmd_post_comment)
# reply-comment
sub = subparsers.add_parser("reply-comment", help="回复评论")
sub.add_argument("--feed-id", required=True, help="Feed ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.add_argument("--content", required=True, help="回复内容")
sub.add_argument("--comment-id", help="目标评论 ID")
sub.add_argument("--user-id", help="目标用户 ID")
sub.set_defaults(func=cmd_reply_comment)
# like-feed
sub = subparsers.add_parser("like-feed", help="点赞")
sub.add_argument("--feed-id", required=True, help="Feed ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.add_argument("--unlike", action="store_true", help="取消点赞")
sub.set_defaults(func=cmd_like_feed)
# favorite-feed
sub = subparsers.add_parser("favorite-feed", help="收藏")
sub.add_argument("--feed-id", required=True, help="Feed ID")
sub.add_argument("--xsec-token", required=True, help="xsec_token")
sub.add_argument("--unfavorite", action="store_true", help="取消收藏")
sub.set_defaults(func=cmd_favorite_feed)
# publish
sub = subparsers.add_parser("publish", help="发布图文")
sub.add_argument("--title-file", required=True, help="标题文件路径")
sub.add_argument("--content-file", required=True, help="正文文件路径")
sub.add_argument("--images", nargs="+", required=True, help="图片路径/URL")
sub.add_argument("--tags", nargs="*", help="标签")
sub.add_argument("--schedule-at", help="定时发布 (ISO8601)")
sub.add_argument("--original", action="store_true", help="声明原创")
sub.add_argument("--visibility", help="可见范围")
sub.add_argument("--headless", action="store_true", help="无头模式(未登录自动降级)")
sub.set_defaults(func=cmd_publish)
# publish-video
sub = subparsers.add_parser("publish-video", help="发布视频")
sub.add_argument("--title-file", required=True, help="标题文件路径")
sub.add_argument("--content-file", required=True, help="正文文件路径")
sub.add_argument("--video", required=True, help="视频文件路径")
sub.add_argument("--tags", nargs="*", help="标签")
sub.add_argument("--schedule-at", help="定时发布 (ISO8601)")
sub.add_argument("--visibility", help="可见范围")
sub.add_argument("--headless", action="store_true", help="无头模式(未登录自动降级)")
sub.set_defaults(func=cmd_publish_video)
# fill-publish(只填写图文表单,不发布)
sub = subparsers.add_parser("fill-publish", help="填写图文表单(不发布)")
sub.add_argument("--title-file", required=True, help="标题文件路径")
sub.add_argument("--content-file", required=True, help="正文文件路径")
sub.add_argument("--images", nargs="+", required=True, help="图片路径/URL")
sub.add_argument("--tags", nargs="*", help="标签")
sub.add_argument("--schedule-at", help="定时发布 (ISO8601)")
sub.add_argument("--original", action="store_true", help="声明原创")
sub.add_argument("--visibility", help="可见范围")
sub.set_defaults(func=cmd_fill_publish)
# fill-publish-video(只填写视频表单,不发布)
sub = subparsers.add_parser("fill-publish-video", help="填写视频表单(不发布)")
sub.add_argument("--title-file", required=True, help="标题文件路径")
sub.add_argument("--content-file", required=True, help="正文文件路径")
sub.add_argument("--video", required=True, help="视频文件路径")
sub.add_argument("--tags", nargs="*", help="标签")
sub.add_argument("--schedule-at", help="定时发布 (ISO8601)")
sub.add_argument("--visibility", help="可见范围")
sub.set_defaults(func=cmd_fill_publish_video)
# click-publish(点击发布按钮)
sub = subparsers.add_parser("click-publish", help="点击发布按钮")
sub.set_defaults(func=cmd_click_publish)
# long-article(长文模式)
sub = subparsers.add_parser("long-article", help="长文模式:填写 + 一键排版")
sub.add_argument("--title-file", required=True, help="标题文件路径")
sub.add_argument("--content-file", required=True, help="正文文件路径")
sub.add_argument("--images", nargs="*", help="可选图片路径")
sub.set_defaults(func=cmd_long_article)
# select-template(选择模板)
sub = subparsers.add_parser("select-template", help="选择排版模板")
sub.add_argument("--name", required=True, help="模板名称")
sub.set_defaults(func=cmd_select_template)
# next-step(下一步 + 填写描述)
sub = subparsers.add_parser("next-step", help="点击下一步 + 填写描述")
sub.add_argument("--content-file", required=True, help="描述内容文件路径")
sub.set_defaults(func=cmd_next_step)
return parser
def main() -> None:
"""CLI 入口。"""
parser = build_parser()
args = parser.parse_args()
try:
args.func(args)
except Exception as e:
logger.error("执行失败: %s", e, exc_info=True)
_output({"success": False, "error": str(e)}, exit_code=2)
if __name__ == "__main__":
main()