Skip to content

ZJU-REAL/Easel / skills/builtin/skill-xhs-analyzer

redbook

Flagged

小红书内容分析:搜索笔记、拉取互动数据、分析爆款规律、创作者画像、限流检测,支持 CLI 自动化操作。 当用户说"小红书数据分析""小红书爆款分析""笔记数据""小红书限流检测""小红书创作者画像""分析小红书账号"时使用。 发布与日常互动运营请用 skill-xhs-publisher。

FileKindSize
.github/workflows/npm-publish.ymlconfig3.8 KB
EASEL-META.mdmarkdown2.1 KB
SKILL.mdskill md5.2 KB
package-lock.jsonmanifest36.6 KB
package.jsonmanifest1.6 KB
references/commands.mdmarkdown4.4 KB
references/modules.mdmarkdown6.2 KB
references/platform-signals.mdmarkdown1.7 KB
references/research-loop.mdmarkdown8.2 KB
references/technical-reference.mdmarkdown3.8 KB
scripts/postinstall.jsscript4.5 KB
scripts/preuninstall.jsscript1.4 KB
social-preview.htmlother5.1 KB
social-preview.pngbinary261.4 KB
src/cli.tsscript76.8 KB
src/lib/analyze.tsscript20.0 KB
src/lib/cdp-cookies.tsscript13.1 KB
src/lib/client.tsscript22.2 KB
src/lib/cookies.tsscript13.3 KB
src/lib/creator-signing.tsscript1.8 KB
src/lib/detect.tsscript6.6 KB
src/lib/fingerprint-data.tsscript2.3 KB
src/lib/health.tsscript5.5 KB
src/lib/platform.tsscript2.7 KB
src/lib/render.tsscript19.5 KB
src/lib/reply-strategy.tsscript6.0 KB
src/lib/signing.tsscript21.1 KB
src/lib/template.tsscript8.0 KB
src/lib/url.tsscript1.8 KB
tsconfig.jsonconfig458 B

src/lib/reply-strategy.ts

View on GitHub
/**
 * Batch reply strategy — deterministic comment filtering and reply orchestration.
 *
 * Selects which comments deserve a reply based on strategy, expands templates,
 * and executes replies with rate limiting and safety guards.
 */

import { QUESTION_PATTERN } from "./analyze.js";
import { XhsClient, NeedVerifyError } from "./client.js";

// ─── Interfaces ─────────────────────────────────────────────────────────────

export interface ReplyCandidate {
  commentId: string;
  author: string;
  content: string;
  likes: number;
  hasSubReplies: boolean;
  isQuestion: boolean;
  matchedStrategy: string;
}

export interface ReplyPlan {
  noteId: string;
  strategy: string;
  candidates: ReplyCandidate[];
  skipped: number;
  totalComments: number;
}

export interface ReplyResult {
  commentId: string;
  author: string;
  success: boolean;
  error?: string;
}

export type StrategyName = "questions" | "top-engaged" | "all-unanswered";

// ─── Constants ──────────────────────────────────────────────────────────────
// Based on XHS risk control research: 3+ minute intervals between replies,
// uniform timing patterns trigger bot detection.

const MAX_REPLIES_HARD_CAP = 30;
const MIN_DELAY_MS = 180_000; // 3 minutes — XHS minimum safe interval
const DEFAULT_DELAY_MS = 300_000; // 5 minutes — recommended safe interval
const JITTER_FACTOR = 0.3; // ±30% random variation to avoid uniform patterns

// ─── Strategy Selection ─────────────────────────────────────────────────────

export function selectCandidates(
  comments: Array<Record<string, unknown>>,
  strategy: StrategyName,
  max: number
): ReplyPlan {
  const cap = Math.min(max, MAX_REPLIES_HARD_CAP);
  const total = comments.length;

  const mapped = comments.map((c) => {
    const userInfo = (c.user_info ?? {}) as Record<string, unknown>;
    const content = String(c.content ?? "");
    const likes = toNum(c.like_count);
    const subCount = toNum(c.sub_comment_count);
    return {
      commentId: String(c.id ?? c.comment_id ?? ""),
      author: String(userInfo.nickname ?? ""),
      content,
      likes,
      hasSubReplies: subCount > 0,
      isQuestion: QUESTION_PATTERN.test(content),
      matchedStrategy: strategy,
    };
  });

  let selected: ReplyCandidate[];

  switch (strategy) {
    case "questions":
      selected = mapped.filter((c) => c.isQuestion);
      break;

    case "top-engaged":
      selected = [...mapped].sort((a, b) => b.likes - a.likes);
      break;

    case "all-unanswered":
      selected = mapped.filter((c) => !c.hasSubReplies);
      break;

    default:
      selected = mapped;
  }

  const candidates = selected.slice(0, cap);
  return {
    noteId: "",
    strategy,
    candidates,
    skipped: total - candidates.length,
    totalComments: total,
  };
}

// ─── Template Expansion ─────────────────────────────────────────────────────

export function expandTemplate(
  template: string,
  candidate: ReplyCandidate,
  context: { noteTitle?: string }
): string {
  return template
    .replace(/\{author\}/g, candidate.author)
    .replace(/\{content\}/g, candidate.content)
    .replace(/\{noteTitle\}/g, context.noteTitle ?? "");
}

// ─── Execution ──────────────────────────────────────────────────────────────

export async function executeReplies(
  client: XhsClient,
  noteId: string,
  candidates: ReplyCandidate[],
  template: string,
  delayMs: number,
  context: { noteTitle?: string }
): Promise<ReplyResult[]> {
  const delay = Math.max(delayMs, MIN_DELAY_MS);
  const results: ReplyResult[] = [];

  for (const candidate of candidates) {
    const replyText = expandTemplate(template, candidate, context);

    try {
      await client.replyComment(noteId, candidate.commentId, replyText);
      results.push({ commentId: candidate.commentId, author: candidate.author, success: true });
    } catch (err) {
      if (err instanceof NeedVerifyError) {
        results.push({
          commentId: candidate.commentId,
          author: candidate.author,
          success: false,
          error: "Captcha triggered — stopping batch",
        });
        break; // Stop immediately on captcha
      }
      results.push({
        commentId: candidate.commentId,
        author: candidate.author,
        success: false,
        error: err instanceof Error ? err.message : "Unknown error",
      });
    }

    // Rate limit between replies with jitter (skip after last)
    if (candidate !== candidates[candidates.length - 1]) {
      const jittered = addJitter(delay, JITTER_FACTOR);
      await sleep(jittered);
    }
  }

  return results;
}

// ─── Helpers ────────────────────────────────────────────────────────────────

function toNum(v: unknown): number {
  if (typeof v === "number") return v;
  const s = String(v ?? "0").trim();
  if (s.endsWith("万")) return Math.round(parseFloat(s.slice(0, -1)) * 10000);
  if (s.endsWith("亿")) return Math.round(parseFloat(s.slice(0, -1)) * 100000000);
  return parseInt(s, 10) || 0;
}

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function addJitter(ms: number, factor: number): number {
  const offset = ms * factor * (2 * Math.random() - 1); // ±factor
  return Math.max(MIN_DELAY_MS, Math.round(ms + offset));
}

export { DEFAULT_DELAY_MS, MIN_DELAY_MS, MAX_REPLIES_HARD_CAP };
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall