> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mavera.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Competitor Sentiment Tracking

> Search Reddit for competitor mentions across subreddits, enrich with comments, and produce structured sentiment breakdowns via Mave

## Scenario

Competitors are discussed daily on Reddit. This job searches for mentions across subreddits, feeds text into Mavera Chat, and produces a structured sentiment breakdown: positive, negative, neutral, and opportunity. Run weekly.

## Architecture

```mermaid theme={"dark"}
flowchart LR
    A["Reddit GET /r/{sub}/search?q={competitor}"] --> B["Aggregate mentions"]
    B --> C["Mavera POST /mave/chat"]
    C --> D["Sentiment map"]
```

## Code

<CodeGroup>
  ```python Python theme={"dark"}
  import os, requests, time

  # --- Auth setup same as Job 1 ---

  COMPETITORS = ["Competitor A", "Competitor B", "Competitor C"]
  SUBS = ["SaaS", "startups", "productivity", "marketing"]

  # 1. Search each competitor across subreddits
  all_results = []
  for comp in COMPETITORS:
      for sub in SUBS:
          r = requests.get(f"{RD}/r/{sub}/search", headers=RD_H,
              params={"q": comp, "restrict_sr": "true", "sort": "relevance", "t": "month", "limit": 10, "raw_json": 1})
          if r.status_code == 429: time.sleep(int(r.headers.get("X-Ratelimit-Reset", 60))); continue
          if not r.ok: continue
          for p in r.json().get("data",{}).get("children",[]):
              d = p["data"]
              all_results.append({"competitor": comp, "subreddit": sub, "title": d.get("title",""),
                  "text": d.get("selftext","")[:400], "score": d.get("score",0), "post_id": d.get("id","")})
          time.sleep(0.7)

  # 2. Enrich top posts with comments
  enriched = []
  for item in sorted(all_results, key=lambda x: -x["score"])[:20]:
      enriched.append(f"[/r/{item['subreddit']}] {item['competitor']} | score:{item['score']}\n{item['title']}\n{item['text'][:250]}")
      cr = requests.get(f"{RD}/comments/{item['post_id']}", headers=RD_H,
          params={"limit": 5, "depth": 1, "sort": "top", "raw_json": 1})
      if cr.ok and len(cr.json()) > 1:
          for c in cr.json()[1]["data"]["children"]:
              body = c.get("data",{}).get("body","")
              if body and body not in ("[removed]","[deleted]"):
                  enriched.append(f"  COMMENT ({item['competitor']}): {body[:250]}")
      time.sleep(0.7)

  # 3. Structured analysis
  analysis = requests.post(f"{MV_BASE}/mave/chat", headers=MV_H, json={
      "message": f"Competitive intelligence analyst: analyze Reddit mentions.\n\nCOMPETITORS: {', '.join(COMPETITORS)}\n\nDATA:\n"
          + "\n".join(enriched[:30])
          + "\n\nFor EACH competitor: Sentiment breakdown (positive/negative/neutral with quotes), Top themes, Opportunities for us, Sentiment trend. End with comparative ranking."
  }).json()

  print(f"Collected {len(all_results)} mentions across {len(COMPETITORS)} competitors")
  print(analysis.get("content", "")[:2000])
  ```

  ```javascript JavaScript theme={"dark"}
  // --- Auth setup same as Job 1 ---

  const COMPETITORS = ["Competitor A", "Competitor B", "Competitor C"];
  const SUBS = ["SaaS", "startups", "productivity", "marketing"];

  // 1. Search
  const allResults = [];
  for (const comp of COMPETITORS) {
    for (const sub of SUBS) {
      const r = await fetch(
        `${RD}/r/${sub}/search?q=${encodeURIComponent(comp)}&restrict_sr=true&sort=relevance&t=month&limit=10&raw_json=1`,
        { headers: RD_H });
      if (r.status === 429) { await new Promise(res => setTimeout(res, 60000)); continue; }
      if (!r.ok) continue;
      for (const p of (await r.json()).data?.children || []) {
        const d = p.data;
        allResults.push({ competitor: comp, subreddit: sub, title: d.title||"",
          text: (d.selftext||"").slice(0,400), score: d.score||0, post_id: d.id||"" });
      }
      await new Promise(r => setTimeout(r, 700));
    }
  }

  // 2. Enrich + analyze
  const enriched = [];
  for (const item of allResults.sort((a,b) => b.score - a.score).slice(0, 20)) {
    enriched.push(`[/r/${item.subreddit}] ${item.competitor} | score:${item.score}\n${item.title}\n${item.text.slice(0,250)}`);
    const cr = await fetch(`${RD}/comments/${item.post_id}?limit=5&depth=1&sort=top&raw_json=1`, { headers: RD_H });
    if (cr.ok) for (const c of ((await cr.json())[1]?.data?.children || [])) {
      const body = c.data?.body || "";
      if (body && body !== "[removed]" && body !== "[deleted]")
        enriched.push(`  COMMENT (${item.competitor}): ${body.slice(0,250)}`);
    }
    await new Promise(r => setTimeout(r, 700));
  }

  const analysis = await fetch(`${MV_BASE}/mave/chat`, { method: "POST", headers: MV_H,
    body: JSON.stringify({ message: `Analyze Reddit competitor mentions.\n\nCOMPETITORS: ${COMPETITORS.join(", ")}\n\nDATA:\n${enriched.slice(0,30).join("\n")}\n\nFor each: sentiment breakdown, themes, opportunities, trend. Comparative ranking.` }),
  }).then(r => r.json());

  console.log(`Collected ${allResults.length} mentions`);
  console.log((analysis.content || "").slice(0, 2000));
  ```
</CodeGroup>

## Example Output

```text theme={"dark"}
Collected 87 mentions across 3 competitors

## Competitor A — Mixed-Negative
- Positive (34%): Onboarding, integrations, support
- Negative (41%): Pricing ("doubled overnight"), performance
- Opportunity: Pricing transparency + dashboard speed

## Competitor B — Positive
- Positive (62%): UX, mobile, free tier
- Negative (18%): "Outgrows you — no enterprise features"
- Opportunity: Enterprise gap we can fill
```

## Error Handling

<AccordionGroup>
  <Accordion title="Name disambiguation">Use quoted search or add product-category terms for precision.</Accordion>
  <Accordion title="Rate limiting">N × M API calls. 700ms delays keep you under 100 req/min.</Accordion>
</AccordionGroup>

***

<CardGroup cols={2}>
  <Card title="Reddit Integration" icon="arrow-left" href="/integrations/reddit" />

  <Card title="Mave Agent" icon="brain" href="/features/mave-agent" />
</CardGroup>
