Skip to content
Back to search

redbook

小红书 CLI — 搜索、分析、自动化 Xiaohongshu content. Built for AI agents.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/lucasygu--redbook/badge.svg)](/listings/lucasygu--redbook)

HTML

<a href="/listings/lucasygu--redbook"><img src="/api/listings/lucasygu--redbook/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

npm install -g @lucasygu/redbook
# 或通过 ClawHub(OpenClaw 生态)
clawhub install redbook

需要 Node.js >= 22。支持 **macOS、Windows、Linux**。使用 Chrome 浏览器的 Cookie —— 请先在 Chrome 中登录 xiaohongshu.com。

安装后运行 `redbook whoami` 验证连接。CLI 会自动检测所有 Chrome 配置文件,找到你的小红书登录状态。

- **macOS** —— 如果遇到钥匙串弹窗,请点击"始终允许" - **Windows** —— Chrome 127+ 使用了 App-Bound Encryption,CLI 会自动启动 Chrome headless 模式读取 Cookie(需要先关闭 Chrome)。如果自动提取失败,可以用 `--cookie-string` 手动传入

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

SKILL.md · Manifest · 1,255 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. ---
  2. description: Search, read, analyze, and automate Xiaohongshu (小红书) content via CLI
  3. allowed-tools: Bash, Read, Write, Glob, Grep
  4. # OpenClaw / ClawHub metadata (clawhub install redbook)
  5. name: redbook
  6. version: 0.5.0
  7. metadata:
  8. openclaw:
  9. requires:
  10. bins:
  11. - redbook
  12. install:
  13. - kind: node
  14. package: "@lucasygu/redbook"
  15. bins: [redbook]
  16. os: [macos]
  17. homepage: https://github.com/lucasygu/redbook
  18. tags:
  19. - xiaohongshu
  20. - social-media
  21. - analytics
  22. - content-ops
  23. ---
  24. # Redbook — Xiaohongshu CLI
  25. Use the `redbook` CLI to search notes, read content, analyze creators, automate engagement, and research topics on Xiaohongshu (小红书/RED).
  26. **OpenClaw users:** Install via `clawhub install redbook` or `npm install -g @lucasygu/redbook`.
  27. > **⚠️ Research discipline (read this first).** XHS 风控 throttles *reading*, not just writing. Any research that reads more than a handful of notes MUST run through the **[Research Loop](#research-loop--rate-limit-safe-long-running-research)** — **human-paced by default** (~20 s/note, one at a time; a typical job finishes in tens of minutes, large ones spread across the day). Hammering `read` / `comments` / `analyze-viral` in a tight loop trips captcha / IP block (300012) within a few dozen hits and degrades the account for hours. ⚡ Fast mode is **emergency-only** and requires a printed warning + explicit user opt-in. Never fire reads in parallel or with zero delay.
  28. ## Usage
  29. ```
  30. /redbook search "AI编程" # Search notes
  31. /redbook read <url> # Read a note
  32. /redbook user <profileUrl> # Creator profile
  33. /redbook account-report --file ids.txt --json # Batch account metrics
  34. /redbook analyze <userId> # Full creator analysis (profile + posts)
  35. ```
  36. ## Quick Reference
  37. | Intent | Command |
  38. |--------|---------|
  39. | Search notes | `redbook search "keyword" --json` |
  40. | Read a note | `redbook read <url> --json` |
  41. | Get comments | `redbook comments <url> --json --all` |
  42. | Creator profile | `redbook user <userId-or-profileUrl> --json` |
  43. | Creator's posts | `redbook user-posts <userId-or-profileUrl> --json` |
  44. | Batch account report | `redbook account-report --file accounts.txt --month YYYY-MM --json` |
  45. | Browse feed | `redbook feed --json` |
  46. | Search hashtags | `redbook topics "keyword" --json` |
  47. | Analyze viral note | `redbook analyze-viral <url> --json` |
  48. | Extract content template | `redbook viral-template <url1> <url2> --json` |
  49. | Post a comment | `redbook comment <url> --content "text"` |
  50. | Reply to comment | `redbook reply <url> --comment-id <id> --content "text"` |
  51. | Batch reply (preview) | `redbook batch-reply <url> --strategy questions --dry-run` |
  52. | Like a note | `redbook like <url>` |
  53. | Unlike a note | `redbook like <url> --undo` |
  54. | List favorites | `redbook favorites --json` or `redbook favorites <userId> --json` |
  55. | Collect a note | `redbook collect <url>` |
  56. | Remove from collection | `redbook uncollect <url>` |
  57. | List followers | `redbook followers <userId> --json` |
  58. | List following | `redbook following <userId> --json` |
  59. | Delete own note | `redbook delete <url>` |
  60. | Check note health | `redbook health --json` or `redbook health --all --json` |
  61. | List user boards | `redbook boards` or `redbook boards <userId> --json` |
  62. | List album notes | `redbook board <board-url>` or `redbook board <boardId> --json` |
  63. | Render markdown to cards | `redbook render content.md --style xiaohongshu` |
  64. | Publish image note | `redbook post --title "..." --body "..." --images img.jpg` |
  65. | Check connection | `redbook whoami` |
  66. | Save cookies for cloud/OpenClaw | `redbook auth export` or `redbook auth save --cookie-string "a1=...; web_session=..."` |
  67. **Always add `--json`** when parsing output programmatically. Without it, output is human-formatted text.
  68. ---
  69. ## XHS Platform Signals
  70. XHS is not Twitter or Instagram. These platform-specific engagement ratios reveal content type and audience behavior.
  71. ### Collect/Like Ratio (`collected_count / liked_count`)
  72. XHS's "collect" (收藏) is a save-for-later mechanic — users build personal reference libraries. This ratio is the strongest signal of content utility.
  73. | Ratio | Classification | Meaning |
  74. |-------|---------------|---------|
  75. | >40% | 工具型 (Reference) | Tutorial, checklist, template — users bookmark for reuse |
  76. | 20–40% | 认知型 (Insight) | Thought-provoking but not saved for later |
  77. | <20% | 娱乐型 (Entertainment) | Consumed and forgotten — engagement is passive |
  78. ### Comment/Like Ratio (`comment_count / liked_count`)
  79. Measures how much a note triggers conversation.
  80. | Ratio | Classification | Meaning |
  81. |-------|---------------|---------|
  82. | >15% | 讨论型 (Discussion) | Debate, sharing experiences, asking questions |
  83. | 5–15% | 正常互动 (Normal) | Typical engagement pattern |
  84. | <5% | 围观型 (Passive) | Users like but don't engage further |
  85. ### Share/Like Ratio (`share_count / liked_count`)
  86. Measures social currency — whether users share to signal identity or help others.
  87. | Ratio | Meaning |
  88. |-------|---------|
  89. | >10% | 社交货币 — people share to signal taste, identity, or help friends |
  90. | <10% | Content consumed individually, not forwarded |
  91. ### Search Sort Semantics
  92. | Sort | What It Reveals |
  93. |------|----------------|
  94. | `--sort popular` | Proven ceiling — the best a keyword can do |
  95. | `--sort latest` | Content velocity — how much is being posted now |
  96. | `--sort general` | Algorithm-weighted blend (default) |
  97. ### Content Form Dynamics
  98. | Form | Tendency |
  99. |------|----------|
  100. | 图文 (image-text, `type: "normal"`) | Higher collect rate — users save reference content |
  101. | 视频 (video, `type: "video"`) | Higher like rate — easier to consume passively |
  102. ---
  103. ## Analysis Modules
  104. Each module is a composable building block. Combine them for different analysis depths.
  105. ### Module A: Keyword Engagement Matrix
  106. **Answers:** Which keywords have the highest engagement ceiling? Which are saturated vs. underserved?
  107. **Commands:**
  108. ```bash
  109. redbook search "keyword1" --sort popular --json
  110. redbook search "keyword2" --sort popular --json
  111. # Repeat for each keyword in your list
  112. ```
  113. **Fields to extract** from each result's `items[]`:
  114. - `items[].note_card.interact_info.liked_count` — likes (may use Chinese numbers: "1.5万" = 15,000)
  115. - `items[].note_card.interact_info.collected_count` — collects
  116. - `items[].note_card.interact_info.comment_count` — comments
  117. - `items[].note_card.user.nickname` — author
  118. **How to interpret:**
  119. - **Top1 ceiling** = `items[0]` likes — the best-performing note for this keyword. This is the proven demand signal.
  120. - **Top10 average** = mean likes across `items[0..9]` — how well an average top note does.
  121. - A high Top1 but low Top10 avg means one outlier dominates; hard to compete.
  122. - A high Top10 avg means consistent demand; easier to break in.
  123. **Output:** Keyword × engagement table ranked by Top1 ceiling.
  124. | Keyword | Top1 Likes | Top10 Avg | Top1 Collects | Collect/Like |
  125. |---------|-----------|-----------|---------------|-------------|
  126. | keyword1 | 12,000 | 3,200 | 5,400 | 45% |
  127. | keyword2 | 8,500 | 4,100 | 1,200 | 14% |
  128. ---
  129. ### Module B: Cross-Topic Heatmap
  130. **Answers:** Which topic × scene intersections have demand? Where are the content gaps?
  131. **Commands:**
  132. ```bash
  133. # Combine base topic with scene/angle keywords
  134. redbook search "base topic + scene1" --sort popular --json
  135. redbook search "base topic + scene2" --sort popular --json
  136. redbook search "base topic + scene3" --sort popular --json
  137. ```
  138. **Fields to extract:** Same as Module A — Top1 `liked_count` for each combination.
  139. **How to interpret:**
  140. - High Top1 = proven demand for this intersection
  141. - Zero or very low results = content gap (opportunity or no demand — check if the combination makes sense)
  142. - Compare across scenes to find which angles resonate most with the base topic
  143. **Output:** Base × Scene heatmap.
  144. ```
  145. scene1 scene2 scene3 scene4
  146. base topic ████ 8K ██ 2K ████ 12K ░░ 200
  147. ```
  148. ---
  149. ### Module C: Engagement Signal Analysis
  150. **Answers:** What type of content is each keyword? Reference, insight, or entertainment?
  151. **Commands:** Use search results from Module A, or for a single note:
  152. ```bash
  153. redbook analyze-viral "<noteUrl>" --json
  154. ```
  155. **Fields to extract:**
  156. - From search results: compute ratios from `interact_info` fields
  157. - From `analyze-viral`: use pre-computed `engagement.collectToLikeRatio`, `engagement.commentToLikeRatio`, `engagement.shareToLikeRatio`
  158. **How to interpret:** Apply the ratio benchmarks from [XHS Platform Signals](#xhs-platform-signals) above.
  159. **Output:** Per-keyword or per-note classification.
  160. | Keyword | Collect/Like | Comment/Like | Type |
  161. |---------|-------------|-------------|------|
  162. | keyword1 | 45% | 8% | 工具型 + 正常互动 |
  163. | keyword2 | 12% | 22% | 娱乐型 + 讨论型 |
  164. ---
  165. ### Module D: Creator Discovery & Profiling
  166. **Answers:** Who are the key creators in this niche? What are their strategies?
  167. **Commands:**
  168. ```bash
  169. # 1. Collect unique user_ids from search results across keywords
  170. # Extract from items[].note_card.user.user_id
  171. # 2. For each creator:
  172. redbook user "<userId>" --json
  173. redbook user-posts "<userId>" --json
  174. ```
  175. **Fields to extract:**
  176. - From `user`: `interactions[]` where `type === "fans"` → follower count
  177. - From `user-posts`: `notes[].interact_info.liked_count` for all posts → compute avg, median, max
  178. - From `user-posts`: `notes[].display_title` → content patterns, posting frequency
  179. **How to interpret:**
  180. - **Avg vs. Median likes:** Large gap means viral outliers inflate the average. Median is the "true" baseline.
  181. - **Max / Median ratio:** >5× means they've had breakout hits. Study those notes specifically.
  182. - **Post frequency:** Count notes to estimate posting cadence. Prolific creators (>3/week) vs. quality-focused (<1/week).
  183. **Output:** Creator comparison table.
  184. | Creator | Followers | Avg Likes | Median | Max | Posts | Style |
  185. |---------|----------|-----------|--------|-----|-------|-------|
  186. | @creator1 | 12万 | 3,200 | 1,800 | 45,000 | 89 | Tutorial |
  187. | @creator2 | 5.4万 | 8,100 | 6,500 | 22,000 | 34 | Story |
  188. ---
  189. ### Module D2: Known Account Reporting
  190. **Answers:** Given a known list of account IDs/profile URLs, how often did each account post and how did each post perform?
  191. Use this when the user already has KOS/KOC account IDs and wants clean account-scoped metrics. Do **not** approximate this with keyword search; keyword search introduces unrelated posts and noisy attribution.
  192. ```bash
  193. redbook account-report --file accounts.txt --month 2026-07 --json
  194. redbook account-report "<profileUrl1>" "<profileUrl2>" --max-pages 2 --json
  195. ```
  196. Input files are newline-separated user IDs or profile URLs; blank lines and `#` comments are ignored. Prefer profile URLs containing `xsec_token` when available. JSON output includes account summary fields (`fetchedPosts`, `postsInMonth`, `complete`, `pagesFetched`), engagement totals and averages, top posts, and per-note rows with title, type, publish time, metrics, and `webUrl`.
  197. Default mode fetches only the first page per account. `complete: false` means more pages exist. Use `--all` only when the user explicitly wants full history and the account list is small enough to pace safely; otherwise prefer `--max-pages <n>`.
  198. ---
  199. ### Module E: Content Form Breakdown
  200. **Answers:** Do image-text or video notes perform better for this topic?
  201. **Commands:**
  202. ```bash
  203. redbook search "keyword" --type image --sort popular --json
  204. redbook search "keyword" --type video --sort popular --json
  205. ```
  206. **Fields to extract:**
  207. - Compare Top1 and Top10 avg `liked_count` and `collected_count` between the two result sets
  208. - Note the `type` field: `"normal"` = image-text, `"video"` = video
  209. **Output:** Form × engagement table.
  210. | Form | Top1 Likes | Top10 Avg | Collect/Like |
  211. |------|-----------|-----------|-------------|
  212. | 图文 | 8,000 | 2,400 | 42% |
  213. | 视频 | 15,000 | 5,100 | 18% |
  214. ---
  215. ### Module F: Opportunity Scoring
  216. **Answers:** Which keywords should I target? Where is the best effort-to-reward ratio?
  217. **Input:** Keyword matrix from Module A.
  218. **Scoring logic:**
  219. - **Demand** = Top1 likes ceiling (proven audience size)
  220. - **Competition** = density of high-engagement results (how many notes in Top10 have >1K likes)
  221. - **Score** = Demand × (1 / Competition density)
  222. **Tier thresholds** (based on Top1 likes):
  223. | Tier | Top1 Likes | Meaning |
  224. |------|-----------|---------|
  225. | S | >100,000 (10万+) | Massive demand — hard to compete but huge upside |
  226. | A | 20,000–100,000 | Strong demand — competitive but winnable |
  227. | B | 5,000–20,000 | Moderate demand — good for growing accounts |
  228. | C | <5,000 | Niche — low competition, low ceiling |
  229. **Output:** Tiered keyword list.
  230. | Tier | Keyword | Top1 | Competition | Opportunity |
  231. |------|---------|------|-------------|------------|
  232. | A | keyword1 | 45K | Medium (6/10 >1K) | High |
  233. | B | keyword3 | 12K | Low (2/10 >1K) | Very High |
  234. | S | keyword2 | 120K | High (10/10 >1K) | Medium |
  235. ---
  236. ### Module G: Audience Inference
  237. **Answers:** Who is the audience for this niche? What do they want?
  238. **Input:** Engagement ratios from Module C + comment themes from `analyze-viral` + content patterns.
  239. **Fields to extract** from `analyze-viral` JSON:
  240. - `comments.themes[]` — recurring phrases and keywords from comment section
  241. - `comments.questionRate` — % of comments that are questions (learning intent)
  242. - `engagement.collectToLikeRatio` — save behavior signals intent
  243. - `hook.hookPatterns[]` — what title patterns attract this audience
  244. **Inference rules:**
  245. - High collect rate + high question rate → learning-oriented audience (students, professionals)
  246. - High comment rate + emotional themes → community-oriented audience (sharing experiences)
  247. - High share rate → aspiration-oriented audience (lifestyle, identity signaling)
  248. - Comment language patterns → age/education signals (formal = older, slang = younger)
  249. **Output:** Audience persona summary — demographics, intent, content preferences.
  250. ---
  251. ### Module H: Content Brainstorm
  252. **Answers:** What specific content should I create, backed by data?
  253. **Input:** Opportunity scores (Module F) + audience persona (Module G) + heatmap gaps (Module B).
  254. **For each content idea, specify:**
  255. - **Target keyword** — from opportunity scoring
  256. - **Hook angle** — based on `hookPatterns` that work for this niche
  257. - **Content type** — 工具型/认知型/娱乐型 based on what the audience wants
  258. - **Form** — 图文 or 视频 based on Module E
  259. - **Engagement target** — realistic based on Top10 avg for this keyword
  260. - **Competitive reference** — specific note URL that proves this angle works
  261. **Output:** Ranked content ideas with data backing.
  262. | # | Keyword | Hook Angle | Type | Target Likes | Reference |
  263. |---|---------|-----------|------|-------------|-----------|
  264. | 1 | keyword3 | "N个方法..." (List) | 工具型 图文 | 5K+ | [top note URL] |
  265. | 2 | keyword1 | "为什么..." (Question) | 认知型 视频 | 10K+ | [top note URL] |
  266. ---
  267. ### Module I: Comment Operations
  268. **Answers:** Which comments deserve a reply? What is the comment quality distribution?
  269. **Commands:**
  270. ```bash
  271. # 1. Fetch all comments
  272. redbook comments "<noteUrl>" --all --json
  273. # 2. Preview reply candidates (dry run)
  274. redbook batch-reply "<noteUrl>" --strategy questions --dry-run --json
  275. # 3. Execute replies with template (5 min delay with ±30% jitter)
  276. redbook batch-reply "<noteUrl>" --strategy questions \
  277. --template "感谢提问!关于{content},..." \
  278. --max 10
  279. ```
  280. **Fields to extract from `--dry-run` JSON:**
  281. - `candidates[].commentId` — target comments
  282. - `candidates[].isQuestion` — boolean, detected question
  283. - `candidates[].likes` — engagement signal
  284. - `candidates[].hasSubReplies` — whether already answered
  285. - `skipped` — how many comments were filtered out
  286. - `totalComments` — total fetched
  287. **Strategies:**
  288. - `questions` — replies to comments ending with `?` or `?` (learning-oriented audience)
  289. - `top-engaged` — replies to highest-liked comments (maximum visibility)
  290. - `all-unanswered` — replies to comments with no existing sub-replies (fill gaps)
  291. **How to interpret:**
  292. - High question rate (>15%) = audience is learning-oriented → reply to build authority
  293. - High top-engaged comments (>100 likes) = reply to visible comments for maximum reach
  294. - Many unanswered comments = engagement gap, opportunity to increase reply rate
  295. **Safety:** Hard cap 30 replies per batch, minimum 3-minute delay with ±30% jitter (default 5 min), `--dry-run` by default (no template = preview only), immediate stop on captcha. See [Rate Limits & Safety](#rate-limits--safety) for details.
  296. **Output:** Reply plan table with candidate comments, strategy match reason, and status.
  297. ---
  298. ### Module J: Viral Replication
  299. **Answers:** What structural template can I extract from successful notes to guide new content creation?
  300. **Commands:**
  301. ```bash
  302. # 1. Find top notes for a keyword
  303. redbook search "keyword" --sort popular --json
  304. # 2. Extract structural template from 2-3 top performers
  305. redbook viral-template "<url1>" "<url2>" "<url3>" --json
  306. ```
  307. **Fields to extract from `viral-template` JSON:**
  308. - `dominantHookPatterns[]` — hook types appearing in majority of notes
  309. - `titleStructure.commonPatterns[]` — specific title formula
  310. - `titleStructure.avgLength` — target title length
  311. - `bodyStructure.lengthRange` — target word count [min, max]
  312. - `bodyStructure.paragraphRange` — target paragraph count
  313. - `engagementProfile.type` — reference/insight/entertainment
  314. - `audienceSignals.commonThemes[]` — what the audience talks about
  315. **How to interpret:**
  316. - Consistent hook patterns across notes = proven formula for this niche
  317. - Narrow body length range = audience has clear content length preference
  318. - High collect/like in profile = audience saves content → create reference material
  319. - Common comment themes = topics to address in new content
  320. **Composition with other modules:**
  321. - Uses Module A results to identify top URLs for template extraction
  322. - Feeds into Module H (Content Brainstorm) as structural constraint
  323. - Uses Module C classification to validate engagement profile
  324. **Output:** Content template spec — the structural skeleton for content creation. An LLM (via the composed workflow) uses this template to generate actual title, body, hashtags, and cover image prompt.
  325. ---
  326. ### Module K: Engagement Automation
  327. **Answers:** How should I manage ongoing engagement with my audience?
  328. This module is a workflow that composes Modules I and J with human oversight.
  329. **Workflow:**
  330. 1. **Monitor** — `redbook comments "<myNoteUrl>" --all --json` to fetch recent comments
  331. 2. **Filter** — `redbook batch-reply --strategy questions --dry-run` to identify reply candidates
  332. 3. **Review** — Human reviews dry-run output (or LLM reviews with persona guidelines)
  333. 4. **Execute** — `redbook batch-reply --strategy questions --template "..." --max 10`
  334. 5. **Report** — Summary of replies sent, errors encountered, rate limit status
  335. **Safety rules:**
  336. - Always `--dry-run` first, human approval before execution
  337. - Maximum 30 replies per session (hard cap)
  338. - Minimum 3-minute delay between replies, default 5 minutes, with ±30% random jitter
  339. - Never reply to the same comment twice (check `hasSubReplies`)
  340. - Stop immediately on captcha — do not retry
  341. - See [Rate Limits & Safety](#rate-limits--safety) for XHS risk control thresholds
  342. **Anti-spam guidelines:**
  343. - Vary reply templates across batches
  344. - Limit to 1-2 batch runs per note per day
  345. - Prioritize quality (targeted strategy) over quantity
  346. - Uniform timing patterns trigger bot detection — jitter is applied automatically
  347. ---
  348. ### Module L: Card Rendering
  349. **Answers:** How do I turn markdown content into Xiaohongshu-ready image cards?
  350. **Commands:**
  351. ```bash
  352. # Render markdown to styled PNG cards
  353. redbook render content.md --style xiaohongshu
  354. # Custom style and output directory
  355. redbook render content.md --style dark --output-dir ./cards
  356. # JSON output (for programmatic use)
  357. redbook render content.md --json
  358. ```
  359. **Input:** Markdown file with YAML frontmatter:
  360. ```markdown
  361. ---
  362. emoji: "🚀"
  363. title: "5个AI效率技巧"
  364. subtitle: "Claude Code 实战"
  365. ---
  366. ## 技巧一:...
  367. Content here...
  368. ---
  369. ## 技巧二:...
  370. More content...
  371. ```
  372. **Output:** `cover.png` + `card_1.png`, `card_2.png`, ... in the same directory.
  373. **Card specs:**
  374. - **Size:** 1080×1440 (3:4 ratio, standard XHS image)
  375. - **DPR:** 2 (retina quality, actual output 2160×2880)
  376. - **Styles:** purple, xiaohongshu, mint, sunset, ocean, elegant, dark
  377. **Pagination modes:**
  378. - `auto` (default) — smart split on heading/paragraph boundaries using character-count heuristic
  379. - `separator` — manual split on `---` in markdown
  380. **How to interpret:**
  381. - Uses the user's existing Chrome for rendering (via `puppeteer-core`) — no browser download needed
  382. - Purely offline — no XHS API or cookies required
  383. - Output images are ready for `redbook post --images cover.png card_1.png ...`
  384. **Dependencies:** Requires `puppeteer-core` and `marked` (optional, install with `npm install -g puppeteer-core marked`).
  385. **Composition with other modules:**
  386. - Pairs with Module H (Content Brainstorm) — generate content ideas, write markdown, render to cards
  387. - Pairs with Module J (Viral Replication) — extract template, write content matching the template, render
  388. - Output feeds into `redbook post --images` for publishing
  389. ---
  390. ### Module M: Note Health Check (限流检测)
  391. **Answers:** Are any of my notes being secretly rate-limited by XHS?
  392. XHS assigns a hidden `level` field to each note in the creator backend API. This level controls recommendation distribution but is **never shown in the UI**. Your note may look "normal" while secretly receiving zero recommendations.
  393. **Commands:**
  394. ```bash
  395. # Check all notes (first page)
  396. redbook health
  397. # Check all pages
  398. redbook health --all
  399. # JSON output for programmatic use
  400. redbook health --all --json
  401. ```
  402. **Level definitions:**
  403. | Level | Status | Meaning |
  404. |-------|--------|---------|
  405. | 4 | 🟢 Normal | Full recommendation distribution |
  406. | 2-3 | 🟡 Baseline | Basically normal, minor constraints |
  407. | 1 | ⚪ New | Under review (new post) |
  408. | -1 | 🔴 Soft limit | Mild throttling, decreased recommendations |
  409. | -5 to -101 | 🔴 Moderate | Moderate throttling, minimal promotion |
  410. | -102 | ⛔ Severe | Irreversible — must delete and repost |
  411. **Additional checks:**
  412. - **Sensitive word detection** — flags titles containing automation/AI keywords (自动化, AI生成, 批量, etc.)
  413. - **Tag count warning** — flags notes with >5 hashtags (risk factor)
  414. **How to interpret:**
  415. - Level -1 or below = your note is being throttled. Consider editing or deleting + reposting.
  416. - Level -102 = irreversible. Delete the note and create fresh content.
  417. - Sensitive word hits = risky title keywords that may trigger throttling. Rephrase.
  418. - Excessive tags = potential spam signal. Use 3-5 targeted tags.
  419. **Output:** Terminal dashboard with color-coded distribution summary, limited notes list, and risk factor warnings.
  420. **Discovery credit:** [@xxx111god](https://x.com/xxx111god) — [xhs-note-health-checker](https://github.com/jzOcb/xhs-note-health-checker)
  421. ---
  422. ## Composed Workflows
  423. Combine modules for different analysis depths.
  424. ### Quick Topic Scan (~5 min)
  425. **Modules:** A → C → F
  426. Search 3–5 keywords, classify engagement type, rank opportunities. Good for quickly validating whether a niche is worth deeper research.
  427. ### Content Planning
  428. **Modules:** A → B → E → F → H
  429. Build keyword matrix, map topic × scene intersections, check content form performance, score opportunities, brainstorm specific content ideas.
  430. ### Creator Competitive Analysis
  431. **Modules:** A → D
  432. Find who dominates a niche and study their content strategy, posting frequency, and engagement patterns.
  433. ### Full Niche Analysis
  434. **Modules:** A → B → C → D → E → F → G → H
  435. The comprehensive playbook — keyword landscape, cross-topic heatmap, engagement signals, creator profiles, content form analysis, opportunity scoring, audience personas, and data-backed content ideas.
  436. ### Single Note Deep-Dive
  437. **Command:** `redbook analyze-viral "<url>" --json`
  438. No module composition needed — `analyze-viral` returns hook analysis, engagement ratios, comment themes, author baseline comparison, and a 0-100 viral score in one call.
  439. ### Viral Pattern Research → Content Template
  440. ```bash
  441. # 1. Find top notes
  442. redbook search "keyword" --sort popular --json
  443. # 2. Extract template from top 3 notes (replaces manual synthesis)
  444. redbook viral-template "<url1>" "<url2>" "<url3>" --json
  445. ```
  446. `viral-template` automates what previously required manual synthesis across `analyze-viral` results. It outputs a `ContentTemplate` JSON that captures dominant hooks, body structure ranges, engagement profile, and audience signals.
  447. ### Reply Management
  448. **Modules:** I
  449. Single-module workflow for managing comment engagement on your notes. Use `batch-reply --dry-run` to audit, then execute with a template.
  450. ### Content Replication
  451. **Modules:** A → J → H → L
  452. Keyword research → viral template extraction → data-backed content brainstorm → render to image cards. The template provides structural constraints that guide Module H's content ideas. Module L renders the final markdown to XHS-ready PNGs.
  453. ### Content Creation End-to-End
  454. **Modules:** A → J → H → L → `post`
  455. The full pipeline: research keywords → extract viral template → brainstorm content → write markdown → render to styled image cards → publish via `redbook post --images cover.png card_1.png ...`
  456. ### Account Health Monitoring
  457. **Modules:** M
  458. Run `redbook health --all` periodically to catch throttled notes early. If level drops below 1, investigate the note's content for policy violations. Combine with Module I to check if throttled notes still have unanswered comments worth replying to.
  459. ### Full Operations
  460. **Modules:** A → C → I → J → K → M
  461. Comprehensive automation playbook — keyword analysis, engagement classification, comment operations, viral replication templates, and engagement automation workflow.
  462. ---
  463. ## Rate Limits & Safety
  464. XHS enforces aggressive anti-spam (风控) that detects automated behavior through device fingerprinting, activity ratio monitoring, and timing pattern analysis. The CLI applies safe defaults based on platform research.
  465. ### Safe Thresholds
  466. | Action | Safe Interval | CLI Default | Hard Cap |
  467. |--------|--------------|-------------|----------|
  468. | Post a note | 3-4 hours (2-3 notes/day max) | N/A (manual) | — |
  469. | Comment | ≥3 minutes | N/A (manual) | — |
  470. | Reply | ≥3 minutes | N/A (manual) | — |
  471. | Batch reply delay | ≥3 minutes | 5 min ±30% jitter | — |
  472. | Batch reply count | — | 10 | 30 |
  473. ### Anti-Detection Measures
  474. - **Timing jitter:** ±30% random variation on all batch delays. Uniform intervals are a bot signature.
  475. - **Hard caps:** Maximum 30 replies per batch (down from 50). No override.
  476. - **Rate limit warnings:** `post`, `comment`, and `reply` commands display safe interval reminders after each action.
  477. - **Captcha circuit breaker:** Batch operations stop immediately on captcha (NeedVerify).
  478. ### What Triggers Risk Control
  479. - **Uniform timing** — replying at exact 3-second intervals flags bot detection
  480. - **High frequency** — >50 interactions/minute across any action type
  481. - **Activity ratio anomaly** — more comments than post views signals inauthentic behavior
  482. - **Device fingerprint mismatch** — XHS fingerprints 21 hardware parameters
  483. ### Best Practices for Agents
  484. 1. Always `--dry-run` first, review candidates, then execute
  485. 2. Use the default 5-minute delay — do not override `--delay` below 180000 (3 min)
  486. 3. Limit batch runs to 1-2 per note per day
  487. 4. Vary reply templates between batches
  488. 5. Space `post` commands 3-4 hours apart (2-3 notes/day maximum)
  489. ---
  490. ## Research Loop — Rate-Limit-Safe Long-Running Research
  491. The [Rate Limits & Safety](#rate-limits--safety) section above paces *writes*. This section paces **reads** — the part research actually hammers. `read`, `comments`, and `analyze-viral` each hit the note-detail API (with `xsec_token`); fire 30–50 in a tight loop and XHS returns `NeedVerify` / captcha or IP-blocks you (300012), and a tripped account stays degraded for **hours**. So research here is **paced, not parallel**: one note in flight, spaced to look like a human reading rather than a script scraping.
  492. The mechanism is a **file-based loop**: a queue of work items on disk, one item processed per "tick", every result checkpointed immediately. Because all state lives in files, the loop is **resumable and survives the session ending** — a fresh session (or a Push heartbeat) picks up exactly where the last left off. Pairs with the `/checkpoint-research` skill for the synthesis step.
  493. ### Pace — the safe band (why these numbers)
  494. These are calibrated to XHS's documented read-side safe band, not guesswork. Community crawlers ([MediaCrawler](https://github.com/NanmiCoder/MediaCrawler)) default to **~2 s/request, single-threaded** (`CRAWLER_MAX_SLEEP_SEC = 2`, `MAX_CONCURRENCY_NUM = 1`); reverse-engineering write-ups put the "looks-human" frequency at **3–8 s/request** and the per-IP ceiling at **≤5 requests/min** (~12 s average). This skill runs on your **real logged-in cookies + residential IP + real Chrome fingerprint** — the *lowest*-detection profile (the thing scrapers spend most of their effort faking). So the binding risk isn't request signature, it's **behavioral**: a human doesn't open 100 note-detail pages in two minutes. We therefore pace to a human reading cadence — comfortably inside the safe band — rather than to the absolute minimum. (5-minute gaps, an earlier guess, are ~25× slower than the ceiling and buy nothing.)
  495. ### The real rule: behave like a human reading (not "go slow")
  496. Detection here is **distributional, not a rate threshold.** XHS doesn't ask "more than N requests?" — it models what a human session looks like and flags the *unlikely* ones. Pure speed isn't the tell; the **shape** of the behavior is. Three things give a script away:
  497. - **Timing micro-structure.** A human's gaps between actions are high-variance and heavy-tailed (2 s, then 40 s, then 5 min — they read, scroll, get distracted). A script emits a tight, low-variance stream. *Three distinct searches in five seconds has near-zero variance and is faster than a person can read a result page* — that single fact is a stronger signal than the total count.
  498. - **Session macro-structure.** Humans browse depth-first: search → open a note → dwell → open a related note → wander. A scrape is breadth-first enumeration: search A, search B, search C… never clicking in, never dwelling. A keyword list run top-to-bottom *is* the signature.
  499. - **Action composition.** Real sessions mix likes, collects, dwell, scroll, video-watch. A research run is 100% read with zero dwell and zero engagement — an impossible ratio for a person.
  500. So the rule is **not "go slow."** It's **make the session indistinguishable from a person reading**: human-shaped *variance* (jitter + the occasional long pause, not merely a bigger constant), one note at a time *with dwell*, depth over breadth, a ceiling because people don't open hundreds of things, and **stop at the first sign of friction** (a human who hits a captcha backs off; a bot retries — so the circuit breaker is itself human-like behavior).
  501. **Safety-first is the *more* agentic posture, not the timid one.** An agent's real advantage isn't speed — it's *patience at scale*: it can run a human-shaped loop for eight hours, which no person will. Aggression imitates the one human trait that gets you caught (impatience) and wastes the one the agent uniquely has (tireless patience). Lean into the patience.
  502. **This is a pattern, not a blacklist.** The numbers here were calibrated from a real incident — a beverage-trend sweep that fired *3 distinct searches in ~5 seconds* across ~17 unrelated keywords and drew an account-level warning. What's encoded is the *behavioral invariant* (human-shaped timing, one-in-flight, ceiling, dwell, breaker), **not** "don't run those queries." It generalizes to any topic and any platform. The incident is the calibration sample that tells us where the human/bot line sits — not a rule about matcha.
  503. ### Three modes
  504. | Mode | Pace per note | ~Reads/min | Use when | Gate |
  505. |------|--------------|-----------|----------|------|
  506. | 🚶 **Steady (default)** | **20 s ± 50% jitter** (≈10–35 s) | ~2–3 | All routine / multi-note research | **None — this is the default.** |
  507. | 🐢 **Deep / overnight** | 60–120 s | ~0.5–1 | Very large corpora, or minimizing footprint | Opt in for big jobs |
  508. | ⚡ **Fast (emergency)** | **5 s ± jitter floor**, max 30-note burst then cooldown | ~10+ (over the safe ceiling) | A genuine deadline that cannot wait | MUST print the [fast-mode warning](#-fast-mode-warning-emergency-only) verbatim **and** get explicit user opt-in |
  509. **Invariants (all modes):** never zero-delay, never parallel, exactly one note in flight, and — except for warned Fast mode — **never exceed ~5 reads/min sustained.** At the Steady pace a 100-note queue finishes in ~35–50 min; only very large queues or Deep mode stretch toward end-of-day.
  510. ### Strict rules (non-negotiable)
  511. 1. **The loop is mandatory; Steady is the default pace.** Any research touching more than ~5 notes runs through the loop at Steady pace. Deep/overnight and especially Fast are explicit opt-ins — Fast additionally requires the printed warning + user confirmation.
  512. 2. **One note in flight.** Never batch or parallelize reads. No `for url in …; do redbook read …; done` without the inter-item delay. No background `&` fan-out. (`MAX_CONCURRENCY = 1`, like the reference crawlers.)
  513. 3. **Stay under ~5 reads/min, always jittered.** The per-IP safe ceiling is ~5 requests/min (~12 s/note); Steady (20 s) sits comfortably under it. Apply ±50% random jitter to every wait — uniform intervals are a bot signature. Only warned Fast mode may cross the ceiling.
  514. 4. **Cap comment pagination.** Comment / sub-comment reads are the highest-risk endpoint — they trip 风控 first (deep comment crawls fail even at very long sleeps). Keep `--comment-pages ≤ 3`, count each comment page against the pace + budget like any other read, and never deep-crawl a comment thread.
  515. 5. **Checkpoint every item.** Write each result to disk and update the manifest *before* the next tick. Nothing in memory only.
  516. 6. **Respect the daily budget.** Default soft cap **~200 detail-reads/day** — anomalous *volume* is its own 风控 trigger, independent of pace. When `consumedToday >= dailyBudget`, stop until the next calendar day — do not "just finish a few more".
  517. 7. **Circuit breaker is absolute.** On the first 风控 signal (see [Circuit breaker](#circuit-breaker)), STOP the entire loop, persist state, surface to the user, and **do not auto-retry through it.** Resume only on an explicit human "resume".
  518. 8. **Reads, not writes.** This loop is for reading/analysis only. Engagement actions (comment/reply/like) keep their own [write-side limits](#rate-limits--safety) and are never folded into a research tick.
  519. ### State contract (resumable, survives session death)
  520. All state lives under one job directory — default `research/xhs/<job-slug>/` in the **private content repo** (ask if unclear which repo):
  521. | File | Role |
  522. |------|------|
  523. | `queue.jsonl` | The work queue, one item per line: `{ "id": "001", "kind": "read\|comments\|analyze-viral\|search\|user\|user-posts", "arg": "<url-or-keyword-or-userId>", "status": "pending\|done\|error", "note": "" }` |
  524. | `results/<id>.json` | Raw `--json` output for each processed item (the corpus) |
  525. | `loop-state.json` | `{ "mode": "steady\|deep\|fast", "intervalSec": 20, "jitterPct": 50, "dailyBudget": 200, "consumedToday": 0, "budgetDate": "YYYY-MM-DD", "lastTickAt": "<iso>", "breaker": "ok\|tripped", "breakerReason": null }` (Deep: `intervalSec` 60–120; Fast: `intervalSec` 5 + `mode:"fast"`) |
  526. | `manifest.md` | Human-readable plan + progress (checkmark per done item) — the recovery checkpoint, updated every tick |
  527. | `SUMMARY.md` | Final synthesis, written once the queue drains |
  528. **Seeding the queue:** the cheap list endpoints (`search`, `feed`, and `user-posts` with a fresh profile URL/token) are how you *build* the queue, not part of the paced loop. Run a `search`/`feed` up front, extract each note `webUrl`, and write one `read`/`analyze-viral` item per note into `queue.jsonl`. Then the loop drains the expensive detail-reads at the Steady pace. Always carry the fresh `webUrl` (with token) as the item `arg` — tokens expire, so don't queue bare noteIds (see [xsec_token](#xsec_token--required-for-reading--sharing-notes)). For creator queues, prefer a profile URL containing `xsec_token`; bare userIds may return `code=-1`.
  529. ### One tick = one note
  530. A tick is the unit both drivers call. It processes exactly one item and stops:
  531. 1. **Load `loop-state.json`.** If `breaker != "ok"` → exit immediately (surface the reason; do not process).
  532. 2. **Roll the daily budget.** If `budgetDate` != today, reset `consumedToday = 0`, `budgetDate = today`. If `consumedToday >= dailyBudget` → exit until tomorrow.
  533. 3. **Pop the next `pending` item** from `queue.jsonl`. If none remain → **finalize**: synthesize `SUMMARY.md` from `results/`, mark the loop complete, and tell the driver to stop. Done.
  534. 4. **Run exactly one read:** `redbook <kind> "<arg>" --json`.
  535. 5. **Inspect the result for a 风控 signal** (empty `{}`, `NeedVerify`/captcha, `Session expired`, IP block 300012). If found → **trip the breaker**: set `breaker:"tripped"` + `breakerReason`, leave the item `pending` (not consumed), persist, surface to the user, STOP. (See [Circuit breaker](#circuit-breaker).)
  536. 6. **On success:** write `results/<id>.json`, set the item `status:"done"`, check it off in `manifest.md`, `consumedToday += 1`, set `lastTickAt`.
  537. 7. **Stop.** One note only — the driver re-invokes after the (jittered) interval.
  538. ### Drivers — keeping the loop running in the background
  539. The same tick, driven two ways. Pick by how long the job must outlive the current session:
  540. **A) In-session pacing (default — Steady).** The simplest driver and the right one for most jobs: run ticks back-to-back inside one session, sleeping `intervalSec` ± jitter between each read. At Steady pace a 100-note queue finishes in ~35–50 min — comfortably within one session — and every item is checkpointed, so a crash just resumes. No scheduler needed. (Pace *per read*; don't fake it with one long blocking `sleep`.)
  541. **B) `/loop` self-paced (Deep / overnight / survives idle gaps).** For Deep mode or jobs spanning hours, drive ticks with `/loop` *without* an interval (self-paced): do one tick, then `ScheduleWakeup` for `intervalSec` + jitter, and re-fire. `ScheduleWakeup` clamps to **≥60 s**, so it fits Deep (60–120 s) — not sub-minute Steady (run that in-session, per A). The loop ends itself when the queue drains (Step 3) or the breaker trips (Step 5).
  542. **C) Hook — Push recurring issue (multi-day / true background, survives app restarts).** Best for "run this every day" research or corpora too big for one day. Create a **recurring issue** (`recurringIntervalSec` — a few minutes per tick, or a daily sweep) assigned to a redbook-capable agent. Each occurrence is a **fresh session = one tick** against the same job directory — so the issue body must point at the job dir and say "run exactly one tick, then exit." It keeps firing until a human retires it; the agent finalizes + comments when the queue drains, and comments + leaves it for human attention if the breaker trips. (Push "scout" pattern — the schedule lives on the issue, the agent's Auto switch gates it.)
  543. > **Why file-state, not a long-lived process:** a single blocking `sleep`-loop dies with the terminal and can't be resumed. The queue + `loop-state.json` + per-item result files mean *any* future session — `/loop` wake, Push heartbeat, or a human re-running the tick — continues exactly where the last stopped, and the partial corpus is never lost.
  544. ### ⚡ Fast-mode warning (emergency only)
  545. Before **any** fast-mode run, print this verbatim and require an explicit "yes, fast mode" from the user. Do not proceed on silence or a vague affirmative:
  546. ```
  547. ⚠️ XHS FAST RESEARCH MODE — elevated 风控 risk
  548. Reading at ~12 notes/min crosses the safe ~5/min ceiling and
  549. materially raises the chance of:
  550. • captcha / NeedVerify mid-run (stops the loop)
  551. • IP block (error 300012) for hours
  552. • account-level recommendation throttling
  553. Steady mode (the default, ~20s/note) stays inside the safe band
  554. and still finishes a typical job in well under an hour.
  555. Proceed with fast mode for this run only? (yes / no)
  556. ```
  557. Fast mode still obeys the floor (≥5 s ± jitter between notes — never zero), caps a burst at 30 notes then forces a cooldown back to Steady pace, and the circuit breaker still hard-stops on the first 风控 signal. Fast mode raises the *pace* past the safe ceiling; it never removes the floor or the breaker.
  558. ### Circuit breaker
  559. Trip the breaker and STOP the whole loop on the **first** of any of these from a read:
  560. | Signal | Where it shows |
  561. |--------|----------------|
  562. | `NeedVerify` / captcha | error message or response flag |
  563. | Empty `{}` response | usually expired/invalid `xsec_token` or anti-scrape — re-seed the queue with fresh `webUrl`s, don't retry blindly |
  564. | `Session expired` / "No 'a1' cookie" | cookie invalid — re-login in Chrome before resuming |
  565. | IP block `300012` | hard rate limit — wait it out / switch network |
  566. On trip: set `loop-state.breaker:"tripped"` + `breakerReason`, leave the current item `pending`, persist, and surface to the user (or comment on the Push issue). **Never auto-retry through a block** — that's what escalates a soft throttle into a multi-hour block. Resume only after a human clears the cause and explicitly says to continue.
  567. ---
  568. ## API vs Browser Limitations
  569. The following operations work reliably via API:
  570. - **Reading**: search, notes, comments, user profiles, feed, favorites
  571. - **Writing**: top-level comments, comment replies, collect/uncollect notes
  572. - **Analysis**: viral scoring, template extraction, batch reply planning
  573. The following operations are unreliable via API (frequently trigger captcha):
  574. - Publishing notes (use `--private` for higher success rate)
  575. - Bulk operations at very high frequency
  576. The following operations require browser automation (not supported by this CLI):
  577. - Captcha solving, real-time notifications
  578. - Like/follow (heavy anti-automation enforcement)
  579. - DM/private messaging
  580. - Cover image generation (use external tools like Gemini/DALL-E)
  581. ---
  582. ## Command Details
  583. ### `redbook search <keyword>`
  584. Search for notes by keyword. Returns note titles, URLs, likes, author info.
  585. ```bash
  586. redbook search "Claude Code教程" --json
  587. redbook search "AI编程" --sort popular --json # Sort: general, popular, latest
  588. redbook search "Cursor" --type image --json # Type: all, video, image
  589. redbook search "MCP Server" --page 2 --json # Pagination
  590. ```
  591. **Options:**
  592. - `--sort <type>`: `general` (default), `popular`, `latest`
  593. - `--type <type>`: `all` (default), `video`, `image`
  594. - `--page <n>`: Page number (default: 1)
  595. ### `redbook read <url>`
  596. Read a note's full content — title, body text, images, likes, comments count.
  597. ```bash
  598. redbook read "https://www.xiaohongshu.com/explore/abc123" --json
  599. ```
  600. Accepts full URLs or short note IDs. Falls back to HTML scraping if API returns captcha.
  601. ### `redbook comments <url>`
  602. Get comments on a note. Use `--all` to fetch all pages.
  603. ```bash
  604. redbook comments "https://www.xiaohongshu.com/explore/abc123" --json
  605. redbook comments "https://www.xiaohongshu.com/explore/abc123" --all --json
  606. ```
  607. ### `redbook user <userId|profileUrl>`
  608. Get a creator's profile — nickname, bio, follower count, note count, likes received.
  609. ```bash
  610. redbook user "https://www.xiaohongshu.com/user/profile/5a1234567890abcdef012345?xsec_token=...&xsec_source=pc_search" --json
  611. ```
  612. Accepts a bare userId or a full profile URL. If a bare userId returns `code=-1`, use a fresh profile URL containing `xsec_token`, or pass `--xsec-token <token> --xsec-source pc_search`.
  613. ### `redbook user-posts <userId|profileUrl>`
  614. List all notes posted by a creator. Returns titles, URLs, likes, timestamps.
  615. ```bash
  616. redbook user-posts "https://www.xiaohongshu.com/user/profile/5a1234567890abcdef012345?xsec_token=...&xsec_source=pc_search" --json
  617. ```
  618. ### `redbook account-report <userId|profileUrl...>`
  619. Batch summarize account posting and engagement metrics.
  620. ```bash
  621. redbook account-report --file accounts.txt --month 2026-07 --json
  622. redbook account-report "<profileUrl1>" "<profileUrl2>" --max-pages 2 --json
  623. ```
  624. Options:
  625. - `--file <path>`: newline-separated account IDs/profile URLs
  626. - `--month <YYYY-MM>`: month used for `postsInMonth` (default: current month)
  627. - `--max-pages <n>`: page cap per account when not using `--all` (default: 1)
  628. - `--all`: fetch every page for each account
  629. - `--delay <ms>`: delay between page/account requests (default: 3000)
  630. For KOS/KOC reporting, feed it known account IDs or profile URLs instead of using keyword search. If a bare userId returns `code=-1`, use a fresh profile URL containing `xsec_token`.
  631. ### `redbook feed`
  632. Browse the recommendation feed.
  633. ```bash
  634. redbook feed --json
  635. ```
  636. ### `redbook topics <keyword>`
  637. Search for topic hashtags. Useful for finding trending topics to attach to posts.
  638. ```bash
  639. redbook topics "Claude Code" --json
  640. ```
  641. ### `redbook favorites [userId]`
  642. List a user's collected (bookmarked) notes. Defaults to the current logged-in user when no userId is provided.
  643. ```bash
  644. redbook favorites --json # Your own favorites
  645. redbook favorites "5a1234567890abcdef" --json # Another user's favorites
  646. redbook favorites --all --json # Fetch all pages
  647. ```
  648. **Options:**
  649. - `--all`: Fetch all pages of favorites (default: first page only)
  650. **Note:** Other users' favorites are only visible if they haven't set their collection to private.
  651. ### `redbook collect <url>`
  652. Collect (bookmark) a note to your favorites.
  653. ```bash
  654. redbook collect "https://www.xiaohongshu.com/explore/abc123"
  655. ```
  656. ### `redbook uncollect <url>`
  657. Remove a note from your collection.
  658. ```bash
  659. redbook uncollect "https://www.xiaohongshu.com/explore/abc123"
  660. ```
  661. ### `redbook analyze-viral <url>`
  662. Analyze why a viral note works. Returns a deterministic viral score (0–100).
  663. ```bash
  664. redbook analyze-viral "https://www.xiaohongshu.com/explore/abc123" --json
  665. redbook analyze-viral "https://www.xiaohongshu.com/explore/abc123" --comment-pages 5
  666. ```
  667. **Options:**
  668. - `--comment-pages <n>`: Comment pages to fetch (default: 3, max: 10)
  669. **JSON output structure:**
  670. Returns `{ note, score, hook, content, visual, engagement, comments, relative, fetchedAt }`.
  671. - `score.overall` (0–100) — composite of hook (20) + engagement (20) + relative (20) + content (20) + comments (20)
  672. - `hook.hookPatterns[]` — detected title patterns (Identity Hook, Emotion Word, Number Hook, Question, etc.)
  673. - `engagement` — likes, comments, collects, shares + ratios (collectToLikeRatio, commentToLikeRatio, shareToLikeRatio)
  674. - `relative.viralMultiplier` — this note's likes / author's median likes
  675. - `relative.isOutlier` — true if viralMultiplier > 3
  676. - `comments.themes[]` — top recurring keyword phrases from comments
  677. ### `redbook viral-template <url> [url2] [url3]`
  678. Extract a reusable content template from 1-3 viral notes. Analyzes each note (same pipeline as `analyze-viral`) and synthesizes common structural patterns.
  679. ```bash
  680. redbook viral-template "<url1>" "<url2>" "<url3>" --json
  681. redbook viral-template "<url1>" --comment-pages 5 --json
  682. ```
  683. **Options:**
  684. - `--comment-pages <n>`: Comment pages to fetch per note (default: 3, max: 10)
  685. **JSON output structure:**
  686. Returns `{ dominantHookPatterns, titleStructure, bodyStructure, engagementProfile, audienceSignals, sourceNotes, generatedAt }`.
  687. - `dominantHookPatterns[]` — hook types appearing in majority of input notes
  688. - `titleStructure.avgLength` — average title length across notes
  689. - `bodyStructure.lengthRange` — [min, max] body length
  690. - `engagementProfile.type` — "reference" / "insight" / "entertainment"
  691. - `audienceSignals.commonThemes[]` — merged comment themes across notes
  692. ### `redbook comment <url>`
  693. Post a top-level comment on a note.
  694. ```bash
  695. redbook comment "<noteUrl>" --content "Great post!" --json
  696. ```
  697. **Options:**
  698. - `--content <text>` (required): Comment text
  699. ### `redbook reply <url>`
  700. Reply to a specific comment on a note.
  701. ```bash
  702. redbook reply "<noteUrl>" --comment-id "<commentId>" --content "Thanks for asking!" --json
  703. ```
  704. **Options:**
  705. - `--comment-id <id>` (required): Comment ID to reply to (from `comments --json` output)
  706. - `--content <text>` (required): Reply text
  707. ### `redbook batch-reply <url>`
  708. Reply to multiple comments using a filtering strategy. Always preview with `--dry-run` first.
  709. ```bash
  710. # Preview which comments match the strategy
  711. redbook batch-reply "<noteUrl>" --strategy questions --dry-run --json
  712. # Execute replies with a template (default 5 min delay with jitter)
  713. redbook batch-reply "<noteUrl>" --strategy questions \
  714. --template "感谢提问!{content}" --max 10
  715. ```
  716. **Options:**
  717. - `--strategy <name>`: `questions` (default), `top-engaged`, `all-unanswered`
  718. - `--template <text>`: Reply template with `{author}`, `{content}` placeholders
  719. - `--max <n>`: Max replies (default: 10, hard cap: 30)
  720. - `--delay <ms>`: Delay between replies in ms (default: 300000 / 5 min, min: 180000 / 3 min). ±30% random jitter applied automatically.
  721. - `--dry-run`: Preview candidates without posting (default when no template)
  722. **Safety:** Stops immediately on captcha. No template = dry-run only. Delays include random jitter to avoid uniform timing patterns that trigger XHS bot detection.
  723. ### `redbook render <file>`
  724. Render a markdown file with YAML frontmatter into styled PNG image cards. Uses the user's existing Chrome installation — no browser download needed.
  725. ```bash
  726. redbook render content.md --style xiaohongshu
  727. redbook render content.md --style dark --output-dir ./cards
  728. redbook render content.md --pagination separator --json
  729. ```
  730. **Options:**
  731. - `--style <name>`: `purple`, `xiaohongshu` (default), `mint`, `sunset`, `ocean`, `elegant`, `dark`
  732. - `--pagination <mode>`: `auto` (default), `separator` (split on `---`)
  733. - `--output-dir <dir>`: Output directory (default: same as input file)
  734. - `--width <n>`: Card width in px (default: 1080)
  735. - `--height <n>`: Card height in px (default: 1440)
  736. - `--dpr <n>`: Device pixel ratio (default: 2)
  737. **Requires:** `puppeteer-core` and `marked` (`npm install -g puppeteer-core marked`). Does NOT require XHS cookies — purely offline rendering.
  738. **Override Chrome path:** Set `CHROME_PATH` environment variable if Chrome is not in the standard location.
  739. ### `redbook whoami`
  740. Check connection status. Verifies cookies are valid and shows the logged-in user.
  741. ```bash
  742. redbook whoami
  743. ```
  744. ### `redbook auth`
  745. Manage saved cookies for OpenClaw, cloud, or CI runs where browser cookie extraction is unavailable or `--cookie-string` would be repeated on every command.
  746. ```bash
  747. # Export from the logged-in local browser to ~/.redbook/cookies.json
  748. redbook auth export
  749. # Or save a cookie string copied from Chrome DevTools
  750. redbook auth save --cookie-string "a1=VALUE; web_session=VALUE"
  751. # Inspect without printing secret cookie values
  752. redbook auth path
  753. redbook auth inspect --json
  754. # Remove saved local reuse
  755. redbook auth clear
  756. ```
  757. Normal commands resolve cookies in this order: `--cookie-string`, `REDBOOK_COOKIE_STRING`, `REDBOOK_COOKIE_FILE`, `~/.redbook/cookies.json`, then browser extraction. Saved cookie files are plaintext login credentials written with `0600` permissions; never commit them or include them in logs.
  758. ### `redbook post` (Limited)
  759. Publish an image note. **Frequently triggers captcha (type=124) on the creator API.** Image upload works, but the publish step is unreliable. For posting, consider using browser automation instead.
  760. ```bash
  761. redbook post --title "标题" --body "正文" --images cover.png --json
  762. redbook post --title "测试" --body "..." --images img.png --private --json
  763. ```
  764. **Options:**
  765. - `--title <title>`: Note title (required)
  766. - `--body <body>`: Note body text (required)
  767. - `--images <paths...>`: Image file paths (required, at least one)
  768. - `--topic <keyword>`: Search and attach a topic hashtag
  769. - `--private`: Publish as private note
  770. ### Global Options
  771. All commands accept:
  772. - `--cookie-source <browser>`: `chrome` (default), `safari`, `firefox`
  773. - `--chrome-profile <name>`: Chrome profile directory name (e.g., "Profile 1"). Auto-discovered if omitted.
  774. - `--cookie-string <cookies>`: manual cookie string, e.g. `"a1=VALUE; web_session=VALUE"`
  775. - `--platform <name>`: force `xhs` (mainland) or `rednote` (global). **Default: auto-detect** which one you're logged into — see [Mainland vs Global](#mainland-xiaohongshu-vs-global-rednote).
  776. - `--global`: force the global RedNote backend (= `--platform rednote`)
  777. - `--json`: Output as JSON
  778. ---
  779. ## Mainland Xiaohongshu vs Global RedNote
  780. XHS runs **two separate backends that do NOT share sessions or cookies**:
  781. | | Mainland | Global |
  782. |---|---|---|
  783. | App / site | 小红书 / `xiaohongshu.com` | RedNote / `rednote.com` |
  784. | API host | `edith.xiaohongshu.com` | `webapi.rednote.com` |
  785. | Cookie domain | `.xiaohongshu.com` | `.rednote.com` |
  786. RedNote routes you to mainland vs global **by IP/region**, and you can only be signed into one at a time on a machine — so **the CLI auto-detects which one you're logged into**. You normally pass **no flag at all**:
  787. ```bash
  788. redbook whoami # auto-detects mainland vs global, then shows your account
  789. redbook search "AI" # runs against whichever backend you're logged into
  790. ```
  791. **How detection works:** it probes both cookie domains; if only one has a session it uses that, and if both have cookies (the unused domain often keeps a stale guest cookie) it verifies which is actually logged in via one lightweight `/user/me` call. The result is cached in `~/.redbook/platform-cache.json` (keyed by a cookie fingerprint), so it doesn't re-hit the API every command and self-invalidates when you log in/out. You'll see a dim `Platform: … [auto-detected|cached]` line on stderr.
  792. **Override** only if you need to force one (rare):
  793. ```bash
  794. redbook whoami --global # force global RedNote (= --platform rednote)
  795. redbook whoami --platform xhs # force mainland
  796. # or: export REDBOOK_PLATFORM=rednote
  797. ```
  798. The web signing (x-s/x-t) algorithm is **identical** across both — only the host + cookie domain differ.
  799. **Known gaps on the global backend:**
  800. - `user-posts` / `user` may need a fresh profile `xsec_token`; pass a full profile URL or `--xsec-token` if a bare userId returns `code -1`.
  801. - `health` (note throttle levels) needs creator-dashboard cookies; log into the RedNote creator dashboard first.
  802. ---
  803. ## Technical Reference
  804. ### xsec_token — Required for Reading & Sharing Notes
  805. The XHS API requires a valid `xsec_token` to fetch note content. Without it, `read`, `comments`, and `analyze-viral` return `{}`.
  806. **The same token is also required for shareable URLs.** Any `https://www.xiaohongshu.com/explore/<id>` URL without `?xsec_token=...&xsec_source=...` is 302-redirected by XHS's anti-scrape layer to `https://www.xiaohongshu.com/404/sec_*?source=xhs_sec_server&originalUrl=...`. This affects anyone who clicks the URL — Safari, iOS link previews, agent action buttons, etc.
  807. **`webUrl` — use this (since v0.7.0):**
  808. Every note-returning command (`feed`, `search`, `user-posts`, `favorites`, `board`, `read`, `post`) now includes a `webUrl` field with the token baked in and the correct `xsec_source`. Consumers should use `webUrl` directly — do not construct URLs by hand.
  809. ```bash
  810. redbook feed --json | jq '.items[0].webUrl'
  811. # => "https://www.xiaohongshu.com/explore/<id>?xsec_token=<t>&xsec_source=pc_feed"
  812. ```
  813. `xsec_source` is set per-command: `pc_feed`, `pc_search`, `pc_user`, `pc_board`, `pc_share`.
  814. **Key rules:**
  815. 1. **Tokens expire.** A URL with `?xsec_token=...` from a previous session will return `{}`. Never cache or reuse old URLs.
  816. 2. **`search` and `feed` always return fresh tokens.** Every item includes a valid `xsec_token` + a pre-built `webUrl`.
  817. 3. **noteId alone returns `{}`.** Running `redbook read <noteId>` without a token almost always fails.
  818. **The correct workflow — always search first:**
  819. ```bash
  820. # WRONG — stale URL or bare noteId, will likely return {}
  821. redbook read "689da7b0000000001b0372c6" --json
  822. redbook read "https://www.xiaohongshu.com/explore/689da7b0?xsec_token=OLD_TOKEN" --json
  823. # RIGHT — search first, then use the fresh URL with token
  824. redbook search "AI编程" --sort popular --json
  825. # Extract the webUrl from search results, then:
  826. redbook read "<webUrl from search result>" --json
  827. ```
  828. **For agents:** Prefer `webUrl` from the response. When only a bare noteId is available, search first to obtain a fresh token, then use the returned `webUrl`.
  829. **Commands that need note xsec_token:** `read`, `comments`, `analyze-viral`
  830. **Commands that may need profile xsec_token:** `user`, `user-posts`
  831. **Commands that do NOT need xsec_token:** `search`, `feed`, `whoami`, `topics`
  832. ### Chinese Number Formats in API Responses
  833. The XHS API returns abbreviated numbers with Chinese unit suffixes:
  834. | API value | Actual number |
  835. |-----------|---------------|
  836. | `"1.5万"` | 15,000 |
  837. | `"2.4万"` | 24,000 |
  838. | `"1.2亿"` | 120,000,000 |
  839. | `"115"` | 115 |
  840. `万` = ×10,000. `亿` = ×100,000,000. Numbers under 10,000 are plain integers as strings.
  841. The `analyze-viral` command handles this automatically. When parsing `--json` output manually, watch for these suffixes in `interact_info` fields (`liked_count`, `collected_count`, etc.).
  842. ### Error Handling
  843. | Error | Meaning | Fix |
  844. |-------|---------|-----|
  845. | `{}` empty response | Missing or expired xsec_token | Search first to get a fresh token |
  846. | "No 'a1' cookie" | Not logged into XHS in browser | Log into xiaohongshu.com in Chrome |
  847. | "Session expired" | Cookie too old | Re-login in Chrome |
  848. | "NeedVerify" / captcha | Anti-bot triggered | Wait and retry, or reduce request frequency |
  849. | "IP blocked" (300012) | Rate limited | Wait or switch network |
  850. | "Request signature rejected (HTTP 406)" | XHS changed its web signing | Update redbook (`npm i -g @lucasygu/redbook@latest`); don't retry in a loop |
  851. | "No API permission for this account" (-104) | Account-level restriction by XHS (often on `search`), not a cookie/signing bug | Confirm `whoami` works, then use another account or the browser. Don't keep retrying |
  852. | "looks like a 小红书号 (Red ID)" | Passed the numeric Red ID instead of the user ID | Use the 24-char ID from `/user/profile/<id>`, or the full profile URL |
  853. ---
  854. ## Output Format Guidance
  855. When producing analysis reports, use these formats:
  856. **Data tables:** Markdown tables with exact field mappings. Always include the metric unit.
  857. **Heatmaps:** ASCII bar charts for cross-topic comparison:
  858. ```
  859. 职场 生活 教育 创业
  860. AI编程 ████ 8K ██ 2K ████ 12K ░░ 200
  861. Claude Code ██ 3K ░░ 100 ██ 4K █ 1K
  862. ```
  863. **Creator comparison:** Structured table with both quantitative metrics and qualitative style assessment.
  864. **Final reports:** Use this section order:
  865. 1. Market Overview (demand signals, content velocity)
  866. 2. Keyword Landscape (engagement matrix, opportunity tiers)
  867. 3. Cross-Topic Heatmap (topic × scene intersections)
  868. 4. Audience Persona (demographics, intent, preferences)
  869. 5. Competitive Landscape (creator profiles, strategy patterns)
  870. 6. Content Opportunities (tiered recommendations with data backing)
  871. 7. Content Ideas (specific hooks, angles, targets)
  872. ## Programmatic API
  873. ```typescript
  874. import { XhsClient } from "@lucasygu/redbook";
  875. import { loadCookies } from "@lucasygu/redbook/cookies";
  876. const cookies = await loadCookies("chrome");
  877. const client = new XhsClient(cookies);
  878. const results = await client.searchNotes("AI编程", 1, 20, "popular");
  879. const topics = await client.searchTopics("Claude Code");
  880. ```
  881. ## Requirements
  882. - Node.js >= 22
  883. - Logged into xiaohongshu.com in Chrome (or Safari/Firefox with `--cookie-source`)
  884. - macOS (cookie extraction uses native keychain access)
  885. - **For card rendering only:** `puppeteer-core` and `marked` (`npm install -g puppeteer-core marked`). Uses your existing Chrome — no additional browser download.
README.md · README · 742 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # redbook — 小红书命令行工具
  2. 小红书 CLI 工具:搜索笔记、阅读内容、分析博主、发布图文。使用浏览器 Cookie 认证,无需 API Key。
  3. [English](#english) | 中文
  4. > ### 最快上手方式
  5. >
  6. > 把这段话发给你的 AI 助手(Claude Code、Cursor、Codex、Windsurf、OpenClaw 等):
  7. >
  8. > **"帮我用 npm 安装 `@lucasygu/redbook` 这个小红书 CLI 工具,然后运行 `redbook whoami` 验证是否能正常连接。GitHub 地址:https://github.com/lucasygu/redbook"**
  9. >
  10. > OpenClaw 用户也可以直接:**`clawhub install redbook`**
  11. >
  12. > AI 会自动完成安装、验证连接、处理可能的 Cookie 问题。你只需要确保已在 Chrome 中登录 xiaohongshu.com。
  13. >
  14. > 安装完成后,试试:**"帮我分析'AI编程'这个话题在小红书上的竞争格局"** —— AI 会自动搜索关键词、分析互动数据、发现头部博主、给出内容建议。
  15. ## 安装
  16. ```bash
  17. npm install -g @lucasygu/redbook
  18. # 或通过 ClawHub(OpenClaw 生态)
  19. clawhub install redbook
  20. ```
  21. 需要 Node.js >= 22。支持 **macOS、Windows、Linux**。使用 Chrome 浏览器的 Cookie —— 请先在 Chrome 中登录 xiaohongshu.com。
  22. 安装后运行 `redbook whoami` 验证连接。CLI 会自动检测所有 Chrome 配置文件,找到你的小红书登录状态。
  23. - **macOS** —— 如果遇到钥匙串弹窗,请点击"始终允许"
  24. - **Windows** —— Chrome 127+ 使用了 App-Bound Encryption,CLI 会自动启动 Chrome headless 模式读取 Cookie(需要先关闭 Chrome)。如果自动提取失败,可以用 `--cookie-string` 手动传入
  25. ## 能做什么
  26. - **话题研究** —— 搜索关键词,分析哪些话题有流量、哪些是蓝海
  27. - **竞品分析** —— 找到头部博主,对比粉丝量、互动数据、内容风格
  28. - **爆款拆解** —— 分析爆款笔记的标题钩子、互动比例、评论主题
  29. - **爆款模板** —— 从多篇爆款笔记提取内容模板(标题结构、正文结构、钩子模式)
  30. - **限流检测** —— 检测笔记是否被隐形限流(通过创作者后台 API 的隐藏 level 字段)
  31. - **收藏专辑** —— 查看收藏专辑内容,分析专辑内的笔记
  32. - **收藏管理** —— 查看收藏列表、收藏/取消收藏笔记(支持自己和其他用户的公开收藏)
  33. - **评论管理** —— 发评论、回复评论、按策略批量回复(问题优先 / 高赞优先 / 未回复优先)
  34. - **图文卡片** —— Markdown 渲染为小红书风格的 PNG 图文卡片(7 种配色主题)
  35. - **内容策划** —— 基于数据发现内容机会,生成有数据支撑的选题建议
  36. - **受众洞察** —— 从互动信号推断目标用户画像
  37. 通过 AI 助手使用时,这些工作流可以自动串联完成。直接使用 CLI 时,每个命令也可以独立运行。
  38. ## 快速开始
  39. ```bash
  40. # 检查连接
  41. redbook whoami
  42. # 搜索笔记
  43. redbook search "AI编程" --sort popular
  44. # 阅读笔记
  45. redbook read https://www.xiaohongshu.com/explore/abc123
  46. # 获取评论
  47. redbook comments https://www.xiaohongshu.com/explore/abc123 --all
  48. # 浏览推荐页
  49. redbook feed
  50. # 查看博主信息
  51. redbook user "<profileUrl>"
  52. redbook user-posts "<profileUrl>"
  53. redbook account-report --file kos-accounts.txt --month 2026-07 --json
  54. # 搜索话题标签
  55. redbook topics "Claude Code"
  56. # 查看收藏(默认当前用户)
  57. redbook favorites --json
  58. redbook favorites <userId> --json --all
  59. # 收藏/取消收藏
  60. redbook collect "<noteUrl>"
  61. redbook uncollect "<noteUrl>"
  62. # 分析爆款笔记
  63. redbook analyze-viral https://www.xiaohongshu.com/explore/abc123
  64. # 从多篇爆款提取内容模板
  65. redbook viral-template "<url1>" "<url2>" "<url3>" --json
  66. # 发评论
  67. redbook comment "<noteUrl>" --content "写得好!"
  68. # 回复评论
  69. redbook reply "<noteUrl>" --comment-id "<id>" --content "感谢提问!"
  70. # 按策略批量回复(先预览再执行)
  71. redbook batch-reply "<noteUrl>" --strategy questions --dry-run
  72. redbook batch-reply "<noteUrl>" --strategy questions --template "感谢!{content}" --max 10
  73. # 查看收藏专辑
  74. redbook boards # 列出自己的专辑
  75. redbook boards <userId> # 列出他人的专辑
  76. redbook board "https://www.xiaohongshu.com/board/abc123"
  77. redbook board abc123 --json
  78. # 检测笔记限流状态
  79. redbook health
  80. redbook health --all --json
  81. # 将 Markdown 渲染为图文卡片(需要可选依赖)
  82. redbook render content.md --style xiaohongshu
  83. redbook render content.md --style dark --output-dir ./cards
  84. # 发布图文笔记
  85. redbook post --title "标题" --body "正文内容" --images cover.png
  86. redbook post --title "测试" --body "..." --images img.png --private
  87. ```
  88. ## 命令一览
  89. | 命令 | 说明 |
  90. |------|------|
  91. | `whoami` | 查看当前登录账号 |
  92. | `search <关键词>` | 搜索笔记 |
  93. | `read <url>` | 阅读单篇笔记 |
  94. | `comments <url>` | 获取笔记评论 |
  95. | `user <userId\|profileUrl>` | 查看用户资料 |
  96. | `user-posts <userId\|profileUrl>` | 列出用户所有笔记 |
  97. | `account-report <user...>` | 批量统计账号发帖和互动数据 |
  98. | `feed` | 获取推荐页内容 |
  99. | `post` | 发布图文笔记(易触发验证码,详见下方说明) |
  100. | `topics <关键词>` | 搜索话题/标签 |
  101. | `favorites [userId]` | 查看收藏笔记列表(默认当前用户) |
  102. | `collect <url>` | 收藏(书签)笔记 |
  103. | `uncollect <url>` | 取消收藏笔记 |
  104. | `health` | 检测笔记隐形限流(通过创作者后台隐藏 level 字段) |
  105. | `boards [userId]` | 列出用户的收藏专辑(默认当前用户) |
  106. | `board <url>` | 查看收藏专辑内容(接受专辑 URL 或 ID) |
  107. | `analyze-viral <url>` | 分析爆款笔记(钩子、互动、结构) |
  108. | `viral-template <url...>` | 从 1-3 篇爆款笔记提取内容模板 |
  109. | `comment <url>` | 发表评论 |
  110. | `reply <url>` | 回复指定评论 |
  111. | `batch-reply <url>` | 按策略批量回复评论(支持预览模式) |
  112. | `render <文件>` | Markdown 渲染为小红书图文卡片 PNG(需可选依赖) |
  113. | `auth` | 保存、导出、检查 Cookie 文件,适合云端/OpenClaw 使用 |
  114. ### 通用选项
  115. | 选项 | 说明 | 默认值 |
  116. |------|------|--------|
  117. | `--cookie-source <浏览器>` | Cookie 来源浏览器(chrome, safari, firefox) | `chrome` |
  118. | `--chrome-profile <名称>` | Chrome 配置文件目录名(如 "Profile 1"),默认自动检测 | 自动 |
  119. | `--cookie-string <cookies>` | 手动传入 Cookie 字符串:`"a1=值; web_session=值"`(从 Chrome DevTools 复制) | 无 |
  120. | `--platform <name>` | 强制后端:`xhs`(大陆)或 `rednote`(全球版),不传则自动检测 | 自动 |
  121. | `--global` | 强制使用全球版 RedNote 后端(等同 `--platform rednote`) | 无 |
  122. | `--json` | JSON 格式输出 | `false` |
  123. ### 保存 Cookie / 云端使用
  124. 如果在 OpenClaw、云服务器或 CI 里运行,不想每条命令都加 `--cookie-string`,可以把 Cookie 保存成文件。普通命令会按这个顺序读取 Cookie:`--cookie-string` → `REDBOOK_COOKIE_STRING` → `REDBOOK_COOKIE_FILE` → `~/.redbook/cookies.json` → 本机浏览器。
  125. ```bash
  126. # 本地浏览器已登录时,导出到默认路径 ~/.redbook/cookies.json
  127. redbook auth export
  128. # 或手动保存从 DevTools 复制的 Cookie 字符串
  129. redbook auth save --cookie-string "a1=值; web_session=值"
  130. # 查看保存位置和键名(不会打印 Cookie 值)
  131. redbook auth path
  132. redbook auth inspect
  133. # 上传 ~/.redbook/cookies.json 到云端后,普通命令会自动读取
  134. redbook whoami
  135. # 如果放在自定义路径
  136. export REDBOOK_COOKIE_FILE=/secure/path/redbook-cookies.json
  137. redbook search "AI编程" --json
  138. ```
  139. Cookie 文件是明文登录凭据,默认写入权限为 `0600`。不要提交到 Git,也不要贴到日志里。需要撤销时可以删除文件或执行 `redbook auth clear`,然后在浏览器里退出登录/重新登录刷新会话。
  140. ### 用户主页选项
  141. `user` 和 `user-posts` 可以接受完整主页 URL,例如 `https://www.xiaohongshu.com/user/profile/<id>?xsec_token=...&xsec_source=pc_search`。如果只有用户 ID,但接口返回 `code=-1`,请从搜索结果或浏览器地址栏复制带 `xsec_token` 的主页 URL,或手动传入:
  142. ```bash
  143. redbook user "<userId>" --xsec-token "<token>" --xsec-source pc_search --json
  144. redbook user-posts "<userId>" --xsec-token "<token>" --xsec-source pc_search --json
  145. ```
  146. ### 账号报表选项
  147. `account-report` 用于按账号 ID/主页 URL 批量统计发帖和互动数据,适合 KOS/KOC 账号巡检。文件中每行一个用户 ID 或带 `xsec_token` 的主页 URL,`#` 开头的行会被忽略。
  148. ```bash
  149. redbook account-report --file kos-accounts.txt --month 2026-07 --json
  150. redbook account-report "<profileUrl1>" "<profileUrl2>" --max-pages 2 --json
  151. ```
  152. 默认每个账号只拉第一页,结果里 `complete: false` 表示后面还有分页;需要完整历史时加 `--all`,或用 `--max-pages <n>` 控制每个账号最多拉几页。JSON 输出包含账号汇总和每篇笔记的点赞、评论、收藏、分享、总互动、发布时间和 `webUrl`。
  153. ### 搜索选项
  154. | 选项 | 说明 | 默认值 |
  155. |------|------|--------|
  156. | `--sort <类型>` | `general`(综合)、`popular`(热门)、`latest`(最新) | `general` |
  157. | `--type <类型>` | `all`(全部)、`video`(视频)、`image`(图文) | `all` |
  158. | `--page <页码>` | 页码 | `1` |
  159. ### 分析选项(analyze-viral / viral-template)
  160. | 选项 | 说明 | 默认值 |
  161. |------|------|--------|
  162. | `--comment-pages <n>` | 获取评论页数 | `3` |
  163. ### 批量回复选项(batch-reply)
  164. | 选项 | 说明 | 默认值 |
  165. |------|------|--------|
  166. | `--strategy <策略>` | `questions`(提问)、`top-engaged`(高赞)、`all-unanswered`(未回复) | `questions` |
  167. | `--template <模板>` | 回复模板,支持 `{author}`, `{content}` 占位符 | 无(预览模式) |
  168. | `--max <数量>` | 最大回复数(上限 30) | `10` |
  169. | `--delay <毫秒>` | 回复间隔(最小 180000ms/3分钟),自动添加 ±30% 随机抖动 | `300000`(5分钟) |
  170. | `--dry-run` | 只预览不发送 | 无模板时自动开启 |
  171. > ⚠️ **风控安全:** 小红书检测均匀时间间隔的自动化行为。回复间隔已自动添加 ±30% 随机抖动,避免触发机器人检测。建议每天每篇笔记最多批量回复 1-2 次。
  172. ### 渲染选项(render)
  173. 将 Markdown 文件渲染为小红书风格的 PNG 图文卡片。使用本机 Chrome 渲染,无需额外下载浏览器。
  174. | 选项 | 说明 | 默认值 |
  175. |------|------|--------|
  176. | `--style <名称>` | 配色:purple, xiaohongshu, mint, sunset, ocean, elegant, dark | `xiaohongshu` |
  177. | `--pagination <模式>` | 分页:auto(自动拆分)、separator(按 `---` 拆分) | `auto` |
  178. | `--output-dir <目录>` | 输出目录 | 与输入文件同目录 |
  179. | `--width <像素>` | 卡片宽度 | `1080` |
  180. | `--height <像素>` | 卡片高度 | `1440` |
  181. | `--dpr <倍率>` | 设备像素比 | `2` |
  182. **可选依赖:** 需要安装 `puppeteer-core` 和 `marked`:
  183. ```bash
  184. npm install -g puppeteer-core marked
  185. ```
  186. ### 发布选项(post)
  187. 发布功能目前**容易触发验证码**(type=124)。图片上传正常,但发布步骤经常被拦截。如需发布笔记,建议使用浏览器自动化。
  188. | 选项 | 说明 |
  189. |------|------|
  190. | `--title <标题>` | 笔记标题(必填) |
  191. | `--body <正文>` | 笔记正文(必填) |
  192. | `--images <路径...>` | 图片文件路径(必填) |
  193. | `--topic <关键词>` | 附加话题标签 |
  194. | `--private` | 发布为私密笔记 |
  195. ## 常见问题
  196. | 问题 | 解决方案 |
  197. |------|----------|
  198. | `No 'a1' cookie found` | 在 Chrome 中登录 xiaohongshu.com,然后重试 |
  199. | Windows 上 `-101` 错误 | Chrome 127+ 的 App-Bound Encryption 导致。先**关闭 Chrome**,再运行命令(CLI 会自动启动 Chrome headless 读取 Cookie)。如仍失败,用 `--cookie-string` 手动传入 |
  200. | Windows `--cookie-string` 用法 | Chrome 按 F12 → Application → Cookies → xiaohongshu.com,复制 `a1` 和 `web_session` 的值:`redbook whoami --cookie-string "a1=值; web_session=值"` |
  201. | macOS 钥匙串弹窗 | 输入密码后点击"始终允许",CLI 需要读取 Chrome 的加密 Cookie |
  202. | 多个 Chrome 配置文件 | CLI 自动扫描所有配置文件(macOS / Windows / Linux)。如需指定:`--chrome-profile "Profile 1"` |
  203. | 使用 Brave/Arc 等浏览器 | 尝试 `--cookie-source safari`,或在 Chrome 中登录 |
  204. | `user` / `user-posts` / `comments` 报 `code=-1`(HTTP 406) | 请求签名被拒绝,通常是小红书更新了网页签名。升级到最新版:`npm i -g @lucasygu/redbook@latest` |
  205. | `search` 报 `-104`(当前登录账号没有权限访问) | 小红书按账号限制接口权限,不是 Cookie 或签名问题。`whoami` / `feed` / `read` 正常、只有 `search` 报 `-104` 时,换一个账号或改用浏览器搜索。新号、未养号的账号,以及高频调用或触发过风控的账号都可能遇到 |
  206. | 用小红书号(纯数字)查用户失败 | `user` / `user-posts` 需要主页 URL 里 24 位的用户 ID(`/user/profile/<id>`),不是小红书号。直接传完整主页 URL 最稳妥 |
  207. ## 工作原理
  208. `redbook` 从 Chrome 读取小红书的登录 Cookie,然后用 TypeScript 实现的签名算法对 API 请求签名。
  209. **三层 Cookie 提取策略:**
  210. 1. **sweet-cookie**(快速路径)—— 直接读取 Chrome 的 SQLite 数据库,macOS 上即开即用
  211. 2. **CDP 回退**(Windows 自动触发)—— 启动 Chrome headless,通过 DevTools Protocol 读取 Cookie,绕过 Chrome 127+ 的 App-Bound Encryption
  212. 3. **`--cookie-string`**(手动兜底)—— 从 Chrome DevTools 复制 Cookie 字符串,任何平台通用
  213. **两套签名系统:**
  214. - **主 API**(`edith.xiaohongshu.com`)—— 读取:搜索、推荐页、笔记、评论、用户资料。使用 144 字节 x-s 签名(v4.3.1)
  215. - **创作者 API**(`creator.xiaohongshu.com`)—— 写入:上传图片、发布笔记。使用 AES-128-CBC 签名
  216. ## 分析模块(A-M)
  217. 内置 13 个可组合的分析模块,覆盖从关键词研究到内容发布的完整工作流:
  218. | 模块 | 功能 |
  219. |------|------|
  220. | A. 关键词矩阵 | 分析各关键词的互动天花板和竞争密度 |
  221. | B. 跨话题热力图 | 发现话题 × 场景的内容空白 |
  222. | C. 互动信号分析 | 分类内容类型(工具型 / 认知型 / 娱乐型) |
  223. | D. 博主画像 | 对比头部博主的粉丝、互动、风格 |
  224. | E. 内容形式分析 | 图文 vs. 视频的表现对比 |
  225. | F. 机会评分 | 按性价比排序关键词 |
  226. | G. 受众推断 | 从互动信号推断用户画像 |
  227. | H. 选题策划 | 数据驱动的内容创意 |
  228. | I. 评论运营 | 按策略筛选和批量回复评论 |
  229. | J. 爆款复刻 | 从爆款笔记提取内容模板 |
  230. | K. 互动自动化 | 组合 I + J 的自动化运营工作流 |
  231. | L. 图文卡片 | Markdown → 小红书风格 PNG 图文卡片(7 种配色) |
  232. | M. 限流检测 | 通过创作者后台隐藏 level 字段检测笔记限流状态 |
  233. 详见 [SKILL.md](SKILL.md) 的模块文档和组合工作流。
  234. ## AI 助手集成
  235. ### Claude Code
  236. 安装后自动注册为 Claude Code 技能。在 Claude Code 中使用 `/redbook` 命令:
  237. ```
  238. /redbook search "AI编程" # 搜索笔记
  239. /redbook read <url> # 阅读笔记
  240. /redbook user <profileUrl> # 查看博主
  241. /redbook analyze-viral <url> # 分析爆款笔记
  242. ```
  243. 你可以直接用自然语言下达复杂任务:
  244. - *"分析'AI编程'在小红书的竞争格局,找出蓝海关键词"*
  245. - *"对比这三个博主的内容策略和互动数据"*
  246. - *"拆解这篇爆款笔记,告诉我为什么火了"*
  247. - *"帮我回复这篇笔记下面的提问评论"*
  248. Claude 会自动组合多个命令,解析 JSON 数据,输出结构化分析报告。
  249. ### OpenClaw / ClawHub
  250. 官方支持 [OpenClaw](https://openclaw.ai) 和 [ClawHub](https://docs.openclaw.ai/tools/clawhub) 生态。通过 ClawHub 安装:
  251. ```bash
  252. clawhub install redbook
  253. ```
  254. 安装后在 OpenClaw 中可直接使用所有 `redbook` 命令。SKILL.md 同时兼容 Claude Code 和 OpenClaw 两个生态。
  255. ## 编程接口
  256. ```typescript
  257. import { XhsClient } from "@lucasygu/redbook";
  258. import { loadCookies } from "@lucasygu/redbook/cookies";
  259. const cookies = await loadCookies("chrome");
  260. const client = new XhsClient(cookies);
  261. const results = await client.searchNotes("AI编程", 1, 20, "popular");
  262. const topics = await client.searchTopics("Claude Code");
  263. ```
  264. ## 致谢
  265. 签名算法移植自以下开源项目(MIT 协议):
  266. - [Cloxl/xhshow](https://github.com/Cloxl/xhshow) — 主 API 签名(x-s, x-s-common)
  267. - [Spider_XHS](https://github.com/JoeanAmier/XHS-Downloader) — 创作者 API 签名
  268. - [ReaJason/xhs](https://github.com/ReaJason/xhs) — API 端点参考
  269. Cookie 提取使用 [@steipete/sweet-cookie](https://github.com/nicklockwood/sweet-cookie)。
  270. 限流检测灵感来自 [jzOcb/xhs-note-health-checker](https://github.com/jzOcb/xhs-note-health-checker)([@xxx111god](https://x.com/xxx111god) 发现了创作者后台 API 的隐藏 level 字段)。
  271. ## 免责声明
  272. 本工具使用非官方 API。小红书可能随时更改或封锁这些接口。请合理使用,风险自负。本项目与小红书无任何关联。
  273. ---
  274. <a id="english"></a>
  275. # English
  276. A fast CLI tool for [Xiaohongshu (小红书 / RED)](https://www.xiaohongshu.com) — search notes, read content, analyze creators, and publish posts. Uses browser cookie auth (no API key needed).
  277. > ### Easiest way to get started
  278. >
  279. > Paste this to your AI coding agent (Claude Code, Cursor, Codex, Windsurf, OpenClaw, etc.):
  280. >
  281. > **"Install the `@lucasygu/redbook` Xiaohongshu CLI tool via npm and run `redbook whoami` to verify it works. Repo: https://github.com/lucasygu/redbook"**
  282. >
  283. > OpenClaw users can also run: **`clawhub install redbook`**
  284. >
  285. > The agent will handle installation, verify the connection, and troubleshoot any cookie issues. Just make sure you're logged into xiaohongshu.com in Chrome first.
  286. >
  287. > Once installed, try: **"Analyze the competitive landscape for 'AI编程' on Xiaohongshu"** — the agent will search keywords, analyze engagement data, profile top creators, and suggest content opportunities.
  288. ## Install
  289. ```bash
  290. npm install -g @lucasygu/redbook
  291. # Or via ClawHub (OpenClaw ecosystem)
  292. clawhub install redbook
  293. ```
  294. Requires Node.js >= 22. Supports **macOS, Windows, and Linux**. Uses cookies from your Chrome browser session — you must be logged into xiaohongshu.com in Chrome.
  295. After installing, run `redbook whoami` to verify the connection. The CLI auto-detects all Chrome profiles to find your XHS session.
  296. - **macOS** — If Keychain prompt appears, click "Always Allow"
  297. - **Windows** — Chrome 127+ uses App-Bound Encryption. The CLI auto-launches Chrome headless to read cookies (close Chrome first). If auto-extraction fails, use `--cookie-string` as fallback
  298. ## What You Can Do
  299. - **Topic research** — Search keywords, analyze which topics have demand vs. gaps
  300. - **Competitive analysis** — Find top creators, compare followers, engagement, content style
  301. - **Viral note breakdown** — Analyze title hooks, engagement ratios, comment themes
  302. - **Viral templates** — Extract content templates from multiple viral notes (hook patterns, body structure, engagement profile)
  303. - **Rate-limit detection** — Detect hidden throttling on your notes via the creator API's secret `level` field
  304. - **Collection albums** — List notes in a collection album (收藏专辑) for batch analysis
  305. - **Favorites management** — List collected notes, collect/uncollect notes (own and other users' public collections)
  306. - **Comment management** — Post comments, reply to comments, batch-reply with strategies (questions / top-engaged / unanswered)
  307. - **Image cards** — Render markdown to styled PNG cards for XHS posts (7 color themes)
  308. - **Content planning** — Discover content opportunities with data-backed topic suggestions
  309. - **Audience insights** — Infer target audience from engagement signals
  310. When used through an AI agent, these workflows chain together automatically. Each CLI command also works standalone.
  311. ## Quick Start
  312. ```bash
  313. # Check connection
  314. redbook whoami
  315. # Search notes
  316. redbook search "AI编程" --sort popular
  317. # Read a note
  318. redbook read https://www.xiaohongshu.com/explore/abc123
  319. # Get comments
  320. redbook comments https://www.xiaohongshu.com/explore/abc123 --all
  321. # Browse your feed
  322. redbook feed
  323. # Look up a creator
  324. redbook user "<profileUrl>"
  325. redbook user-posts "<profileUrl>"
  326. redbook account-report --file kos-accounts.txt --month 2026-07 --json
  327. # Search hashtags
  328. redbook topics "Claude Code"
  329. # List favorites (defaults to current user)
  330. redbook favorites --json
  331. redbook favorites <userId> --json --all
  332. # Collect/uncollect notes
  333. redbook collect "<noteUrl>"
  334. redbook uncollect "<noteUrl>"
  335. # Analyze a viral note
  336. redbook analyze-viral https://www.xiaohongshu.com/explore/abc123
  337. # Extract content template from viral notes
  338. redbook viral-template "<url1>" "<url2>" "<url3>" --json
  339. # Post a comment
  340. redbook comment "<noteUrl>" --content "Great post!"
  341. # Reply to a comment
  342. redbook reply "<noteUrl>" --comment-id "<id>" --content "Thanks for asking!"
  343. # Batch reply with strategy (preview first, then execute)
  344. redbook batch-reply "<noteUrl>" --strategy questions --dry-run
  345. redbook batch-reply "<noteUrl>" --strategy questions --template "Thanks! {content}" --max 10
  346. # List user's collection boards
  347. redbook boards # your own boards
  348. redbook boards <userId> # another user's boards
  349. redbook board "https://www.xiaohongshu.com/board/abc123" --json
  350. # Check note health / rate-limiting status
  351. redbook health
  352. redbook health --all --json
  353. # Render markdown to image cards (requires optional deps)
  354. redbook render content.md --style xiaohongshu
  355. redbook render content.md --style dark --output-dir ./cards
  356. # Publish (requires image)
  357. redbook post --title "标题" --body "正文" --images cover.png
  358. redbook post --title "测试" --body "..." --images img.png --private
  359. ```
  360. ## Commands
  361. | Command | Description |
  362. |---------|-------------|
  363. | `whoami` | Check connection and show current user info |
  364. | `search <keyword>` | Search notes by keyword |
  365. | `read <url>` | Read a note by URL |
  366. | `comments <url>` | Get comments on a note |
  367. | `user <userId\|profileUrl>` | Get user profile info |
  368. | `user-posts <userId\|profileUrl>` | List a user's posted notes |
  369. | `account-report <user...>` | Batch summarize account posting and engagement |
  370. | `feed` | Get homepage feed |
  371. | `post` | Publish an image note (captcha-prone, see below) |
  372. | `topics <keyword>` | Search for topics/hashtags |
  373. | `favorites [userId]` | List collected/favorited notes (defaults to current user) |
  374. | `collect <url>` | Collect (bookmark) a note |
  375. | `uncollect <url>` | Remove a note from your collection |
  376. | `health` | Detect hidden rate-limiting on your notes (via creator API's secret level field) |
  377. | `boards [userId]` | List user's collection boards (defaults to current user) |
  378. | `board <url>` | List notes in a collection album (accepts board URL or ID) |
  379. | `analyze-viral <url>` | Analyze why a viral note works (hooks, engagement, structure) |
  380. | `viral-template <url...>` | Extract a content template from 1-3 viral notes |
  381. | `comment <url>` | Post a top-level comment |
  382. | `reply <url>` | Reply to a specific comment |
  383. | `batch-reply <url>` | Batch reply to comments with filtering strategy (supports dry-run) |
  384. | `render <file>` | Render markdown to styled PNG image cards for XHS posts (optional deps) |
  385. | `auth` | Save, export, inspect, and clear reusable cookie files for cloud/OpenClaw runs |
  386. ### Global Options
  387. | Option | Description | Default |
  388. |--------|-------------|---------|
  389. | `--cookie-source <browser>` | Browser to read cookies from (chrome, safari, firefox) | `chrome` |
  390. | `--chrome-profile <name>` | Chrome profile directory name (e.g., "Profile 1"). Auto-detected if omitted. | auto |
  391. | `--cookie-string <cookies>` | Manual cookie string: `"a1=VALUE; web_session=VALUE"` (from Chrome DevTools) | none |
  392. | `--platform <name>` | Force backend: `xhs` (mainland) or `rednote` (global). Omit to auto-detect. | auto |
  393. | `--global` | Force the global RedNote backend (= `--platform rednote`) | — |
  394. | `--json` | Output as JSON | `false` |
  395. > **Mainland 小红书 vs global RedNote — handled automatically.** These are two separate backends (`xiaohongshu.com` / `edith.xiaohongshu.com` vs `rednote.com` / `webapi.rednote.com`) with separate sessions and cookie domains; RedNote routes you to one by IP/region and you can only be signed into one at a time. The CLI **auto-detects which one you're logged into** (probing both cookie domains, verifying with one `/user/me` call when both have cookies, then caching the result in `~/.redbook/`), so you normally pass **no flag**. Use `--global` / `--platform xhs` only to force one.
  396. ### Saved Cookies / Cloud Use
  397. For OpenClaw, cloud servers, or CI, save cookies once so every command does not need `--cookie-string`. Normal commands resolve cookies in this order: `--cookie-string` → `REDBOOK_COOKIE_STRING` → `REDBOOK_COOKIE_FILE` → `~/.redbook/cookies.json` → local browser extraction.
  398. ```bash
  399. # Export from a logged-in local browser to ~/.redbook/cookies.json
  400. redbook auth export
  401. # Or save a cookie string copied from DevTools
  402. redbook auth save --cookie-string "a1=VALUE; web_session=VALUE"
  403. # Inspect path/keys without printing secret values
  404. redbook auth path
  405. redbook auth inspect
  406. # After uploading ~/.redbook/cookies.json to the cloud, commands auto-load it
  407. redbook whoami
  408. # For a custom location
  409. export REDBOOK_COOKIE_FILE=/secure/path/redbook-cookies.json
  410. redbook search "AI编程" --json
  411. ```
  412. The cookie file is a plaintext login credential and is written with `0600` permissions by default. Do not commit it or print it in logs. To revoke local reuse, remove it with `redbook auth clear`, then log out/in from the browser to rotate the session.
  413. ### User Profile Options
  414. `user` and `user-posts` accept full profile URLs such as `https://www.xiaohongshu.com/user/profile/<id>?xsec_token=...&xsec_source=pc_search`. If a bare user ID returns `code=-1`, copy a fresh profile URL from search results or the browser address bar, or pass the token explicitly:
  415. ```bash
  416. redbook user "<userId>" --xsec-token "<token>" --xsec-source pc_search --json
  417. redbook user-posts "<userId>" --xsec-token "<token>" --xsec-source pc_search --json
  418. ```
  419. ### Account Report Options
  420. `account-report` summarizes posting activity and engagement by account ID/profile URL, useful for KOS/KOC account checks. A file can contain one user ID or tokenized profile URL per line; blank lines and `#` comments are ignored.
  421. ```bash
  422. redbook account-report --file kos-accounts.txt --month 2026-07 --json
  423. redbook account-report "<profileUrl1>" "<profileUrl2>" --max-pages 2 --json
  424. ```
  425. By default it fetches the first page per account. `complete: false` means more pages exist; use `--all` for full history or `--max-pages <n>` to cap page reads. JSON includes account summaries plus per-note likes, comments, collects, shares, total engagement, publish time, and `webUrl`.
  426. ### Search Options
  427. | Option | Description | Default |
  428. |--------|-------------|---------|
  429. | `--sort <type>` | `general`, `popular`, `latest` | `general` |
  430. | `--type <type>` | `all`, `video`, `image` | `all` |
  431. | `--page <n>` | Page number | `1` |
  432. ### Analyze-Viral / Viral-Template Options
  433. | Option | Description | Default |
  434. |--------|-------------|---------|
  435. | `--comment-pages <n>` | Number of comment pages to fetch | `3` |
  436. ### Batch-Reply Options
  437. | Option | Description | Default |
  438. |--------|-------------|---------|
  439. | `--strategy <name>` | `questions`, `top-engaged`, `all-unanswered` | `questions` |
  440. | `--template <text>` | Reply template with `{author}`, `{content}` placeholders | none (dry-run) |
  441. | `--max <n>` | Max replies to send (hard cap: 30) | `10` |
  442. | `--delay <ms>` | Delay between replies in ms (min: 180000 / 3 min), ±30% random jitter applied automatically | `300000` (5 min) |
  443. | `--dry-run` | Preview candidates without posting | auto when no template |
  444. > ⚠️ **Rate limit safety:** XHS detects uniform timing patterns as bot behavior. Reply delays include ±30% random jitter automatically. Limit to 1-2 batch runs per note per day. See SKILL.md for full rate limit guidance.
  445. ### Render Options
  446. Render a markdown file to styled PNG image cards. Uses your existing Chrome for rendering — no browser download needed.
  447. | Option | Description | Default |
  448. |--------|-------------|---------|
  449. | `--style <name>` | Color style: purple, xiaohongshu, mint, sunset, ocean, elegant, dark | `xiaohongshu` |
  450. | `--pagination <mode>` | Pagination: auto, separator | `auto` |
  451. | `--output-dir <dir>` | Output directory | same as input |
  452. | `--width <n>` | Card width in pixels | `1080` |
  453. | `--height <n>` | Card height in pixels | `1440` |
  454. | `--dpr <n>` | Device pixel ratio | `2` |
  455. **Optional dependencies:** Requires `puppeteer-core` and `marked`:
  456. ```bash
  457. npm install -g puppeteer-core marked
  458. ```
  459. ### Post Options
  460. Publishing **frequently triggers captcha** (type=124). Image upload works, but the publish step is unreliable. For posting, consider using browser automation instead.
  461. | Option | Description |
  462. |--------|-------------|
  463. | `--title <title>` | Note title (required) |
  464. | `--body <body>` | Note body text (required) |
  465. | `--images <paths...>` | Image file paths (required) |
  466. | `--topic <keyword>` | Topic/hashtag to search and attach |
  467. | `--private` | Publish as private note |
  468. ## Troubleshooting
  469. | Problem | Solution |
  470. |---------|----------|
  471. | `No 'a1' cookie found` | Log into xiaohongshu.com in Chrome, then retry |
  472. | Windows `-101` error | Chrome 127+ App-Bound Encryption. **Close Chrome first**, then re-run (CLI auto-launches Chrome headless to read cookies). If it still fails, use `--cookie-string` |
  473. | Windows `--cookie-string` | Press F12 in Chrome → Application → Cookies → xiaohongshu.com. Copy `a1` and `web_session` values: `redbook whoami --cookie-string "a1=VALUE; web_session=VALUE"` |
  474. | macOS Keychain prompt | Enter your password and click "Always Allow" — the CLI needs to decrypt Chrome's cookies |
  475. | Multiple Chrome profiles | The CLI auto-scans all profiles (macOS / Windows / Linux). To pick one: `--chrome-profile "Profile 1"` |
  476. | Using Brave/Arc/other | Try `--cookie-source safari`, or log into xiaohongshu.com in Chrome |
  477. | `user` / `user-posts` / `comments` return `code=-1` (HTTP 406) | XHS rejected the request signature, usually after a web signing update. Upgrade: `npm i -g @lucasygu/redbook@latest` |
  478. | `search` returns `-104` ("no permission for this account") | An account-level API restriction from XHS, not a cookie or signing bug. If `whoami` / `feed` / `read` work but `search` returns `-104`, try another account or search in the browser. New or barely used accounts, and accounts that made heavy API calls or tripped risk control, can both hit this |
  479. | Looking up a user by Red ID (all digits) fails | `user` / `user-posts` need the 24-character user ID from the profile URL (`/user/profile/<id>`), not the 小红书号. Passing the full profile URL is safest |
  480. ## How It Works
  481. `redbook` reads your XHS session cookies from Chrome and signs API requests using a TypeScript port of the XHS signing algorithm.
  482. **Three-tier cookie extraction:**
  483. 1. **sweet-cookie** (fast path) — reads Chrome's SQLite cookie database directly. Works instantly on macOS
  484. 2. **CDP fallback** (auto on Windows) — launches Chrome headless and reads cookies via DevTools Protocol, bypassing Chrome 127+ App-Bound Encryption
  485. 3. **`--cookie-string`** (manual fallback) — paste cookie values from Chrome DevTools. Works on any platform
  486. **Two signing systems:**
  487. - **Main API** (`edith.xiaohongshu.com`) — for reading: search, feed, notes, comments, user profiles. Uses x-s signature with 144-byte payload (v4.3.1).
  488. - **Creator API** (`creator.xiaohongshu.com`) — for writing: upload images, publish notes. Uses simpler AES-128-CBC signing.
  489. ## Analysis Modules (A-M)
  490. 13 composable analysis modules covering the full workflow from keyword research to content publishing:
  491. | Module | Purpose |
  492. |--------|---------|
  493. | A. Keyword Matrix | Analyze engagement ceiling and competition density per keyword |
  494. | B. Cross-Topic Heatmap | Find topic × scene content gaps |
  495. | C. Engagement Signals | Classify content type (reference / insight / entertainment) |
  496. | D. Creator Profiling | Compare top creators' followers, engagement, style |
  497. | E. Content Form | Image-text vs. video performance comparison |
  498. | F. Opportunity Scoring | Rank keywords by effort-to-reward ratio |
  499. | G. Audience Inference | Infer user persona from engagement signals |
  500. | H. Content Brainstorm | Data-backed content ideas |
  501. | I. Comment Operations | Filter and batch-reply to comments by strategy |
  502. | J. Viral Replication | Extract content templates from viral notes |
  503. | K. Engagement Automation | Combined I + J workflow for operations |
  504. | L. Card Rendering | Markdown → styled PNG image cards for XHS posts (7 color themes) |
  505. | M. Note Health Check | Detect hidden rate-limiting via creator API's secret level field |
  506. See [SKILL.md](SKILL.md) for full module documentation and composed workflows.
  507. ## AI Agent Integration
  508. ### Claude Code
  509. Installs automatically as a Claude Code skill. Use `/redbook` in Claude Code:
  510. ```
  511. /redbook search "AI编程" # Search notes
  512. /redbook read <url> # Read a note
  513. /redbook user <profileUrl> # Creator profile
  514. /redbook analyze-viral <url> # Analyze a viral note
  515. ```
  516. You can give natural language instructions for complex tasks:
  517. - *"Analyze the competitive landscape for 'AI编程' on Xiaohongshu and find blue ocean keywords"*
  518. - *"Compare the content strategies of these three creators"*
  519. - *"Break down this viral note and tell me why it worked"*
  520. - *"Reply to the question comments on my latest post"*
  521. Claude will automatically combine multiple commands, parse JSON data, and produce structured analysis reports.
  522. ### OpenClaw / ClawHub
  523. Officially supports [OpenClaw](https://openclaw.ai) and [ClawHub](https://docs.openclaw.ai/tools/clawhub). Install via ClawHub:
  524. ```bash
  525. clawhub install redbook
  526. ```
  527. All `redbook` commands are available in OpenClaw after installation. The SKILL.md is compatible with both Claude Code and OpenClaw ecosystems.
  528. ## Programmatic Usage
  529. ```typescript
  530. import { XhsClient } from "@lucasygu/redbook";
  531. import { loadCookies } from "@lucasygu/redbook/cookies";
  532. const cookies = await loadCookies("chrome");
  533. const client = new XhsClient(cookies);
  534. const results = await client.searchNotes("AI编程", 1, 20, "popular");
  535. const topics = await client.searchTopics("Claude Code");
  536. ```
  537. ## Acknowledgments
  538. Signing algorithms ported from these open-source projects (MIT licensed):
  539. - [Cloxl/xhshow](https://github.com/Cloxl/xhshow) — Main API signing (x-s, x-s-common)
  540. - [Spider_XHS](https://github.com/JoeanAmier/XHS-Downloader) — Creator API signing
  541. - [ReaJason/xhs](https://github.com/ReaJason/xhs) — API endpoint reference
  542. Cookie extraction via [@steipete/sweet-cookie](https://github.com/nicklockwood/sweet-cookie).
  543. Rate-limit detection inspired by [jzOcb/xhs-note-health-checker](https://github.com/jzOcb/xhs-note-health-checker) ([@xxx111god](https://x.com/xxx111god) discovered the hidden `level` field in the creator backend API).
  544. ## Disclaimer
  545. This tool uses unofficial/private APIs. Xiaohongshu may change or block these APIs at any time. Use responsibly and at your own risk. This project is not affiliated with Xiaohongshu.
  546. ## License
  547. MIT

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.