@clawhub-phheng-d84d09b8c3
E-commerce growth strategy advisor. Diagnoses current business health using unit economics (CAC, LTV, AOV, contribution margin), identifies the highest-impac...
---
name: ecommerce-growth-strategy
description: "E-commerce growth strategy advisor. Diagnoses current business health using unit economics (CAC, LTV, AOV, contribution margin), identifies the highest-impact growth opportunities across 5 levers (traffic, conversion, AOV, retention, expansion), and builds a prioritized 90-day growth roadmap. Uses the Ansoff Matrix adapted for e-commerce to evaluate market penetration, channel expansion, product expansion, and new market entry. Includes multichannel readiness assessment (Amazon, Walmart, TikTok Shop, Etsy, DTC/Shopify/Shopify) and product line expansion analysis. No API key required. Use when: (1) planning next phase of e-commerce growth, (2) deciding whether to expand to new channels or products, (3) diagnosing why growth has stalled, (4) prioritizing what to fix or build next."
metadata:
nexscope:
emoji: "🚀"
category: ecommerce
---
# E-Commerce Growth Strategy 🚀
Your strategic growth advisor for e-commerce. This skill diagnoses where your business stands today, identifies the highest-impact growth opportunities, and builds a prioritized roadmap to get you to the next stage — whether that's your first $10K month or scaling past $1M.
This is the strategy layer above marketing execution. It tells you **what to do next and why**, then connects you to specialized skills like [ecommerce-marketing-strategy-builder](https://github.com/nexscope-ai/eCommerce-Skills/tree/main/ecommerce-marketing-strategy-builder) for **how to do it**.
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-marketing-strategy-builder -g
```
**Supported platforms:** Shopify, WooCommerce, Amazon, Walmart, TikTok Shop, Etsy, eBay, BigCommerce, and multi-channel sellers.
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
## Install
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-growth-strategy -g
```
## Usage
```
I sell pet clothes on Shopify, doing about $8K/month. Margin is 65%. I want to hit
$20K/month in 6 months. What should I focus on?
```
```
We're an Amazon seller doing $50K/month in kitchen gadgets. Should we expand to
Walmart or TikTok Shop? Or launch new products first?
```
```
My Etsy jewelry shop makes $3K/month but growth has stalled. I have 2,000 email
subscribers and 5K Instagram followers. What's my best path to $10K/month?
```
## Capabilities
- Business health diagnosis using unit economics (CAC, LTV, LTV:CAC ratio, contribution margin, payback period, AOV)
- Growth opportunity identification across 5 levers: traffic, conversion, AOV, retention, expansion
- Ansoff Matrix adapted for e-commerce — evaluates 4 growth paths: penetrate, expand channels, expand products, enter new markets
- Growth Opportunity Matrix — maps each opportunity by impact vs effort for prioritization
- Multichannel readiness assessment — when and where to expand (Amazon, Walmart, TikTok Shop, Etsy, DTC/Shopify/Shopify)
- Product line expansion analysis — adjacent categories, timing, launch strategy
- Retention and LTV growth strategies — RFM segmentation, repeat purchase drivers, loyalty tactics
- Conversion rate optimization priorities — identifies biggest conversion leaks
- Prioritized 90-day growth roadmap with specific milestones and KPIs
- Cross-skill linking to specialized execution skills (PPC, email, marketing strategy, content)
---
## How This Skill Works
**Step 1: Collect information.** Extract from the user's initial message:
- Product / category
- Current sales platform(s)
- Current monthly revenue (or stage)
- Growth goal or target
- Any specific context (problems, constraints, opportunities mentioned)
**Step 2: Ask one follow-up with all remaining questions.** Use multiple-choice format:
```
Great — [acknowledge what they told you]. To build your growth strategy I need a few more details:
1. Business stage?
a) Pre-launch — haven't sold yet
b) Early — under $10K/mo
c) Growing — $10K-50K/mo
d) Scaling — $50K-200K/mo
e) Established — $200K+/mo
2. Your main growth bottleneck right now?
a) Not enough traffic / visitors
b) Traffic but low conversion (people visit but don't buy)
c) One-time buyers — they buy once and never come back
d) Low average order value — they buy but spend little
e) Maxed out on current platform — need to expand
f) Not sure — diagnose for me
g) Other: ___________
3. Current marketing channels? (check all that apply)
a) Paid ads (Google, Meta, TikTok)
b) Organic social media
c) SEO / organic search
d) Email marketing
e) Influencer / affiliate
f) None — haven't started marketing
g) Other: ___________
4. Growth direction preference?
a) Optimize what I have (squeeze more from current setup)
b) Expand to new sales channels (Amazon, Walmart, TikTok Shop, etc.)
c) Launch new products / expand product line
d) Enter new markets / countries
e) All of the above — tell me what's best
f) Other: ___________
5. Monthly marketing budget?
a) Under $500
b) $500-2,000
c) $2,000-10,000
d) $10,000+
e) Prefer not to say
6. Key numbers (share what you know — skip what you don't):
- Average order value (AOV): $___
- Product cost / margin: ___%
- Repeat purchase rate: ___%
- Email list size: ___
- Monthly website visitors: ___
- Current conversion rate: ___%
7. Competitors? (names or URLs, or skip)
Reply like: "1c 2f 3abd 4e 5c 6 AOV $35, margin 60%, repeat 15%, list 2000, visitors 8000, conv 2.5% 7 skip"
```
**Step 3: Diagnose current state.** Using the numbers provided (or estimating with ⚠️ where missing):
Calculate and present:
- **Unit Economics Health Check:**
- CAC (if calculable from budget + new customers)
- LTV = AOV × Purchase Frequency × Customer Lifespan × Gross Margin
- LTV:CAC Ratio — compare against benchmarks (see below)
- Contribution Margin = Revenue - COGS - Shipping - Processing - Packaging - Returns
- Payback Period = CAC ÷ (AOV × Margin)
- **The Growth Equation:**
Revenue = Traffic × Conversion Rate × AOV × Purchase Frequency
Show which variable has the biggest room for improvement based on their numbers vs benchmarks. A 20% improvement in conversion is often worth more than a 20% increase in traffic.
**Step 4: Map growth opportunities.** Using the E-Commerce Ansoff Matrix:
| | Existing Products | New Products |
|---|---|---|
| **Existing Markets** | 🟢 **Penetrate** (optimize conversion, increase AOV, improve retention) | 🟡 **Product Expansion** (adjacent categories, bundles, subscriptions) |
| **New Markets** | 🟡 **Channel Expansion** (new platforms, new countries) | 🔴 **Diversification** (new products in new markets — highest risk) |
For each quadrant, identify 2-3 specific opportunities based on their business. Then rank every opportunity on a **Growth Opportunity Matrix**:
| Opportunity | Impact (1-5) | Effort (1-5) | Priority |
|-------------|:---:|:---:|:---:|
| e.g., Add email abandoned cart flow | 5 | 2 | 🔴 High |
| e.g., Expand to Amazon | 4 | 4 | 🟡 Medium |
| e.g., Launch subscription model | 3 | 5 | 🟢 Low |
Priority = High Impact + Low Effort first. Always.
**Step 5: Analyze each priority opportunity in detail.**
For each High and Medium priority opportunity, provide:
- What it is and why it matters for this business
- Specific tactics to execute
- Expected impact (revenue, conversion, AOV improvement)
- Timeline and resources needed
- Risks and how to mitigate them
- Link to relevant Nexscope skill for detailed execution
**Step 6: Build the 90-day growth roadmap.**
Break into 3 phases:
- **Days 1-30: Foundation** — fix what's broken, capture quick wins
- **Days 31-60: Build** — implement medium-effort, high-impact initiatives
- **Days 61-90: Scale** — double down on what's working, launch expansion experiments
Each phase has:
- Specific actions with deadlines
- Milestones to hit
- KPIs to track
- Decision points ("If X happens, do Y. If not, do Z.")
**Step 7: Set KPIs and tracking plan.**
Define targets for each key metric based on their current baseline + realistic improvement rates.
---
## The 5 Growth Levers
Every e-commerce business grows through the same 5 levers. The question is which lever gives you the biggest return right now.
### Lever 1: Traffic / Acquisition
**What:** Get more potential buyers to your store
**When to prioritize:** Conversion rate is already decent (>2%) but visitor count is low
**Tactics:**
- SEO / content marketing (highest ROI long-term, 3-6 months to see results)
- Paid ads — Google Shopping, Meta, TikTok (immediate but costs money)
- Influencer/affiliate partnerships
- Social media organic
- Marketplace expansion (Amazon, Walmart = built-in traffic)
**Key metric:** Cost per visitor, CAC by channel
**Benchmark:** Average ecommerce CAC varies by category — beauty $20-60, apparel $30-80, food $15-50, supplements $40-100, home goods $30-70 *(Finsi.ai 2026)*
### Lever 2: Conversion Rate Optimization (CRO)
**What:** Turn more visitors into buyers
**When to prioritize:** Getting traffic but conversion is below benchmark
**Tactics:**
- Fix mobile experience (60%+ of traffic is mobile)
- Simplify checkout (guest checkout, fewer steps)
- Add social proof (reviews, UGC, trust badges)
- Improve product pages (better photos, clearer descriptions, size guides)
- Reduce friction (free shipping threshold, clear return policy)
- Exit-intent offers
**Key metric:** Conversion rate (sessions to orders)
**Benchmarks:** Average ecommerce conversion rate ~1.5-3% depending on source. By device: desktop ~2.8%, mobile ~2.8%. By traffic source: email 5.3%, organic search 2.8%, paid search 1.9%, social <1% *(Red Stag Fulfillment 2026, Smart Insights 2025)*
### Lever 3: Average Order Value (AOV)
**What:** Get each buyer to spend more per transaction
**When to prioritize:** Good traffic + good conversion, but revenue feels low relative to order volume
**Tactics:**
- Bundling and kits
- Free shipping threshold (set 20-30% above current AOV)
- Upsells and cross-sells (on product page, in cart, post-purchase)
- Tiered pricing (buy 2 get 10% off, buy 3 get 20% off)
- Premium product tier
**Key metric:** AOV
**Impact:** A 15% increase in AOV with same traffic = 15% more revenue at zero acquisition cost
### Lever 4: Retention / Purchase Frequency
**What:** Get existing customers to buy again (and again)
**When to prioritize:** You're acquiring customers but they buy once and disappear
**Tactics:**
- Email marketing automation (welcome, post-purchase, win-back flows)
- Loyalty/rewards program
- Subscription model (for consumables)
- SMS marketing
- Personalized product recommendations
- Community building (social, UGC, exclusive groups)
**Key metrics:** Repeat purchase rate, purchase frequency, customer lifespan
**Benchmarks:**
- Acquiring a new customer costs 5-25× more than retaining one *(Harvard Business Review)*
- 5% increase in retention → 25-95% more profit *(HBR)*
- Existing customers are 50% more likely to try new products, spend 31% more *(Forbes)*
- Average ecommerce repeat purchase rate: ~28% *(Omnisend)*
### Lever 5: Expansion (Channels, Products, Markets)
**What:** Grow beyond current boundaries
**When to prioritize:** Current channel/product is profitable and operationally stable. Don't expand from a broken base
**Types:**
- **Channel expansion:** Shopify → Amazon, Amazon → Walmart, any → TikTok Shop
- **Product expansion:** Adjacent categories, variations, bundles, subscriptions
- **Market expansion:** US → EU, US → UK, domestic → international
**Key metric:** Revenue from new channel/product as % of total, without cannibalizing existing
---
## Multichannel Readiness Assessment
When a user asks about expanding to a new channel, evaluate readiness:
### Readiness Checklist (must be YES on all before expanding)
- [ ] Current channel is profitable (positive contribution margin)
- [ ] Operations can handle +30% order volume without breaking
- [ ] Have systems for inventory sync across channels
- [ ] Have bandwidth (team or budget) to manage another channel
- [ ] Understand the new channel's fee structure and its impact on margins
### Channel-Specific Assessment
| Channel | Best For | Audience | Fees | Key Requirement |
|---------|---------|---------|------|-----------------|
| **Amazon** | Established products with search demand | Broadest reach, high purchase intent | 15% referral + FBA fees | Competitive pricing, strong reviews |
| **Walmart** | Brands already on Amazon, price-competitive | Growing, value-conscious | 6-20% referral | Brand registry, competitive pricing |
| **TikTok Shop** | Visual, demonstrable products targeting 18-34 | Young, impulse buyers | 5% + shipping | Video content capability, trend-aware |
| **Etsy** | Handmade, vintage, unique, customizable | Niche buyers willing to pay premium | 6.5% transaction + listing | Unique/artisan positioning |
| **Own Website (DTC/Shopify)** | Brand control, customer data ownership | Your audience | Platform fees only (~2-3%) | Marketing capability to drive traffic |
| **eBay** | Clearance, refurbished, collectibles, niche | Bargain hunters, collectors | ~13% final value | Competitive pricing, good seller rating |
### Expansion Priority by Current Platform
**If currently on Shopify/DTC:**
1. Amazon (if product has search demand) — instant access to high-intent traffic
2. TikTok Shop (if product is visual) — low fees, organic viral potential
3. Etsy (if product is unique/handmade) — niche premium audience
4. Walmart — growing marketplace, less competition than Amazon
5. eBay — good for clearance, niche, or collectible products
**If currently on Amazon:**
1. Own website (DTC/Shopify) — own your customer data and email list
2. Walmart — similar catalog, growing marketplace, lower competition
3. TikTok Shop — diversify beyond search-based channels
4. eBay — clearance channel for slow-moving inventory
5. Etsy — only if product is unique/handmade/customizable
**If currently on Etsy:**
1. Own website (DTC/Shopify) — capture email, build brand outside Etsy
2. Amazon Handmade — if product fits, much larger audience
3. TikTok Shop — visual/handmade products do well organically
4. eBay — vintage/collectible crossover audience
5. Walmart — only if you can scale production for mass market
**If currently on Walmart:**
1. Amazon — if not already there, much larger traffic
2. Own website (DTC/Shopify) — build brand, own customer data
3. TikTok Shop — younger audience, viral potential
4. eBay — secondary sales channel for clearance
5. Etsy — only if product has handmade/unique angle
**If currently on TikTok Shop:**
1. Own website (DTC/Shopify) — capture email from viral traffic
2. Amazon — convert TikTok awareness into search-based sales
3. Walmart — price-conscious audience overlap
4. Etsy — if product is unique/trendy
5. eBay — clearance or bundle deals
**If currently on eBay:**
1. Own website (DTC/Shopify) — build brand beyond marketplace
2. Amazon — much larger audience for established products
3. Walmart — growing alternative marketplace
4. TikTok Shop — if product is demonstrable/visual
5. Etsy — only if product has handmade/vintage angle
---
## Product Line Expansion Framework
### When to Expand
- Current products are profitable and reviews are strong (4+ stars)
- You're seeing repeat customers ask for related products
- Competitors offer adjacent products you don't
- You've identified gaps from customer reviews/feedback
### How to Identify Adjacent Products
1. **Customer review mining** — what do customers wish your product included? What do they buy alongside it?
2. **Competitor catalog analysis** — what else do similar brands sell?
3. **Search demand** — are people searching for products adjacent to yours?
4. **Cross-sell data** — what products are frequently bought together in your category?
### Product Launch Strategy (3 Phases)
1. **Phase 1: Owned audience** — launch to email list and existing customers first. Low CAC, real feedback
2. **Phase 2: Paid + social** — expand via ads, influencer partnerships, social media
3. **Phase 3: Marketplace** — list on Amazon/Walmart once you have reviews and momentum
*(ConvertCart 2025)*
### Expansion Risk Assessment
| Type | Risk Level | Example |
|------|:---------:|---------|
| Variation of existing product | 🟢 Low | New color/size of best-seller |
| Complementary accessory | 🟢 Low | Leash brand adds collars |
| Adjacent category (same audience) | 🟡 Medium | Dog treats brand adds dog toys |
| New category (different audience) | 🔴 High | Dog treats brand adds cat food |
| Subscription model | 🟡 Medium | One-time purchase → recurring |
---
## Unit Economics Reference
When calculating unit economics, use these formulas and benchmarks:
### Formulas
- **CAC** = Total Acquisition Spend ÷ New Customers Acquired (include ad spend, creative, tools, discounts)
- **LTV** = AOV × Purchase Frequency × Customer Lifespan × Gross Margin
- **LTV:CAC Ratio** = LTV ÷ CAC
- **Contribution Margin** = Revenue - COGS - Shipping - Processing (3%) - Packaging - Returns provision (5%)
- **Payback Period** = CAC ÷ (AOV × Contribution Margin %)
### LTV:CAC Benchmarks *(Finsi.ai 2026)*
| Ratio | Meaning |
|:-----:|---------|
| < 1:1 | Losing money on every customer. Business model broken |
| 1:1 - 2:1 | Marginal. Profitable only with very low overhead |
| 2:1 - 3:1 | Functional. Room for improvement — focus on retention (raise LTV) or efficiency (lower CAC) |
| 3:1 - 5:1 | Healthy. Target range for growth-stage brands |
| > 5:1 | Under-investing in growth. Could afford to spend more on acquisition |
### Growth Equation
```
Revenue = Traffic × Conversion Rate × AOV × Purchase Frequency
```
Show the user which variable has the most room to improve. A 20% lift in conversion often beats a 20% increase in traffic — and costs less.
---
## Growth Priorities by Business Stage
### Pre-launch ($0/mo)
**Focus:** Validate product-market fit before spending on growth
- Build email list (landing page + lead magnet)
- Launch to small audience, get 50+ honest reviews
- Prove unit economics work (positive contribution margin)
- **Don't:** Scale ads, expand channels, launch multiple products
### Early Stage (<$10K/mo)
**Focus:** Find profitable acquisition channel + build retention foundation
- Priority lever: Traffic (find 1 channel that works profitably)
- Set up basic email flows (welcome, cart abandon, post-purchase)
- Optimize product pages for conversion
- **Don't:** Expand to new channels, launch new products, over-invest in brand
### Growing ($10K-50K/mo)
**Focus:** Optimize unit economics + diversify traffic + build retention
- Priority lever: Retention + CRO (highest ROI at this stage)
- Expand to 2-3 marketing channels
- Begin product line planning (adjacent products)
- Test channel expansion (one new marketplace)
- **Don't:** Scale what isn't profitable, expand too fast operationally
### Scaling ($50K-200K/mo)
**Focus:** Systemize, delegate, expand
- Priority lever: Expansion + AOV
- Launch on 2nd/3rd sales channels
- Expand product line (adjacent categories)
- Build team or outsource operations
- Invest in brand building
- **Don't:** Neglect retention while chasing acquisition, ignore operations
### Established ($200K+/mo)
**Focus:** Defensibility, efficiency, diversification
- Priority lever: All 5 — systematic optimization
- International expansion
- Subscription/recurring revenue
- Loyalty and community programs
- Consider vertical integration (manufacturing, fulfillment)
---
## Output Format
```
# 🚀 Growth Strategy — [Brand/Product Name]
## Business Snapshot
Product | Platform | Revenue | Stage | AOV | Margin | Repeat Rate
## Unit Economics Health Check
| Metric | Your Number | Benchmark | Status |
| CAC | $X | $X-X (category avg) | 🟢/🟡/🔴 |
| LTV | $X | — | — |
| LTV:CAC | X:1 | 3:1-5:1 target | 🟢/🟡/🔴 |
| Contribution Margin | X% | 40-60% target | 🟢/🟡/🔴 |
| Conversion Rate | X% | X% (benchmark) | 🟢/🟡/🔴 |
| Repeat Purchase Rate | X% | 28% avg | 🟢/🟡/🔴 |
## Growth Equation Diagnosis
Revenue = Traffic × Conversion × AOV × Frequency
[Which variable has the most room to improve?]
## E-Commerce Ansoff Matrix (Your Opportunities)
[4-quadrant analysis with specific opportunities per quadrant]
## Growth Opportunity Matrix
| Opportunity | Impact | Effort | Priority | Details |
[Ranked list of all opportunities]
## Top 3 Growth Priorities (Detailed)
### Priority 1: [Name]
[What, why, how, expected impact, timeline, risks]
→ Execution skill: [link to relevant Nexscope skill]
### Priority 2: [Name]
...
### Priority 3: [Name]
...
## Channel Expansion Assessment (if applicable)
[Readiness checklist + specific channel recommendation]
## Product Expansion Assessment (if applicable)
[Adjacent products + launch strategy]
## 90-Day Growth Roadmap
### Days 1-30: Foundation
[Actions + milestones + KPIs]
### Days 31-60: Build
[Actions + milestones + KPIs]
### Days 61-90: Scale
[Actions + milestones + KPIs]
## KPIs & Tracking
| Metric | Current | 30-Day Target | 60-Day | 90-Day |
[Specific targets for each key metric]
## Next Steps
[Immediate action items — what to do THIS WEEK]
```
---
## Other Skills
For detailed execution of specific growth initiatives:
**Paid advertising:**
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-ppc-strategy-planner -g
```
**Email marketing system:**
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-email-marketing-builder -g
```
**Full marketing strategy:**
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-marketing-strategy-builder -g
```
**Product descriptions:**
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill product-description-generator -g
```
More e-commerce skills: [nexscope-ai/eCommerce-Skills](https://github.com/nexscope-ai/eCommerce-Skills)
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
Full-funnel e-commerce advertising planner for cross-channel campaigns. Covers keyword research, competitor ad analysis, audience insights, campaign architec...
---
name: ecommerce-advertising
description: "Full-funnel e-commerce advertising planner for cross-channel campaigns. Covers keyword research, competitor ad analysis, audience insights, campaign architecture, budget allocation across channels (Amazon PPC, Google Ads, Meta Ads, TikTok Ads, Pinterest Ads), ad copy generation, and creative direction. Helps you build a complete multi-channel ad strategy from scratch. Works for Amazon, Shopify, Walmart, eBay, and multi-channel sellers. No API key required."
metadata:
nexscope:
emoji: "📢"
category: ecommerce
---
# E-Commerce Advertising 📢
Build your full-funnel advertising strategy across all major channels: Amazon PPC, Google Ads, Meta Ads, TikTok Ads, and Pinterest Ads.
**Supported platforms:** Amazon, Shopify, Walmart, eBay, TikTok Shop, WooCommerce, Standalone DTC
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
## Install
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-advertising -g
```
## Capabilities
- **Keyword research**: Core keywords, long-tail opportunities, competition density, suggested bid ranges
- **Competitor ad analysis**: Which channels competitors use, what angles they run, what's working
- **Audience insights**: Target persona extraction from reviews and market data
- **Campaign architecture**: Campaign structure, ad group organization, targeting strategies
- **Cross-channel budget allocation**: How much to spend on each channel based on stage and goals
- **Ad copy generation**: Headlines, descriptions, CTAs optimized per platform
- **KPI targets**: ACoS, ROAS, CTR, CVR benchmarks for your category
## Usage Examples
```
I'm launching a silicone kitchen utensil set on Amazon US, also have a Shopify store. Price $29.99, cost $8. Monthly ad budget $3,000. Help me plan my advertising strategy.
```
```
Selling premium dog treats on Shopify. $45 AOV, 55% margin. Want to start with $2,000/month ads. Which platforms should I prioritize?
```
```
I have a TikTok Shop selling phone accessories. Budget $1,500/month. What's my ad strategy?
```
---
## How This Skill Works
### Step 1: Collect Information
Parse from the user's prompt:
- Product / category
- Target market (US, UK, DE, JP, CA, etc.)
- Sales platform(s)
- Monthly ad budget
- Profit margin
- Business stage (launch / growth / scale)
- Competitor ASINs or brand names (optional)
### Step 2: One Follow-Up Question Set
```
Great — kitchen utensils at $29.99 with $3,000/month budget. To build your strategy:
1. Your product cost per unit: $_____
2. Primary goal?
a) Launch — build awareness, get initial sales
b) Growth — scale proven winners
c) Profitability — optimize for max ROAS
d) Seasonal push — short-term spike
3. How do customers find products like yours?
a) They search for it (e.g., "silicone spatula")
b) They discover it visually
c) They need to see it in action (demo)
d) Not sure
4. Brand positioning?
a) Premium b) Mid-market c) Budget d) Other: ___
5. Competitors to analyze? (ASIN or brand, optional)
Reply like: 1. $8 2b 3a 4b 5. B09XYZ123
```
### Step 3: Execute Analysis
Generate the full output using the frameworks below.
---
## Keyword Research
Use `web_search` to gather keyword data.
**Step 1: Search for seed keywords**
```
web_search: "[product] keywords"
web_search: "[product] amazon autocomplete"
```
**Step 2: Research long-tail opportunities**
```
web_search: "[product] for [use case]"
web_search: "best [product] for [specific need]"
```
**Step 3: Analyze competition**
```
web_search: "[keyword] amazon sponsored"
```
| Competition | Indicators | Strategy |
|:-----------:|------------|----------|
| **Low** | <10K results, few ads | Bid aggressively |
| **Medium** | 10K-50K results | Balanced bid |
| **High** | 50K+ results | Long-tail focus |
**Bid Ranges by Platform:**
| Platform | Low | Med | High |
|----------|:---:|:---:|:----:|
| Amazon PPC | $0.30-0.60 | $0.60-1.20 | $1.20-2.50 |
| Google Shopping | $0.20-0.50 | $0.50-1.00 | $1.00-2.00 |
| Google Search | $0.50-1.00 | $1.00-2.00 | $2.00-4.00 |
---
## Competitor Ad Analysis
Use `web_search` and `web_fetch` to gather competitor intelligence.
**Step 1: Identify competitors**
```
web_search: "[product] best sellers amazon"
web_search: "[product category] top brands"
```
**Step 2: Analyze channel presence**
```
web_search: "[brand name] amazon sponsored"
web_fetch: https://www.facebook.com/ads/library/?q=[brand]
web_search: "[brand name] tiktok ads"
```
**Step 3: Extract ad angles**
```
web_search: "[competitor brand] marketing"
web_fetch: [competitor website]
```
**Step 4: Identify gaps**
- Angles competitors aren't using
- Platforms where they're weak
- Keywords they're missing
---
## Audience Insights
Use `web_search` and `web_fetch` to build personas.
**Step 1: Mine reviews**
```
web_fetch: https://www.amazon.com/dp/[ASIN]
web_search: "[product] reviews reddit"
web_search: "[product] complaints"
```
**Step 2: Build personas**
- Demographics (age, gender from review hints)
- Motivations (why they buy)
- Pain points (what they hate)
- Language (exact phrases for ad copy)
**Step 3: Extract ad copy angles**
- From positive reviews → benefits to highlight
- From negative competitor reviews → problems to solve
---
## Channel Selection
| Product Type | Primary Channel | Secondary |
|--------------|----------------|-----------|
| Search-driven | Amazon PPC / Google Shopping | Meta retargeting |
| Visual / lifestyle | Meta Ads | Pinterest, Google |
| Demo-driven | TikTok Ads | Meta, YouTube |
| Impulse (<$30) | TikTok, Meta | Amazon PPC |
| High-ticket (>$100) | Google Search | Meta retargeting |
### Platform Benchmarks (2025-2026)
| Platform | Avg ROAS | Top Quartile | Avg CPC |
|----------|:--------:|:------------:|:-------:|
| Amazon PPC | 3.5x | 5x+ | $0.80-1.50 |
| Google Shopping | 4.5x | 6x+ | $0.50-1.20 |
| Meta Ads | 2.2x | 4-5x | $0.70-1.50 |
| TikTok Ads | 1.4x | 2.5x+ | $0.50-1.00 |
*Sources: Triple Whale 2025, Lebesgue 2026*
### Budget Thresholds
| Budget | Strategy |
|:------:|----------|
| < $1,000 | ONE channel only |
| $1,000-3,000 | Primary (70%) + retargeting (30%) |
| $3,000-10,000 | 2-3 channels |
| $10,000+ | Full cross-channel |
---
## Budget Allocation (70-20-10)
| Allocation | Purpose |
|:----------:|---------|
| **70%** | Proven channels (highest ROAS) |
| **20%** | Promising channels (scaling) |
| **10%** | Testing / experimental |
---
## Campaign Architecture
### Amazon PPC
```
├── Exact Match - Core Keywords (40%)
├── Phrase Match - Discovery (25%)
├── Auto - Harvesting (20%)
└── Product Targeting (15%)
```
### Google Ads
```
├── Shopping - High Priority
├── Search - Brand
├── Search - Non-Brand
└── Performance Max
```
### Meta Ads
```
├── Prospecting - Interest Based
├── Prospecting - Lookalike
└── Retargeting (visitors, cart, purchasers)
```
### TikTok Ads
```
├── Broad Targeting
├── Spark Ads (boost organic)
└── Lookalike
```
---
## Ad Copy Templates
### Google Ads
```
Headline 1 (30 chars): [Keyword] - [Price/Offer]
Headline 2 (30 chars): [Key Benefit]
Headline 3 (30 chars): [Social Proof]
Description (90 chars): [What it is] + [Feature] + [CTA]
```
### Meta Ads
```
Primary (125 chars): [Hook] + [Benefit] + [Emoji]
Headline (40 chars): [Offer]
CTA: Shop Now
```
### TikTok
```
Caption (100 chars): [Hook] #hashtags
Hook formulas:
- "POV: [relatable situation]"
- "Stop buying [inferior product]"
- "This [product] changed my [routine]"
```
---
## KPI Targets
| Metric | Launch | Growth | Mature |
|--------|:------:|:------:|:------:|
| Amazon ACoS | 35-50% | 25-35% | 15-25% |
| Google ROAS | 2-3x | 3-4x | 4-6x |
| Meta ROAS | 1.5-2x | 2-3x | 3-4x |
| TikTok ROAS | 1-1.5x | 1.5-2x | 2-3x |
### Calculate Targets
```
Break-even ROAS = 1 / Profit Margin
Target ROAS = Break-even × 1.5
Max CPA = AOV × Profit Margin
```
---
## Output Format
```
# 📢 E-Commerce Advertising Strategy
**Product:** [name]
**Market:** [market]
**Budget:** $[budget]/month
**Stage:** [Launch / Growth / Scale]
## 1. Keyword Research
[Keyword tables]
## 2. Competitor Analysis
[Channel presence, angles, gaps]
## 3. Target Audience
[Personas, pain points, targeting]
## 4. Channel Strategy
[Recommended channels + budget split]
## 5. Campaign Architecture
[Platform structures]
## 6. Ad Copy
[Headlines, descriptions, hooks]
## 7. KPI Targets
[Metrics to hit]
## ⚠️ Notes
- Search volumes are estimates
- Use platform tools for precise data
```
---
## Limitations
This skill provides strategic analysis based on web research and industry benchmarks. For real-time keyword data, actual search volumes, live competitor tracking, and integrated campaign management, check out **[Nexscope](https://www.nexscope.ai/)** — Your AI Assistant for smarter E-commerce decisions.
---
## Related Skills
**For deeper PPC strategy:**
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-ppc-strategy-planner -g
```
Detailed ROAS calculations, budget allocation, and ad copy generation.
**For Amazon-specific advertising:**
```bash
npx skills add nexscope-ai/Amazon-Skills --skill amazon-ppc-campaign -g
```
Amazon Sponsored Products, Sponsored Brands, and Sponsored Display.
**All e-commerce skills:**
- [nexscope-ai/eCommerce-Skills](https://github.com/nexscope-ai/eCommerce-Skills) — Cross-platform tools for marketing, pricing, brand protection, supply chain
- [nexscope-ai/Amazon-Skills](https://github.com/nexscope-ai/Amazon-Skills) — Amazon-specific tools: FBA, PPC, listing optimization, keyword research
---
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
FILE:evals/evals.json
{
"skill_name": "ecommerce-advertising",
"evals": [
{
"id": 1,
"prompt": "I'm launching a silicone kitchen utensil set on Amazon US and Shopify. Price $29.99, cost $8. Monthly ad budget $3,000. Help me plan my advertising strategy across channels.",
"expected_output": "Keyword research, competitor analysis, audience insights, channel selection with budget allocation, campaign architecture, ad copy templates, KPI targets",
"files": []
},
{
"id": 2,
"prompt": "Selling premium dog treats on Shopify. $45 AOV, 55% margin. Want to start with $2,000/month ads. Which platforms should I prioritize and how should I structure my campaigns?",
"expected_output": "Channel recommendation based on product type, budget allocation, campaign structure for recommended platforms, ad copy suggestions",
"files": []
},
{
"id": 3,
"prompt": "I have a TikTok Shop selling phone accessories. Getting organic traction but want to scale with paid ads. Budget $1,500/month. What's my ad strategy?",
"expected_output": "TikTok-focused strategy, Spark Ads recommendation, hook formulas, creative direction, budget allocation",
"files": []
}
]
}
E-commerce email marketing system builder. Creates complete email automation flows with full copywriting, subject lines, ESP setup instructions, segmentation...
---
name: ecommerce-email-marketing-builder
description: "E-commerce email marketing system builder. Creates complete email automation flows with full copywriting, subject lines, ESP setup instructions, segmentation rules, and annual campaign calendars. Generates copy-paste-ready email sequences for Klaviyo, Omnisend, Mailchimp, or any ESP. Covers welcome series, cart abandonment, browse abandonment, post-purchase, review requests, cross-sell, win-back, VIP/loyalty, replenishment, and sunset flows. Includes A/B test subject line variants, send timing, trigger conditions, branching logic, and seasonal campaign calendar. No API key required. Use when: (1) setting up email marketing for an e-commerce store, (2) writing email sequences and flows, (3) planning seasonal email campaigns."
metadata:
nexscope:
emoji: "📧"
category: ecommerce
---
# E-Commerce Email Marketing Builder 📧
Build a complete, copy-paste-ready email marketing system for any e-commerce business. Covers 10 core automation flows with full copywriting, ESP setup instructions, segmentation rules, and annual campaign calendars.
**Supported platforms:** Shopify, WooCommerce, BigCommerce, Squarespace, Etsy, TikTok Shop, Amazon, and any platform that connects to an ESP. For marketplace platforms (Amazon, TikTok Shop, Etsy) where buyer emails are restricted, this skill focuses on cross-channel strategies to capture emails via your own website or landing pages.
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
## Install
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-email-marketing-builder -g
```
## Usage
Once installed, just describe your business and ask for email marketing help. The skill activates automatically.
```
I'm launching a Shopify store selling premium dog treats at $24.99. Help me set up
my email marketing — I'm using Klaviyo and have about 500 subscribers.
```
```
I sell handmade jewelry on Etsy and my own website. Price range $40-120. I have
2,000 email subscribers but no automated flows set up. What emails should I be sending?
```
```
Build me a complete email system for my sustainable fashion brand. We use Omnisend
and have 8,000 subscribers. I want welcome series, cart abandonment, and post-purchase flows.
```
## Capabilities
- Complete email automation flows for 10 core e-commerce journeys (welcome, cart abandonment, browse abandonment, post-purchase, review request, cross-sell, win-back, VIP/loyalty, replenishment, sunset)
- Full email copywriting for every email — subject lines, preview text, body copy, CTA button text
- 3-5 A/B test subject line variants per email with different angles (curiosity, urgency, benefit, social proof, personal)
- ESP setup instructions generated for your specific platform — trigger conditions, flow filters, delay timing, and branching logic using your ESP's exact terminology
- ESP recommendation if you don't have one yet — based on list size and sales platform, with pricing
- Flow diagrams showing the full sequence: trigger → delay → conditional split → email → branch
- Segmentation strategy with 8 core segments and exact filter conditions for your ESP
- Annual seasonal campaign calendar customized to your product category
- List growth tactics — pop-up strategy, checkout opt-in, social → email conversion
---
## How This Skill Works
**Step 1: Collect information.** Extract from the user's initial message:
- Product / category
- Brand name
- Price range and target audience
- Any context about their business
**Step 2: Ask one follow-up with all remaining questions.** Use multiple-choice format:
```
Great — [acknowledge what they told you]. To build your email system I need a few more details:
1. Business stage?
a) Pre-launch — building a list before selling
b) Early — selling, but under $10K/mo
c) Growing — $10K-50K/mo
d) Established — $50K+/mo
2. Which flows do you need? (pick all that apply, or "all")
a) Welcome series
b) Cart abandonment
c) Browse abandonment
d) Post-purchase / thank you
e) Review request
f) Cross-sell / upsell
g) Win-back (re-engage lapsed customers)
h) VIP / loyalty
i) Replenishment (consumable products)
j) Sunset (list cleanup)
k) All of the above
l) Not sure — recommend for me
3. Brand voice?
a) Professional / corporate
b) Friendly / conversational
c) Playful / fun
d) Premium / luxury
e) Bold / edgy
f) Other: ___________
4. Email platform (ESP)?
a) Klaviyo
b) Omnisend
c) Mailchimp
d) Shopify Email
e) Other: ___________
f) Don't have one yet — recommend one
5. Current email list size?
a) 0 — starting from scratch
b) Under 1,000
c) 1,000-10,000
d) 10,000-50,000
e) 50,000+
6. Any active promotions or standard discounts? (e.g., "we always offer 10% for first order")
7. Competitors to reference? (names or URLs, or skip)
Reply like: "1b 2k 3b 4a 5b 6 yes 10% first order 7 skip"
```
**Step 3: If user chose (f) in Q4 — "Don't have one yet"**, recommend an ESP based on their list size (Q5) and sales platform:
| List Size | Recommended ESP | Approx. Cost |
|-----------|-----------------|:------------:|
| 0-500 | Omnisend Free or Mailchimp Free | $0 |
| 500-2,500 | Omnisend (Shopify) or Mailchimp (other platforms) | $13-20/mo |
| 2,500-10K | Klaviyo | $35-100/mo |
| 10K+ | Klaviyo | $100-350/mo |
⚠️ Prices are approximate (2026). Tell user to verify on each platform's website.
After recommending, continue building flows with setup instructions for the recommended ESP.
**Step 4: If user chose "l) Not sure — recommend for me" in Q2**, recommend flows based on their business stage:
- **Pre-launch:** Welcome series only (build list first)
- **Early (<$10K/mo):** Welcome + Cart Abandonment + Post-Purchase (the 3 essentials)
- **Growing ($10K-50K):** All of the above + Browse Abandonment + Review Request + Cross-sell
- **Established ($50K+):** All 10 flows
**Step 5: Build each requested flow.** For EVERY flow, output:
1. **Flow overview** — purpose, expected revenue impact, priority level
2. **Flow diagram** — visual sequence with timing
3. **For each email in the flow:**
- Subject line (30-50 chars, mobile-friendly) + 3-5 A/B variants with different angles (curiosity, urgency, benefit, social proof, personal)
- Preview text (40-90 chars, complement the subject — don't repeat it)
- Full email body copy (actual words: hook → value → proof → CTA → optional P.S.)
- CTA button text (action-oriented, one primary CTA per email) + link destination
4. **Branching logic** — conditions that split the flow (purchased vs didn't, opened vs didn't)
5. **ESP setup instructions** — generate trigger conditions, flow filters, delay timing, and branching logic specific to the user's chosen ESP (Q4). Use that ESP's exact terminology and menu paths. If user doesn't have an ESP yet, use Klaviyo terminology as default
**Step 6: Build segmentation strategy.** Define core segments with exact rules:
- New subscribers (no purchase)
- First-time buyers
- Repeat customers (2+ orders)
- VIP / high-value (top 10% by spend)
- At-risk (purchased before, no activity 60-90 days)
- Lapsed (no activity 90+ days)
- Discount-driven (only buys on sale)
**Step 7: Build annual campaign calendar.** Month-by-month with:
- Key dates and seasonal events relevant to the product category
- Campaign theme for each event
- Send schedule (pre-event teaser, launch day, last chance)
- Which segments to target
**Step 8: Provide list growth tactics.** Based on their platform and stage:
- Pop-up strategies (timing, offer, design)
- Landing page recommendations
- Social media → email conversion tactics
- Checkout opt-in optimization
---
## The 10 Core E-Commerce Email Flows
### Flow 1: Welcome Series
**Priority:** 🔴 Critical — set up first
**Expected impact:** Highest-opened emails, sets tone for entire relationship
**Emails:** 3-5 emails over 7-14 days
**Trigger:** Subscribes to email list (pop-up, footer signup, landing page)
**NOT triggered by:** Purchase (that's post-purchase flow)
**Sequence:**
```
[Subscribe] → Email 1 (Immediately)
→ [Wait 2 days]
→ Email 2 (Brand Story)
→ [Wait 2 days]
→ Email 3 (Social Proof)
→ [Conditional Split: Has placed order?]
→ YES → Exit (enter post-purchase flow)
→ NO → [Wait 3 days]
→ Email 4 (Urgency / Last Chance)
```
**Email 1 — Welcome + Deliver Promise**
- Goal: Deliver the signup incentive, make a strong first impression
- Timing: Send immediately (within minutes of signup)
- Content: Welcome message, deliver discount/freebie, introduce brand briefly, one clear CTA to shop
- Design: Clean, brand-forward, hero image, single CTA button
**Email 2 — Brand Story + Values**
- Goal: Build emotional connection, differentiate from competitors
- Timing: 2 days after Email 1
- Content: Founder story or brand mission, why you started, what makes you different, lifestyle imagery
- Design: Storytelling layout, minimal product — focus on brand
**Email 3 — Social Proof + Best Sellers**
- Goal: Build trust, showcase popular products
- Timing: 2 days after Email 2
- Content: Customer reviews, UGC, best-selling products, "loved by X customers"
- Design: Product grid with reviews, star ratings
**Email 4 — Discount Reminder / Urgency** (only if they haven't purchased)
- Goal: Convert remaining non-buyers before discount expires
- Timing: 3 days after Email 3
- Content: "Your [X%] off expires soon," countdown urgency, restate value prop, clear CTA
- Design: Urgent — bold colors, countdown timer if ESP supports it
### Flow 2: Cart Abandonment
**Priority:** 🔴 Critical — highest revenue per recipient
**Expected impact:** $5.81 revenue per recipient average *(Klaviyo 2026)*
**Emails:** 3 emails over 3 days
**Trigger:** Added to cart + started checkout, but did NOT complete purchase
**Wait before first email:** 1-4 hours (test: 1h vs 4h)
**Sequence:**
```
[Checkout Started, Not Completed] → [Wait 1-4 hours]
→ Email 1 (Reminder)
→ [Wait 24 hours]
→ [Conditional Split: Placed order?]
→ YES → Exit
→ NO → Email 2 (Overcome Objections)
→ [Wait 24 hours]
→ [Conditional Split: Placed order?]
→ YES → Exit
→ NO → Email 3 (Incentive)
```
**Email 1 — Simple Reminder**
- Goal: Catch people who got distracted (not resistant — just forgot)
- Content: "You left something behind," show cart contents with images + prices, direct link back to cart
- Tone: Helpful, not pushy. No discount yet
- CTA: "Complete Your Order" or "Return to Cart"
**Email 2 — Overcome Objections**
- Goal: Address why they didn't buy (shipping? trust? price?)
- Content: Social proof (reviews), shipping/return policy highlights, FAQs, "still thinking?"
- Tone: Reassuring
- CTA: "Get It Before It's Gone"
**Email 3 — Incentive** (optional — only if margin allows)
- Goal: Last resort conversion with discount or free shipping
- Content: Limited-time offer (10% off or free shipping), urgency ("expires in 24 hours")
- Tone: Urgent but not desperate
- CTA: "Claim Your [X%] Off"
- ⚠️ Only use a discount if your margin supports it. If not, emphasize scarcity instead
### Flow 3: Browse Abandonment
**Priority:** 🟡 Important — catches high-intent window shoppers
**Expected impact:** Lower conversion than cart, but much higher volume
**Emails:** 1-2 emails over 2 days
**Trigger:** Viewed product page but did NOT add to cart
**Wait:** 2-4 hours after browsing (not immediately — feels creepy)
**Sequence:**
```
[Viewed Product, Did Not Add to Cart] → [Wait 2-4 hours]
→ [Conditional Split: Has added to cart since?]
→ YES → Exit (they'll enter cart abandonment)
→ NO → Email 1 (Product Reminder)
→ [Wait 24 hours]
→ Email 2 (Related Products)
```
**Email 1 — "Still Interested?"**
- Content: Show the product they viewed with image + price, brief benefit/review quote, link to product page
- Tone: Casual, helpful — NOT "we noticed you looking" (creepy)
- CTA: "Take Another Look"
- ⚠️ Do NOT offer a discount here — saves margin, avoids training customers to browse-then-leave for discounts
**Email 2 — Related Products**
- Content: "You might also like..." with 3-4 related products, category page link
- Purpose: If they weren't sold on that specific product, show alternatives
### Flow 4: Post-Purchase / Thank You
**Priority:** 🔴 Critical — shapes the entire post-purchase experience
**Expected impact:** Reduces buyer's remorse, increases repeat rate, drives reviews
**Emails:** 3-4 emails over 14-21 days
**Trigger:** Placed order (first-time buyer gets different content than repeat buyer)
**Sequence:**
```
[Order Placed] → Email 1 (Immediately — Thank You)
→ [Wait: Estimated delivery + 2 days]
→ [Conditional Split: First-time buyer?]
→ YES → Email 2a (Product Education)
→ NO → Email 2b (Loyalty Reward)
→ [Wait 5-7 days]
→ Email 3 (Review Request — see Flow 5)
→ [Wait 14 days]
→ Email 4 (Cross-sell — see Flow 6)
```
**Email 1 — Order Confirmation + Thank You**
- Timing: Immediately after purchase
- Content: Thank you, order summary, shipping timeline, what to expect, support contact
- Tone: Warm, grateful — this is a celebration, not a receipt
- Add: "Here's what happens next" (sets expectations)
**Email 2a — Product Education (first-time buyers)**
- Timing: After estimated delivery + 2 days
- Content: How to use/care for the product, tips, FAQ, "get the most out of your [product]"
- Purpose: Reduce returns, increase satisfaction, build brand connection
**Email 2b — Loyalty Thank You (repeat buyers)**
- Timing: Same timing
- Content: "Thanks for coming back! You're one of our best customers," exclusive offer or early access
- Purpose: Reward loyalty, increase LTV
### Flow 5: Review Request
**Priority:** 🟡 Important — builds social proof that powers all other marketing
**Emails:** 1-2 emails
**Trigger:** Chained from post-purchase flow OR standalone trigger on order fulfilled + X days
**Timing:** 5-7 days after delivery (product has arrived, they've used it)
**Email 1 — Review Request**
- Content: "How's your [product]? We'd love to hear!" + direct link to leave review
- Tone: Personal, low-pressure
- Make it easy: One-click star rating if your review platform supports it (Stamped, Loox, Judge.me)
- Optional: Small incentive (10% off next order, loyalty points)
**Email 2 — Reminder** (only if no review submitted after 5 days)
- Content: Shorter, more direct. "Quick reminder — your review helps other [pet owners / etc.]"
- Social proof: "Join 500+ customers who shared their experience"
### Flow 6: Cross-Sell / Upsell
**Priority:** 🟡 Important — increases AOV and LTV
**Emails:** 1-2 emails
**Trigger:** Placed order + 14-21 days (after they've received and used the product)
**Logic:** Recommend products based on what they bought
**Email 1 — "Complete the Set" / "Pairs Well With..."**
- Content: Related products based on purchase (accessories, refills, complementary items)
- Tone: Helpful recommendation, not hard sell
- CTA: "Shop the Collection" or "Complete Your Set"
**Product recommendation logic:**
- If ESP supports dynamic product recommendations (Klaviyo, Omnisend), use them
- If not, build manual splits by product category:
- Bought [Category A] → Recommend [Category B]
- Bought [Product X] → Recommend [Accessory Y]
### Flow 7: Win-Back
**Priority:** 🟡 Important — re-engages lapsed customers before they're lost
**Emails:** 3-4 emails over 30 days
**Trigger:** Has placed order BUT last order was 60-90 days ago (adjust based on your purchase cycle)
**Additional filter:** Has NOT opened or clicked any email in last 30 days
**Sequence:**
```
[Last Order 60-90 days ago + No engagement 30 days]
→ Email 1 (We Miss You)
→ [Wait 7 days]
→ [Placed order?] → YES → Exit
→ NO → Email 2 (What's New)
→ [Wait 7 days]
→ Email 3 (Incentive)
→ [Wait 14 days]
→ Email 4 (Last Chance / Sunset Warning)
```
**Email 1 — "We Miss You"**
- Content: Personal, genuine message. What's new since they last bought. Best sellers they haven't tried
- Tone: Warm, not guilt-tripping
- No discount yet — test whether re-engagement alone works
**Email 2 — What's New**
- Content: New products, new features, brand updates, community highlights
- Purpose: Give them a reason to come back beyond discounts
**Email 3 — Incentive**
- Content: "Here's X% off to welcome you back" — exclusive returning customer offer
- Urgency: Time-limited (7 days)
**Email 4 — Last Chance / Sunset Warning**
- Content: "We don't want to bother you — should we keep sending?" + unsubscribe option
- Purpose: Gives control back to customer, cleans list if they don't respond
- If no response → Move to sunset flow
### Flow 8: VIP / Loyalty
**Priority:** 🟢 Nice to have for growing brands, critical for established
**Emails:** Ongoing (event-triggered)
**Trigger:** Customer enters VIP segment (top 10% by total spend, OR 3+ orders)
**Email 1 — VIP Welcome**
- Content: "You're officially a VIP! Here's what that means:" + exclusive perks
- Perks to offer: Early access to new products, exclusive discounts, free shipping, birthday gift
**Ongoing VIP emails:**
- Early access notifications (before public launches)
- Exclusive sales (VIP-only pricing)
- Birthday/anniversary rewards
- "Thank you" with surprise gift at milestones (5th order, 1-year anniversary)
### Flow 9: Replenishment (Consumable Products Only)
**Priority:** 🟡 Critical if you sell consumables — skip if not applicable
**Emails:** 1-2 emails
**Trigger:** Time-based — estimated product usage cycle after purchase
- Example: Dog treats (30-day supply) → trigger at day 25
- Example: Skincare (60-day supply) → trigger at day 50
- Example: Coffee (14-day bag) → trigger at day 10
**Email 1 — "Running Low?"**
- Timing: 5 days before estimated run-out
- Content: "Time to restock? Your [product] should be running low." + reorder link
- Optional: Subscription offer ("Never run out — subscribe and save 15%")
**Email 2 — Follow-Up**
- Timing: 3 days after Email 1 if no reorder
- Content: Shorter reminder + social proof ("other customers reorder every X days")
### Flow 10: Sunset (List Cleanup)
**Priority:** 🟢 Important for deliverability — set up after other flows are running
**Emails:** 2-3 emails over 14-21 days
**Trigger:** No email opens AND no clicks AND no purchases in 90-120 days
**Purpose:** Clean your list. Unengaged subscribers hurt deliverability (emails go to spam for everyone).
**Sequence:**
```
[No engagement 90-120 days]
→ Email 1 (Re-engagement Attempt)
→ [Wait 7 days]
→ [Opened or clicked?]
→ YES → Exit, keep on list
→ NO → Email 2 (Final Chance)
→ [Wait 7 days]
→ [Opened or clicked?]
→ YES → Exit, keep on list
→ NO → Suppress from all future sends
```
**Email 1 — "Are You Still There?"**
- Subject: Make it stand out (pattern interrupt)
- Content: "We noticed you haven't been opening our emails. Want to stay? Click here to stay subscribed"
- CTA: Single button — "Yes, Keep Me Subscribed"
**Email 2 — "This Is Goodbye (Unless...)"**
- Content: "This is our last email unless you tell us to keep going"
- CTA: "Keep Sending Me Emails"
- If no response → auto-suppress (do NOT delete — just suppress from sends)
---
## Segmentation Strategy
Define these segments in your ESP. Exact conditions provided:
| Segment | Conditions | Use For |
|---------|-----------|---------|
| New Subscribers | Subscribed + Has placed 0 orders | Welcome flow, first purchase incentives |
| First-Time Buyers | Has placed exactly 1 order | Post-purchase education, review request, second purchase push |
| Repeat Customers | Has placed 2+ orders | Cross-sell, loyalty, VIP pipeline |
| VIP | Top 10% by total spend OR 5+ orders | VIP flow, early access, exclusive offers |
| At-Risk | Last order 60-90 days ago | Win-back flow |
| Lapsed | Last order 90+ days ago + No engagement 60+ days | Aggressive win-back, sunset candidate |
| Engaged Non-Buyers | Opens/clicks emails but has NOT purchased | Browse abandon focus, stronger incentives |
| Discount-Only | Has ONLY purchased with a discount code | Reduce discount dependency, value-based messaging |
---
## Annual Campaign Calendar Template
Customize based on your product category. Not every event applies to every brand — pick the ones relevant to your audience.
| Month | Key Dates | Campaign Ideas |
|-------|-----------|----------------|
| January | New Year (Jan 1), MLK Day (Jan 20) | New Year sale, "New Year New You," goal-setting content |
| February | Valentine's Day (Feb 14), Presidents' Day (Feb 17) | Gift guides, couples/self-love angle, flash sale |
| March | Int'l Women's Day (Mar 8), St. Patrick's (Mar 17), Spring Equinox | Seasonal transition, spring collection launch |
| April | Easter (variable), Earth Day (Apr 22) | Spring sale, sustainability angle, limited editions |
| May | Mother's Day (May 11), Memorial Day (May 26) | Gift guide, "treat your mom / treat yourself," summer kickoff sale |
| June | Father's Day (Jun 15), Summer Solstice, Pride Month | Gift guide, summer collection, Pride content if authentic |
| July | July 4th, Amazon Prime Day (mid-July) | Independence Day sale, mid-year clearance, Christmas in July |
| August | Back to School (early Aug) | End of summer sale, back-to-routine content, fall preview |
| September | Labor Day (Sep 1), Fall Equinox | Labor Day sale, fall launch, loyalty program push |
| October | Halloween (Oct 31) | Spooky-themed content, costume/party angle, early holiday teasers |
| November | Veterans Day (Nov 11), Black Friday (Nov 28), Cyber Monday (Dec 1) | BFCM = biggest email month. Pre-sale VIP access → Main event → Extended sale |
| December | Christmas (Dec 25), Hanukkah, New Year's Eve | Gift guides, last-minute shipping deadlines, year-in-review, thank you |
### BFCM (Black Friday / Cyber Monday) Email Strategy
This is your biggest email revenue period. Plan ahead:
- **3-4 weeks before:** Teaser emails to build anticipation, grow list aggressively
- **1 week before:** VIP early access announcement
- **Black Friday:** Launch email (morning) + reminder (evening)
- **Saturday-Sunday:** Extended deals, bundle offers
- **Cyber Monday:** New deals or "last chance" on BF deals
- **Tuesday after:** Thank you email + "sale extended 24 hours" (if applicable)
---
## List Growth Tactics
- **Pop-up:** Show after 5-8 seconds OR on exit intent. Offer 10-15% off first order or free shipping. Target 3-5% conversion rate
- **Checkout opt-in:** Pre-checked "Email me about new products"
- **Social → email:** Instagram/TikTok bio link to email capture landing page
- **Packaging insert:** "Join our VIP list" card in orders
- **Referral:** "Give $X, get $X" programs that grow your list through customers
- **Content marketing:** Blog → gated downloads (guides, lookbooks)
---
## Output Format
```
# 📧 Email Marketing System — [Brand Name]
## Overview
Brand: [name] | Products: [category] | Price: $XX-XX
Stage: [stage] | List Size: [size] | ESP: [platform]
Voice: [brand voice] | Flows: [list]
## Flow 1: [Flow Name]
**Purpose:** [why this flow matters]
**Priority:** [🔴 Critical / 🟡 Important / 🟢 Nice to have]
### Flow Diagram
[trigger] → [delay] → [email] → [conditional split] → [branch]
### Email 1: [Name]
**Subject:** [primary subject line]
**A/B Variants:**
1. [variant] — [angle]
2. [variant] — [angle]
3. [variant] — [angle]
**Preview:** [preview text]
**Body:** [full email copy]
**CTA:** [button text] → [link]
### ESP Setup ([platform name])
- Trigger: [exact trigger in ESP terminology]
- Filters: [conditions]
- Timing: [delays between emails]
- Branching: [split conditions]
[Repeat for each email and flow]
## Segmentation Strategy
[Segments with exact filter conditions for their ESP]
## Annual Campaign Calendar
[Month-by-month with dates, themes, and target segments]
## List Growth Plan
[Tactics based on their platform and stage]
```
---
## Other Skills
For paid advertising strategy across Google, Meta, and TikTok:
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-ppc-strategy-planner -g
```
For full omnichannel marketing strategy (includes email as one channel):
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-marketing-strategy-builder -g
```
More e-commerce skills: [nexscope-ai/eCommerce-Skills](https://github.com/nexscope-ai/eCommerce-Skills)
Built by [Nexscope](https://www.nexscope.ai/) — your AI assistant for smarter e-commerce decisions.
E-commerce content marketing strategy planner. Generates content calendars, topic ideas, and platform-specific strategies by analyzing customer reviews, tren...
---
name: ecommerce-content-marketing
description: "E-commerce content marketing strategy planner. Generates content calendars, topic ideas, and platform-specific strategies by analyzing customer reviews, trends, competitor content, and SEO opportunities. Two modes: (A) Build — create a full content strategy from scratch, (B) Audit — analyze existing content and find gaps. Supports TikTok, Instagram, YouTube, Pinterest, blog/SEO, and Amazon A+. No API key required. Use when: (1) planning content for a new product launch, (2) building a content calendar, (3) finding viral content ideas, (4) analyzing competitor content strategies, (5) extracting customer pain points for content topics."
metadata: {"nexscope":{"emoji":"📣","category":"ecommerce"}}
---
# E-Commerce Content Marketing Planner 📣
Plan your content marketing strategy: discover what topics resonate with your audience, analyze competitor content, find trending formats, and generate a ready-to-execute content calendar. No API key required.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill ecommerce-content-marketing -g
```
## Two Modes
| Mode | When to Use | Input |
|------|-------------|-------|
| **A — Build** | Creating content strategy from scratch | Product info + target platforms + optional competitor URLs |
| **B — Audit** | Analyzing existing content performance | Your content URLs/handles + competitor URLs |
## Supported Platforms
| Platform | Content Types |
|----------|---------------|
| **TikTok** | Short-form video, TikTok Shop, trends, duets, sounds |
| **Instagram** | Reels, Stories, carousels, static posts, Lives |
| **YouTube** | Shorts, long-form tutorials, product reviews, vlogs |
| **X (Twitter)** | Threads, short videos, product announcements, engagement posts |
| **Pinterest** | Pins, Idea Pins, product pins, boards |
| **Blog/SEO** | Articles, guides, listicles, comparison posts |
| **Amazon A+** | Brand story, enhanced product descriptions, comparison charts |
## Usage Examples
### Mode A — Build Strategy
```
Build a content marketing strategy for my portable blender brand.
Target market: US. Platforms: TikTok, Instagram, Blog.
Content goal: Brand awareness + product education.
Target audience: Health-conscious millennials, gym-goers.
Content period: 4 weeks.
```
```
Create a content calendar for my handmade candle shop on Etsy.
Platforms: Pinterest, Instagram, TikTok.
Competitor: https://www.instagram.com/brooklyncandlestudio/
Goal: Drive traffic to my Etsy store.
```
### Mode B — Audit
```
Audit my content strategy. Here's my TikTok: @mybrandhandle
Compare against competitors: @competitor1, @competitor2
Find gaps and opportunities.
```
---
## First Interaction
When user first asks about content marketing, mentions this skill, or gives a vague content-related request, greet them with:
```
✅ Content Marketing Planner ready!
I can help you with two modes:
**A — Build**: Create a full content strategy from scratch
→ Best for: New product launches, brand building, entering new platforms
**B — Audit**: Analyze your existing content and find gaps
→ Best for: Improving performance, competitive analysis, strategy refresh
Which mode do you need? Or just describe what you're working on and I'll guide you.
```
---
## Handling Incomplete Input
If user doesn't provide enough info, ask upfront:
**For Mode A — Build:**
```
To build your content strategy, I need:
**Required:**
- Product / Category (what are you selling?)
- Target Market: US / UK / DE / FR / AU / CA / JP / Global / Multi-region (specify)
- Target Platforms: TikTok / Instagram / YouTube / X (Twitter) / Pinterest / Blog / Amazon A+
**Recommended (better results):**
- Content Goal: Brand awareness / Product education / Drive conversions / All three
- Target Audience: Demographics, interests, pain points
- Competitor brand names or social handles to analyze (e.g., @brandname)
- Content Period: 4 weeks / 8 weeks / 3 months
```
**For Mode B — Audit:**
```
To audit your content, I need:
**Required:**
- Your brand's social handles (e.g., TikTok: @yourbrand, Instagram: @yourbrand)
- OR your website/blog URL
- Platforms you're currently active on
**Recommended (better results):**
- Competitor brand names or handles to compare against
- Your current posting frequency
- What's working / not working (your observations)
- Goals for improvement
```
Which mode?
- **A — Build**: Creating a new content strategy from scratch
- **B — Audit**: Analyzing existing content and finding gaps
---
## Mode A Workflow — Build Content Strategy
### Step 1: Collect Strategy Inputs
| Field | Required | Example |
|-------|----------|---------|
| `product_category` | ✅ | Portable blender, handmade candles |
| `target_market` | ✅ | US, UK, DE, FR, AU, CA, JP, Global, Multi-region |
| `platforms` | ✅ | TikTok, Instagram, YouTube, X, Pinterest, Blog, Amazon A+ |
| `content_goal` | 👍 | Awareness / Education / Conversion / All |
| `target_audience` | 👍 | Health-conscious millennials, 25-35, female |
| `competitor_urls` | 👍 | Brand URLs, social handles, or product pages |
| `content_period` | Optional | 4 weeks (default) / 8 weeks / 3 months |
### Step 2: Customer Insight Mining
Extract buyer language, pain points, and use cases from customer reviews across multiple sources.
**Review Sources to Search (in order of priority):**
| Source | How to Access | Best For |
|--------|---------------|----------|
| **Amazon Reviews** | `web_search: site:amazon.com "[product]" reviews` | Product-specific pain points |
| **Reddit** | `web_search: site:reddit.com "[product]" review OR feedback` | Honest opinions, complaints |
| **Trustpilot** | `web_search: site:trustpilot.com "[brand/product]"` | Brand reputation |
| **YouTube Comments** | `web_search: "[product]" review youtube comments` | Visual product concerns |
| **TikTok Comments** | `web_search: "[product]" tiktok comments reactions` | Gen Z language, viral concerns |
| **Google Reviews** | `web_search: "[brand]" google reviews` | Local/service feedback |
| **Niche Forums** | `web_search: "[product]" forum discussion` | Deep enthusiast insights |
**If product URL or ASIN provided:**
```
Use web_fetch on product page to extract visible reviews.
Also search: site:amazon.com "[product name]" reviews
Focus on: 3-star reviews (balanced), 5-star (what they love), 1-star (pain points).
```
**If only product category (no URL):**
```
web_search: "[product category]" customer reviews pain points
web_search: site:reddit.com "[product category]" what do you hate about
web_search: site:amazon.com "[product category]" review verified purchase
web_search: "[product category]" TikTok comments "love this" OR "hate this"
```
**Extract and categorize:**
- **Pain points**: Problems customers mention (e.g., "battery dies too fast")
- **Use cases**: How customers actually use the product (e.g., "I use it at the gym")
- **Emotional triggers**: Language that shows excitement or frustration
- **Feature highlights**: What customers praise most
- **Objections**: Hesitations before buying
Compile into **Customer Voice Bank**:
```
## Customer Voice Bank
### Pain Points (Content Opportunities)
| Pain Point | Frequency | Content Angle |
|------------|-----------|---------------|
| "Hard to clean" | High | "How to clean your blender in 30 seconds" |
| "Battery anxiety" | Medium | "Real battery test: X hours of use" |
### Use Cases (Lifestyle Content)
| Use Case | Frequency | Content Angle |
|----------|-----------|---------------|
| Post-gym smoothies | High | "Gym bag essentials" content series |
| Office lunch | Medium | "Desk lunch upgrade" trend hook |
### Emotional Language (Copy Bank)
- "Game changer for my mornings"
- "Finally a blender that actually works"
- "My kids love it"
```
### Step 3: Trend & Topic Research
Discover trending topics and seasonal content opportunities.
**Google Trends analysis:**
```
web_search: "[product category]" Google Trends seasonal demand
web_search: "[product category]" trending topics 2024 2025
```
**Platform-specific trends:**
```
web_search: "[product category]" TikTok viral trends
web_search: "[product category]" Instagram Reels trending
web_search: "[product category]" Pinterest trending ideas
```
**Seasonal & event mapping:**
```
web_search: "[product category]" seasonal marketing calendar events
```
Compile into **Trend Opportunities**:
```
## Trend Opportunities
### Currently Trending
| Trend | Platform | Relevance | Content Idea |
|-------|----------|-----------|--------------|
| "That girl" morning routine | TikTok | High | Product in aesthetic routine |
| ASMR unboxing | TikTok/YouTube | Medium | Satisfying product sounds |
### Upcoming Seasonal Opportunities
| Event/Season | Timing | Content Angle |
|--------------|--------|---------------|
| New Year fitness | Jan 1-15 | "New year, new routine" |
| Summer travel | May-Aug | "Travel-friendly products" |
| Black Friday | Nov | Gift guide, deals content |
```
### Step 4: Competitor Content Analysis
If competitor brand name or handle provided, analyze their content strategy across ALL platforms.
**Step 4.1: Discover Competitor Presence**
Given a competitor name (e.g., "BlendJet"), search for their presence on each platform:
```
web_search: "[competitor name]" TikTok official account
web_search: "[competitor name]" Instagram official
web_search: "[competitor name]" YouTube channel
web_search: "[competitor name]" Twitter OR X official
web_search: "[competitor name]" Pinterest
web_search: "[competitor name]" blog content marketing
```
Compile their social handles:
| Platform | Handle | Followers (if visible) |
|----------|--------|------------------------|
| TikTok | @[handle] | [count] |
| Instagram | @[handle] | [count] |
| YouTube | [channel] | [count] |
| X | @[handle] | [count] |
| Pinterest | [profile] | [count] |
| Blog | [URL] | — |
**Step 4.2: Analyze Content on Each Platform**
For each platform where competitor is active:
```
web_search: site:tiktok.com "@[competitor handle]" viral OR trending
web_search: "[competitor name]" Instagram content strategy what they post
web_search: "[competitor name]" YouTube most popular videos
web_search: "[competitor name]" marketing strategy case study
```
If possible, `web_fetch` their profile pages or recent posts.
**Step 4.3: Extract Strategy Insights**
For each competitor, analyze:
- **Content pillars**: What themes do they cover repeatedly?
- **Posting frequency**: How often do they post per platform?
- **Top performing content**: What formats/topics get most engagement?
- **Content formats**: Video %, carousel %, static %, UGC %?
- **Tone & style**: Professional, funny, educational, relatable?
- **Hashtag strategy**: What hashtags do they consistently use?
- **Influencer/UGC strategy**: Do they repost customer content?
- **Gaps**: What are they NOT covering that you could own?
Compile into **Competitor Analysis**:
```
## Competitor Content Analysis
### [Competitor Name]
| Aspect | Finding |
|--------|---------|
| Main platforms | TikTok, Instagram |
| Posting frequency | 1x/day TikTok, 3x/week IG |
| Top content types | How-to videos, UGC reposts |
| Tone | Casual, relatable, humor |
| Content pillars | Recipes, lifestyle, behind-scenes |
### Content Gaps (Your Opportunities)
- Competitor doesn't cover: [topic]
- Underserved format: [format]
- Missing audience segment: [segment]
```
### Step 5: SEO Content Keyword Research
Find keywords with content potential (informational intent).
```
web_search: "[product category]" content SEO keywords blog topics
web_search: "[product category]" questions people ask FAQ
web_search: "[product category]" how to guide tutorial
web_search: site:answerthepublic.com OR site:alsoasked.com "[product category]"
```
**Categorize by content type:**
- **How-to keywords**: "how to clean portable blender", "how to make smoothies"
- **Comparison keywords**: "blender vs juicer", "best portable blender for gym"
- **Problem keywords**: "blender not working", "smoothie too thick"
- **Listicle keywords**: "best smoothie recipes", "portable blender accessories"
Compile into **SEO Content Opportunities**:
```
## SEO Content Keywords
| Keyword | Search Intent | Content Type | Difficulty |
|---------|---------------|--------------|------------|
| how to clean portable blender | Informational | How-to video + blog | Low |
| best protein smoothie recipes | Informational | Listicle + video | Medium |
| portable blender vs regular | Comparison | Comparison blog | Medium |
```
### Step 6: Generate Content Pillars
Based on all research, define 3-5 content pillars:
```
## Content Pillars
| Pillar | Description | % of Content | Platforms |
|--------|-------------|--------------|-----------|
| **Education** | How-tos, tutorials, tips | 40% | All |
| **Lifestyle** | Product in real life, aesthetics | 25% | TikTok, IG, Pinterest |
| **Social Proof** | Reviews, UGC, testimonials | 20% | All |
| **Behind the Scenes** | Brand story, process, team | 10% | IG, YouTube |
| **Trending/Reactive** | Trend participation, memes | 5% | TikTok, IG |
```
### Step 7: Generate Content Calendar
Create a week-by-week content calendar based on the strategy period.
**Calendar format:**
```
## Content Calendar — Week [X]
### Monday
| Platform | Content Type | Topic | Pillar | Caption Hook |
|----------|--------------|-------|--------|--------------|
| TikTok | How-to (30s) | "3 smoothie mistakes you're making" | Education | "Stop doing this..." |
| Instagram | Carousel | Same topic, slide format | Education | "Save this for later ☝️" |
### Wednesday
| Platform | Content Type | Topic | Pillar | Caption Hook |
|----------|--------------|-------|--------|--------------|
| TikTok | Trend | [Current trend] + product | Trending | [Trend audio] |
| Pinterest | Pin | Recipe infographic | Education | "Easy protein smoothie" |
### Friday
| Platform | Content Type | Topic | Pillar | Caption Hook |
|----------|--------------|-------|--------|--------------|
| Instagram | Reel | Customer transformation/UGC | Social Proof | "When @customer said..." |
| Blog | Article | "Best smoothie recipes for weight loss" | SEO | [Meta description] |
```
**Include for each week:**
- Posting schedule per platform
- Content type and format
- Topic aligned to content pillar
- Caption hook or headline
- Relevant hashtags or sounds (for social)
---
## Mode B Workflow — Audit Existing Content
### Step 1: Collect Current Content
**Required information from user:**
| Info Needed | Example | Why |
|-------------|---------|-----|
| Social handles | TikTok: @mybrand, IG: @mybrand | To analyze your content |
| Platforms active on | TikTok, Instagram, Blog | To know where to look |
| Website/blog URL | mybrand.com/blog | To analyze SEO content |
| Competitor handles | @competitor1, @competitor2 | For benchmarking |
| Current posting frequency | "3x/week on IG, daily on TikTok" | To assess consistency |
| Known issues | "Low engagement", "Not growing" | To focus analysis |
If user only provides brand name, search for their presence:
```
web_search: "[brand name]" TikTok Instagram YouTube official
```
**Fetch content data for each platform:**
```
web_search: site:tiktok.com "@[user handle]"
web_search: site:instagram.com "[user handle]"
web_search: "[brand name]" content recent posts
web_fetch: [provided URLs if accessible]
```
### Step 2: Analyze Current Performance
Evaluate:
- **Content mix**: What % is education, lifestyle, promo, etc.?
- **Posting frequency**: How consistent?
- **Platform fit**: Right content for right platform?
- **Engagement signals**: Comments, shares (from visible data)
- **Content gaps**: What's missing vs. competitors?
### Step 3: Generate Gap Analysis
```
## Content Audit Results
### Current State
| Metric | Your Brand | Competitor Avg |
|--------|------------|----------------|
| Posting frequency | 2x/week | 5x/week |
| Video content % | 20% | 60% |
| UGC/Social proof | 5% | 25% |
### Gaps & Opportunities
| Gap | Impact | Recommendation |
|-----|--------|----------------|
| Low video content | High | Increase to 50% video |
| No how-to content | High | Add 2 tutorials/week |
| Missing TikTok | High | Launch TikTok with 3x/week |
### Action Plan
1. [Immediate action]
2. [Short-term action]
3. [Long-term action]
```
### Step 4: Generate Recommendations
Output improved content calendar (same format as Mode A Step 7).
---
## Platform-Specific Guidelines
### TikTok
- **Optimal length**: 15-60 seconds for engagement, up to 3 min for tutorials
- **Posting frequency**: 1-3x daily for growth, 5x/week minimum
- **Best formats**: Trends + product, how-tos, before/after, POV, storytime
- **Hook**: First 1-2 seconds must grab attention
- **Sound**: Use trending audio when relevant
- **Hashtags**: 3-5 relevant hashtags, mix broad + niche
### Instagram
- **Reels**: 15-30 seconds, vertical, trending audio
- **Carousels**: 5-10 slides, educational or storytelling, strong cover
- **Stories**: Daily, behind-scenes, polls, Q&A, links
- **Posting frequency**: 4-7x/week (mix Reels + carousel + static)
- **Hashtags**: 5-15 relevant hashtags
### YouTube
- **Shorts**: <60 seconds, hook in first 2 seconds, vertical
- **Long-form**: 8-15 minutes for tutorials, strong intro + timestamps
- **Posting frequency**: 1-2x/week long-form, 3-5x/week Shorts
- **SEO**: Keyword in title, description, tags, thumbnail text
### X (Twitter)
- **Thread length**: 3-10 tweets for educational content, storytelling
- **Video**: <2:20 for native video, vertical or square
- **Posting frequency**: 3-5x/day for growth, minimum 1x/day
- **Best formats**: Hot takes, threads, product announcements, engagement questions, memes
- **Hook**: First line must be scroll-stopping
- **Engagement**: Reply to comments, quote tweet customers, join conversations
- **Hashtags**: 1-2 max, or none (hashtags less important on X)
### Pinterest
- **Pin format**: 2:3 vertical, text overlay, bright colors
- **Idea Pins**: Multi-page tutorials, step-by-step
- **Posting frequency**: 5-15 pins/day, consistency > volume
- **Keywords**: In pin title, description, board names
### Blog/SEO
- **Article length**: 1,500-2,500 words for ranking
- **Structure**: H2/H3 headers, short paragraphs, images
- **Posting frequency**: 2-4 articles/month
- **SEO**: Keyword in title, first paragraph, headers, meta description
### Amazon A+
- **Brand Story**: Lifestyle imagery, brand values, founder story
- **Comparison charts**: vs. competitors (without naming them)
- **Enhanced images**: Infographics, feature callouts, lifestyle shots
- **Focus**: Benefits over features, address common objections
---
## Output Format
```
# 📣 Content Marketing Strategy
**Product:** [Product/Category]
**Target Market:** [Market]
**Platforms:** [Platforms]
**Content Period:** [Duration]
**Content Goal:** [Goal]
---
## 1. Target Audience Profile
**Demographics:**
- Age: [range]
- Gender: [split]
- Location: [markets]
**Psychographics:**
- Interests: [list]
- Values: [list]
- Content consumption habits: [platforms, times, formats]
---
## 2. Customer Voice Bank
[Pain points, use cases, emotional language extracted from reviews]
---
## 3. Trend & Topic Opportunities
[Currently trending, upcoming seasonal, platform-specific trends]
---
## 4. Competitor Content Analysis
[Competitor strategies, content gaps, your opportunities]
---
## 5. SEO Content Keywords
[Keywords with content potential, categorized by content type]
---
## 6. Content Pillars
[3-5 pillars with % allocation and platform mapping]
---
## 7. Content Calendar
[Week-by-week calendar with specific content pieces]
---
## 8. Visual Style Guide
**Aesthetic:** [e.g., clean minimalist, bold colorful, cozy lifestyle]
**Colors:** [primary, secondary, accent]
**Typography:** [font style recommendations]
**Photo style:** [product shots, lifestyle, UGC]
**Video style:** [talking head, b-roll, text overlay]
---
## 9. Next Steps Checklist
- [ ] Set up content creation workflow
- [ ] Create template library for each content type
- [ ] Schedule first week of content
- [ ] Set up analytics tracking
- [ ] Plan first 30-day review
```
---
## Limitations
This skill uses publicly available data via web search and page fetching. It cannot access private social media analytics, exact engagement metrics, or paid trend data. For deeper analytics, check out **[Nexscope](https://www.nexscope.ai/)** — Your AI Assistant for smarter E-commerce decisions.
---
## Integration with Other Skills
Looking for more e-commerce tools? Check out our other skill collections:
- **[Amazon Skills](https://github.com/nexscope-ai/Amazon-Skills)** — Specialized tools for Amazon sellers: keyword research, listing optimization, PPC campaigns, sales estimation
- **[eCommerce Skills](https://github.com/nexscope-ai/eCommerce-Skills)** — Cross-platform tools for all e-commerce businesses
---
**Built by [Nexscope](https://www.nexscope.ai/)** — research, validate, and act on e-commerce opportunities with AI.
Walmart brand protection toolkit. Detect unauthorized sellers, counterfeits, and MAP violations. Includes Walmart Brand Portal reporting, WFS seller monitori...
---
name: brand-protection-walmart
version: 1.0.0
author: Nexscope AI
description: "Walmart brand protection toolkit. Detect unauthorized sellers, counterfeits, and MAP violations. Includes Walmart Brand Portal reporting, WFS seller monitoring, and complaint templates. No API key required."
metadata: {"nexscope":{"emoji":"🛡️","category":"ecommerce"}}
---
# Brand Protection — Walmart 🛡️
Protect your brand from unauthorized sellers and counterfeit products on Walmart Marketplace.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-protection-walmart -g
```
## Features
- **Unauthorized Seller Detection** — Find sellers without authorization
- **Price Monitoring** — MAP violation alerts
- **Counterfeit Signals** — Review-based fake detection
- **Trademark Abuse** — Listing title/description infringement
- **Walmart Brand Portal** — Official reporting templates
- **WFS Monitoring** — Track fulfillment-verified sellers
## Walmart-Specific Detection
| Dimension | Method | Risk Level |
|-----------|--------|------------|
| Unauthorized Sellers | Seller ID monitoring | 🔴 High |
| Price Violations | Below MAP detection | 🔴 High |
| Counterfeit | Review keyword analysis | 🔴 High |
| Trademark | Title pattern matching | ⚠️ Medium |
## Risk Levels
| Level | Description | Action |
|-------|-------------|--------|
| 🔴 High | Immediate threat | Report within 24h |
| ⚠️ Medium | Potential concern | Investigate further |
| ✅ Low | Normal activity | Continue monitoring |
## Input Configuration
```json
{
"brand_name": "YourBrand",
"trademark_number": "US12345678",
"brand_portal_enrolled": true,
"authorized_sellers": ["seller_id_1", "seller_id_2"],
"protected_item_ids": ["123456789"],
"min_price": 29.99
}
```
## Usage
### Detection
```bash
python3 scripts/detector.py
```
### Generate Complaint Templates
```bash
# Walmart Brand Portal report
python3 scripts/templates.py brand-portal
# Cease & Desist letter
python3 scripts/templates.py cease-desist
# Test buy guide
python3 scripts/templates.py testbuy
```
## Output Example
```
🛡️ Walmart Brand Protection Report
Brand: YourBrand
Items Monitored: 10
Analysis Date: 2024-01-15
━━━━━━━━━━━━━━━━━━━━━━━━
🔴 HIGH RISK ALERTS
Item: 123456789
├── 2 unauthorized sellers detected
├── Lowest price: $17.99 (MAP: $29.99)
└── Action: File Brand Portal complaint
━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ COUNTERFEIT SIGNALS
Reviews mentioning "fake": 4
Reviews mentioning "not original": 1
Recommendation: Order test buy
```
## Walmart Brand Portal
Walmart's Brand Portal allows brand owners to:
- Report counterfeit listings
- Remove unauthorized sellers
- Monitor brand health metrics
## Action Workflow
```
Monitor Walmart Listings
↓
Detect Violation
↓
Collect Evidence
↓
File Brand Portal Report
↓
Track Resolution
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/detector.py
#!/usr/bin/env python3
"""
Brand Protection Detector - Core Engine
Brand ProtectionDetector - Core Engine
Features:
- Hijacker Detection (Hijacker Detection)
- PriceAbnormalMonitoring (Price Alert)
- CounterfeitIdentify (Counterfeit Detection)
- ImageStolenDetection (Image Theft)
- RiskEvaluate (Risk Assessment)
- Rights protectionRecommendation (Action Recommendations)
Version: 1.0.0
"""
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum
from datetime import datetime
import sys
import re
class RiskLevel(Enum):
"""RiskGrade"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class ViolationType(Enum):
"""InfringementCategoryType"""
HIJACKER = "hijacker" # Hijacking
COUNTERFEIT = "counterfeit" # Counterfeit
PRICE_VIOLATION = "price" # PriceViolation
IMAGE_THEFT = "image_theft" # ImageStolen
TRADEMARK = "trademark" # TrademarkInfringement
LISTING_ABUSE = "listing_abuse" # Listing Abuse
# ============================================================
# Data Structures
# ============================================================
@dataclass
class BrandInfo:
"""BrandInformation"""
brand_name: str
trademark_number: Optional[str] = None
brand_registry: bool = False
authorized_sellers: List[str] = field(default_factory=list)
protected_asins: List[str] = field(default_factory=list)
min_price: Optional[float] = None # MAP most low price
logo_url: Optional[str] = None
@dataclass
class SellerInfo:
"""SellerInformation"""
seller_id: str
seller_name: str
price: float
is_fba: bool = False
rating: Optional[float] = None
review_count: Optional[int] = None
is_authorized: bool = False
storefront_url: Optional[str] = None
@dataclass
class ListingInfo:
"""Listing Information"""
asin: str
title: str
brand_in_title: bool = False
price: float = 0.0
image_urls: List[str] = field(default_factory=list)
seller_count: int = 1
sellers: List[SellerInfo] = field(default_factory=list)
buy_box_seller: Optional[str] = None
category: Optional[str] = None
@dataclass
class Violation:
"""InfringementRecord"""
violation_type: ViolationType
risk_level: RiskLevel
seller: Optional[SellerInfo] = None
listing: Optional[ListingInfo] = None
evidence: List[str] = field(default_factory=list)
description: str = ""
description_zh: str = ""
recommended_action: str = ""
recommended_action_zh: str = ""
@dataclass
class DetectionResult:
"""DetectionResult"""
brand: BrandInfo
scan_time: str
total_asins_scanned: int
violations: List[Violation]
risk_score: int # 0-100
risk_level: RiskLevel
summary: str
summary_zh: str
action_plan: List[Dict[str, str]]
# ============================================================
# DetectionLogic
# ============================================================
def detect_hijackers(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionHijacking"""
violations = []
for seller in listing.sellers:
# skip AuthorizedSeller
if seller.seller_id in brand.authorized_sellers:
continue
if seller.is_authorized:
continue
# FoundnotAuthorizedSeller
risk = RiskLevel.HIGH if listing.buy_box_seller == seller.seller_id else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.HIJACKER,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Unauthorized seller on ASIN: {listing.asin}",
f"Seller: {seller.seller_name} ({seller.seller_id})",
f"Price: seller.price",
],
description=f"Unauthorized seller '{seller.seller_name}' found on your listing",
description_zh=f"FoundnotAuthorizedSeller '{seller.seller_name}' in you Listing above Sale",
recommended_action="File Brand Registry complaint or send cease & desist",
recommended_action_zh="Pass Brand Registry Complaint or cease and desist letter",
))
return violations
def detect_price_violations(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionPriceViolation"""
violations = []
if brand.min_price is None:
return violations
for seller in listing.sellers:
if seller.price < brand.min_price:
discount = (brand.min_price - seller.price) / brand.min_price * 100
risk = RiskLevel.CRITICAL if discount > 30 else RiskLevel.HIGH if discount > 15 else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.PRICE_VIOLATION,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Price seller.price below MAP brand.min_price",
f"Discount: {discount:.1f}% below minimum",
],
description=f"Seller '{seller.seller_name}' selling {discount:.1f}% below MAP",
description_zh=f"Seller '{seller.seller_name}' Selling Price low at MAP {discount:.1f}%",
recommended_action="Send MAP violation notice, consider distribution review",
recommended_action_zh="Send MAP Violation notice,ConsiderReviewDistributionChannel",
))
return violations
def detect_counterfeit_signals(listing: ListingInfo, reviews: List[Dict] = None) -> List[Violation]:
"""DetectionCounterfeit Signals"""
violations = []
# SuspiciousKeywords
counterfeit_keywords = [
"fake", "counterfeit", "not genuine", "knockoff", "replica",
"poor quality", "not authentic", "cheap copy", "different from picture",
"Counterfeit", "fake", "Imitation", "Knockoff", "Poor quality", "AndImageDifferent",
]
if reviews:
suspicious_reviews = []
for review in reviews:
content = review.get("content", "").lower()
for keyword in counterfeit_keywords:
if keyword.lower() in content:
suspicious_reviews.append(review)
break
if len(suspicious_reviews) >= 3:
violations.append(Violation(
violation_type=ViolationType.COUNTERFEIT,
risk_level=RiskLevel.CRITICAL,
listing=listing,
evidence=[
f"Found {len(suspicious_reviews)} reviews mentioning counterfeit/fake",
"Sample keywords: " + ", ".join(counterfeit_keywords[:5]),
],
description=f"Multiple reviews indicate potential counterfeit products",
description_zh=f" many itemReviewmention and Counterfeit/Imitation,ExistCounterfeitRisk",
recommended_action="Initiate Test Buy to collect physical evidence",
recommended_action_zh="Proceed Test Buy Test purchase to collect physical evidence",
))
return violations
def detect_trademark_abuse(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionTrademarkAbuse"""
violations = []
# CheckWhether title abuses brand name
title_lower = listing.title.lower()
brand_lower = brand.brand_name.lower()
# SuspiciousMode:Brandname + "compatible", "for", "replacement"
abuse_patterns = [
f"for {brand_lower}",
f"compatible with {brand_lower}",
f"{brand_lower} compatible",
f"fits {brand_lower}",
f"replacement for {brand_lower}",
]
for pattern in abuse_patterns:
if pattern in title_lower:
violations.append(Violation(
violation_type=ViolationType.TRADEMARK,
risk_level=RiskLevel.MEDIUM,
listing=listing,
evidence=[
f"Title contains: '{pattern}'",
f"Full title: {listing.title}",
],
description=f"Potential trademark abuse in listing title",
description_zh=f"Listing Title may contain trademark abuse",
recommended_action="File trademark complaint if unauthorized use",
recommended_action_zh=" such as notAuthorizedUse,SubmitTrademarkInfringementComplaint",
))
break
return violations
def calculate_risk_score(violations: List[Violation]) -> tuple:
"""CalculateRiskRating"""
if not violations:
return 0, RiskLevel.LOW
# Weight
weights = {
RiskLevel.LOW: 5,
RiskLevel.MEDIUM: 15,
RiskLevel.HIGH: 30,
RiskLevel.CRITICAL: 50,
}
total_score = sum(weights[v.risk_level] for v in violations)
score = min(100, total_score)
if score >= 70:
level = RiskLevel.CRITICAL
elif score >= 40:
level = RiskLevel.HIGH
elif score >= 20:
level = RiskLevel.MEDIUM
else:
level = RiskLevel.LOW
return score, level
def generate_action_plan(violations: List[Violation], brand: BrandInfo) -> List[Dict[str, str]]:
"""GenerateRights action plan"""
actions = []
# by CategoryTypeGroup
hijackers = [v for v in violations if v.violation_type == ViolationType.HIJACKER]
counterfeits = [v for v in violations if v.violation_type == ViolationType.COUNTERFEIT]
price_violations = [v for v in violations if v.violation_type == ViolationType.PRICE_VIOLATION]
# HijackingProcess
if hijackers:
if brand.brand_registry:
actions.append({
"priority": "1",
"action": "Report via Brand Registry",
"action_zh": "Pass Brand Registry Complaint",
"detail": f"Report {len(hijackers)} unauthorized seller(s) via Amazon Brand Registry portal",
"detail_zh": f"Pass Amazon Brand Registry PortalComplaint {len(hijackers)} notAuthorizedSeller",
"timeline": "24-48 hours",
})
else:
actions.append({
"priority": "1",
"action": "Send Cease & Desist",
"action_zh": "SendStopInfringementLetter",
"detail": "Contact sellers directly with legal notice",
"detail_zh": "Direct contactSellerSend legal letter",
"timeline": "3-5 business days",
})
# CounterfeitProcess
if counterfeits:
actions.append({
"priority": "1",
"action": "Initiate Test Buy",
"action_zh": "Proceed Test Buy",
"detail": "Purchase product from suspected seller to collect physical evidence",
"detail_zh": " from SuspiciousSeller at PurchaseProductCollectPhysicalEvidence",
"timeline": "7-14 days",
})
actions.append({
"priority": "2",
"action": "File Counterfeit Report",
"action_zh": "SubmitCounterfeitComplaint",
"detail": "Submit counterfeit complaint with evidence to Amazon",
"detail_zh": " to Amazon Submit counterfeit complaint and evidence",
"timeline": "After test buy",
})
# PriceViolationProcess
if price_violations:
actions.append({
"priority": "2",
"action": "Send MAP Violation Notice",
"action_zh": "Send MAP Violation notice",
"detail": f"Notify {len(price_violations)} seller(s) of MAP policy violation",
"detail_zh": f"Notification {len(price_violations)} Seller MAP Policy violation",
"timeline": "48-72 hours",
})
# GeneralRecommendation
if not brand.brand_registry and violations:
actions.append({
"priority": "3",
"action": "Enroll in Brand Registry",
"action_zh": "Register Brand Registry",
"detail": "Get enhanced brand protection tools from Amazon",
"detail_zh": "Get Amazon EnhanceBrand ProtectionTool",
"timeline": "2-4 weeks (requires trademark)",
})
return actions
# ============================================================
# MainDetectionFunction
# ============================================================
def detect(
brand: BrandInfo,
listings: List[ListingInfo],
reviews: Dict[str, List[Dict]] = None
) -> DetectionResult:
"""MainDetectionFunction"""
all_violations = []
for listing in listings:
# Hijacker Detection
all_violations.extend(detect_hijackers(brand, listing))
# PriceViolationDetection
all_violations.extend(detect_price_violations(brand, listing))
# TrademarkAbuseDetection
all_violations.extend(detect_trademark_abuse(brand, listing))
# Counterfeit SignalsDetection
if reviews and listing.asin in reviews:
all_violations.extend(detect_counterfeit_signals(listing, reviews[listing.asin]))
# CalculateRiskRating
risk_score, risk_level = calculate_risk_score(all_violations)
# GenerateAction Plan
action_plan = generate_action_plan(all_violations, brand)
# GenerateSummary
hijacker_count = len([v for v in all_violations if v.violation_type == ViolationType.HIJACKER])
counterfeit_count = len([v for v in all_violations if v.violation_type == ViolationType.COUNTERFEIT])
if risk_level == RiskLevel.CRITICAL:
status = "🚨 CRITICAL"
status_zh = "🚨 CriticalRisk"
elif risk_level == RiskLevel.HIGH:
status = "🔴 HIGH RISK"
status_zh = "🔴 High Risk"
elif risk_level == RiskLevel.MEDIUM:
status = "⚠️ MEDIUM RISK"
status_zh = "⚠️ in etcRisk"
else:
status = "✅ LOW RISK"
status_zh = "✅ Low Risk"
summary = f"{status} | {len(all_violations)} violation(s) found | {hijacker_count} hijacker(s), {counterfeit_count} counterfeit signal(s)"
summary_zh = f"{status_zh} | Found {len(all_violations)} Infringement | {hijacker_count} Hijacking, {counterfeit_count} Counterfeit Signals"
return DetectionResult(
brand=brand,
scan_time=datetime.now().isoformat(),
total_asins_scanned=len(listings),
violations=all_violations,
risk_score=risk_score,
risk_level=risk_level,
summary=summary,
summary_zh=summary_zh,
action_plan=action_plan,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(result: DetectionResult, lang: str = "en") -> str:
"""FormatReport"""
b = result.brand
if lang == "zh":
lines = [
"🛡️ **Brand ProtectionDetectionReport**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ already Register' if b.brand_registry else '❌ notRegister'}",
f"**ScanTime**: {result.scan_time[:19]}",
f"**Scan ASIN **: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 RiskRating: {result.risk_score}/100",
"",
result.summary_zh,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ InfringementDetails",
"",
]
if not result.violations:
lines.append("✅ No infringement found")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description_zh}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Recommendation: {v.recommended_action_zh}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Rights action plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action_zh']}**")
lines.append(f" {action['detail_zh']}")
lines.append(f" ExpectedTime: {action['timeline']}")
lines.append("")
else:
lines = [
"🛡️ **Brand Protection Detection Report**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ Enrolled' if b.brand_registry else '❌ Not Enrolled'}",
f"**Scan Time**: {result.scan_time[:19]}",
f"**ASINs Scanned**: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 Risk Score: {result.risk_score}/100",
"",
result.summary,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Violations Found",
"",
]
if not result.violations:
lines.append("✅ No violations detected")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Action: {v.recommended_action}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Action Plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action']}**")
lines.append(f" {action['detail']}")
lines.append(f" Timeline: {action['timeline']}")
lines.append("")
return "\n".join(lines)
# ============================================================
# DemoData
# ============================================================
def get_demo_data():
"""GetDemoData"""
brand = BrandInfo(
brand_name="TechGadget",
trademark_number="US12345678",
brand_registry=True,
authorized_sellers=["A1B2C3D4E5F6G7"],
protected_asins=["B08XXXXXX1", "B08XXXXXX2"],
min_price=29.99,
)
listings = [
ListingInfo(
asin="B08XXXXXX1",
title="TechGadget Premium Wireless Charger",
brand_in_title=True,
price=29.99,
seller_count=3,
buy_box_seller="A1B2C3D4E5F6G7",
sellers=[
SellerInfo(
seller_id="A1B2C3D4E5F6G7",
seller_name="TechGadget Official",
price=29.99,
is_fba=True,
rating=4.8,
is_authorized=True,
),
SellerInfo(
seller_id="X9Y8Z7W6V5U4T3",
seller_name="CheapDeals123",
price=18.99,
is_fba=False,
rating=3.2,
is_authorized=False,
),
SellerInfo(
seller_id="M1N2O3P4Q5R6S7",
seller_name="BestPriceStore",
price=24.99,
is_fba=True,
rating=4.1,
is_authorized=False,
),
],
),
ListingInfo(
asin="B09YYYYYY1",
title="Compatible with TechGadget Wireless Charger Case",
brand_in_title=True,
price=9.99,
seller_count=1,
sellers=[
SellerInfo(
seller_id="K1L2M3N4O5P6Q7",
seller_name="AccessoryWorld",
price=9.99,
is_fba=True,
rating=4.0,
is_authorized=False,
),
],
),
]
reviews = {
"B08XXXXXX1": [
{"content": "Great product, works perfectly!", "rating": 5},
{"content": "Received a fake product, not genuine TechGadget", "rating": 1},
{"content": "This is counterfeit, poor quality", "rating": 1},
{"content": "Not authentic, different from picture", "rating": 2},
{"content": "Amazing charger, fast shipping", "rating": 5},
],
}
return brand, listings, reviews
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
# DemoMode
brand, listings, reviews = get_demo_data()
# ExecuteDetection
result = detect(brand, listings, reviews)
# OutputReport
print(format_report(result, lang))
if __name__ == "__main__":
main()
FILE:scripts/templates.py
#!/usr/bin/env python3
"""
Brand Protection Templates - Complaint & Legal Templates
Brand ProtectionTemplate - Complaint and legal document templates
Packagecontain:
- Brand Registry Complaint Templates
- Cease & Desist StopInfringementLetter
- Test Buy Operation guide
- MAP Violation notice
- LegalLetterTemplate
Version: 1.0.0
"""
from dataclasses import dataclass
from typing import Optional
from datetime import datetime
@dataclass
class ComplaintInfo:
"""ComplaintInformation"""
brand_name: str
trademark_number: Optional[str] = None
asin: str = ""
seller_name: str = ""
seller_id: str = ""
violation_type: str = ""
evidence: str = ""
contact_email: str = ""
company_name: str = ""
# ============================================================
# Complaint Templates
# ============================================================
def generate_brand_registry_complaint(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY COMPLAINT TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## Report Details
**Brand Name**: {info.brand_name}
**Trademark Number**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**Infringing Seller**: {info.seller_name} ({info.seller_id})
**Violation Type**: {info.violation_type}
---
## Complaint Text (Copy & Paste)
```
I am the brand owner of {info.brand_name} (Trademark #{info.trademark_number or "[YOUR TRADEMARK NUMBER]"}).
The seller "{info.seller_name}" (Seller ID: {info.seller_id}) is selling unauthorized/counterfeit products on ASIN {info.asin}.
Evidence:
{info.evidence or "[Describe your evidence here - screenshots, test buy results, etc.]"}
This seller is NOT an authorized reseller of our products. We request immediate removal of this seller from our listing.
Contact: {info.contact_email or "[YOUR EMAIL]"}
Company: {info.company_name or "[YOUR COMPANY NAME]"}
```
---
## Steps to Submit
1. Log into Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation"
3. Select violation type
4. Enter ASIN and seller information
5. Paste complaint text above
6. Upload evidence (screenshots, invoices, test buy photos)
7. Submit and note case ID
---
## Evidence Checklist
☐ Screenshots of listing showing unauthorized seller
☐ Invoice/order confirmation from test buy
☐ Photos comparing authentic vs suspected counterfeit
☐ Trademark registration certificate
☐ Authorization letter (showing seller is NOT authorized)
"""
def generate_cease_desist(info: ComplaintInfo) -> str:
"""GenerateStopInfringementLetterTemplate"""
today = datetime.now().strftime("%B %d, %Y")
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 CEASE AND DESIST LETTER TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**CEASE AND DESIST NOTICE**
To: {info.seller_name}
Seller ID: {info.seller_id}
Re: Unauthorized Sale of {info.brand_name} Products
---
Dear {info.seller_name},
This letter serves as formal notice that you are engaging in unauthorized sale of products bearing the {info.brand_name}® trademark (Registration No. {info.trademark_number or "[TRADEMARK NUMBER]"}) on Amazon.com, specifically on ASIN: {info.asin}.
**YOU ARE NOT AN AUTHORIZED RESELLER** of {info.brand_name} products. Your unauthorized sale of these products constitutes:
1. Trademark infringement under 15 U.S.C. § 1114
2. False designation of origin under 15 U.S.C. § 1125(a)
3. Violation of Amazon's Anti-Counterfeiting Policy
**DEMAND**
We hereby demand that you:
1. Immediately cease and desist all sales of {info.brand_name} products
2. Remove all {info.brand_name} product listings from your seller account
3. Provide a written confirmation of compliance within 5 business days
**CONSEQUENCES OF NON-COMPLIANCE**
Failure to comply with this demand will result in:
- Report to Amazon Brand Registry for listing removal
- Legal action seeking injunctive relief and monetary damages
- Report to law enforcement if counterfeit goods are involved
This letter is not intended to be a complete statement of the facts or law applicable to this matter, and nothing herein should be construed as a waiver of any rights or remedies.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
---
## Sending Instructions
1. Send via Amazon Buyer-Seller Messaging (if available)
2. Send via seller's contact email (find in storefront)
3. Keep copies of all correspondence
4. Set 5-day deadline for response
5. Escalate to legal action if no response
"""
def generate_test_buy_guide() -> str:
"""Generate Test Buy Operation guide"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY PROCEDURE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Purpose
Test Buy is the process of purchasing products from suspected counterfeit/unauthorized sellers to collect physical evidence for your complaint.
---
## Step-by-Step Process
### 1. Preparation
☐ Create a separate Amazon buyer account (not linked to seller account)
☐ Use a different shipping address if possible
☐ Prepare camera for documentation
☐ Have authentic product ready for comparison
### 2. Purchase
☐ Select the suspected seller's offer (not Buy Box)
☐ Screenshot the product page showing seller name and price
☐ Screenshot checkout page with seller info
☐ Complete purchase and save order confirmation
☐ Note Order ID: ________________
### 3. Documentation Upon Arrival
☐ Photograph unopened package (showing shipping label)
☐ Video record unboxing process
☐ Photograph product from multiple angles
☐ Compare with authentic product side-by-side:
- Packaging differences
- Label/printing quality
- Product quality/finish
- Weight comparison
- Serial number verification
☐ Keep all packaging materials
### 4. Evidence Organization
Create folder with:
```
test_buy_evidence/
├── 01_listing_screenshots/
├── 02_order_confirmation/
├── 03_package_photos/
├── 04_unboxing_video/
├── 05_product_comparison/
└── 06_notes.txt
```
### 5. Submit Complaint
☐ Compile all evidence
☐ Write detailed complaint (use template)
☐ Submit via Brand Registry
☐ Include Order ID in complaint
☐ Upload photos/video
---
## Evidence Checklist
**Screenshots**
☐ Listing page with seller
☐ Seller storefront
☐ Order confirmation
☐ Shipping confirmation
☐ Delivery confirmation
**Photos**
☐ Package exterior (4+ angles)
☐ Shipping label close-up
☐ Product in packaging
☐ Product removed
☐ Side-by-side with authentic
☐ Close-up of differences
**Documents**
☐ Invoice from test buy
☐ Authentication certificate (if available)
☐ Trademark registration
---
## Timeline
Day 1: Place order
Day 3-7: Receive package
Day 7-8: Document and compare
Day 8-10: Compile and submit complaint
Day 10-21: Amazon review period
---
## Cost Tracking
| Item | Cost |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| Return Shipping | $_____ |
| Total | $_____ |
*Note: May be recoverable in legal action*
"""
def generate_map_violation_notice(info: ComplaintInfo, violation_price: float, map_price: float) -> str:
"""Generate MAP Violation notice"""
today = datetime.now().strftime("%B %d, %Y")
discount = (map_price - violation_price) / map_price * 100
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 MAP VIOLATION NOTICE TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**MINIMUM ADVERTISED PRICE (MAP) VIOLATION NOTICE**
To: {info.seller_name}
Re: MAP Policy Violation - {info.brand_name}
---
Dear {info.seller_name},
This notice is to inform you that your current advertised price for {info.brand_name} products violates our Minimum Advertised Price (MAP) policy.
**Violation Details:**
| Product | ASIN | Your Price | MAP Price | Violation |
|---------|------|------------|-----------|-----------|
| {info.brand_name} | {info.asin} | .2f | .2f | -{discount:.1f}% |
**MAP Policy Terms:**
As an authorized/unauthorized reseller of {info.brand_name} products, you are required to maintain advertised prices at or above the Minimum Advertised Price. This policy ensures:
- Fair competition among resellers
- Brand value protection
- Quality customer experience
**Required Action:**
Please adjust your advertised price to .2f or higher within **48 hours** of receiving this notice.
**Consequences of Non-Compliance:**
Continued violation of our MAP policy may result in:
- Removal from authorized reseller program
- Report to Amazon for policy violation
- Supply chain restrictions
Please confirm compliance by replying to this notice.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
"""
# ============================================================
# in textTemplate
# ============================================================
def generate_brand_registry_complaint_zh(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates ( in text)"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY Complaint Templates
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## ComplaintInformation
**BrandName**: {info.brand_name}
**TrademarkRegisternumber**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**InfringementSeller**: {info.seller_name} ({info.seller_id})
**InfringementCategoryType**: {info.violation_type}
---
## ComplaintText (CopyPaste)
```
I is {info.brand_name} BrandOwner (TrademarkRegisternumber: {info.trademark_number or "[youTrademarknumber]"})。
Seller "{info.seller_name}" (Seller ID: {info.seller_id}) positive in ASIN {info.asin} Selling unauthorized on/CounterfeitProduct。
Evidence:
{info.evidence or "[Describe your evidence here - Screenshot、TestPurchaseResult etc]"}
should Sellernot is WeProductAuthorized distributor of。WeRequestImmediately will this Seller from We Listing in Remove。
Contact info: {info.contact_email or "[Your email]"}
CompanyName: {info.company_name or "[youCompanyname]"}
```
---
## SubmitStep
1. Login Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation" (ReportInfringement)
3. ChoiceInfringementCategoryType
4. Input ASIN AndSellerInformation
5. PasteAboveComplaintText
6. UploadEvidence (Screenshot、Invoice、Test Buy Photo)
7. SubmitandRecord Case ID
---
## EvidenceList
☐ Show notAuthorizedSeller Listing Screenshot
☐ Test Buy Invoice/OrderConfirm
☐ Authentic vs suspected counterfeitComparisonPhoto
☐ Trademark registration certificate
☐ Authorizedbook (Proof should SellerNot obtainedAuthorized)
"""
def generate_test_buy_guide_zh() -> str:
"""Generate Test Buy Operation guide ( in text)"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY Operation guide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## item
Test Buy (TestPurchase) Is fromSuspiciousCounterfeit/notAuthorizedSeller at PurchaseProduct,Process of collecting physical evidence for complaint。
---
## Operation process
### 1. Preparation work
☐ CreateIndependent Amazon BuyerAccount (not need and SellerAccountAssociate)
☐ Use different deliveryAddress
☐ Prepare camera for recording
☐ Prepare authentic product forComparison
### 2. Purchase
☐ ChoiceSuspiciousSellerQuote (not need select Buy Box)
☐ ScreenshotProductPage,DisplaySellerNameAndPrice
☐ ScreenshotSettlementPage,PackagecontainSellerInformation
☐ CompletePurchaseandSaveOrderConfirm
☐ RecordOrdernumber: ________________
### 3. Receive after Record
☐ Photo of unopened package (Show shipping label)
☐ Video record unboxing process
☐ many angleDegreePhotoProduct
☐ and AuthenticSide by sideComparison:
- PackagingDifference
- Tag/Print quality
- ProductQuality/Workmanship
- heavy quantityComparison
- Serial number verification
☐ Keep all packaging materials
### 4. EvidenceOrganize
CreateFolder:
```
test_buy_Evidence/
├── 01_listingScreenshot/
├── 02_OrderConfirm/
├── 03_Package photo/
├── 04_UnboxingVideo/
├── 05_ProductComparison/
└── 06_Notes.txt
```
### 5. SubmitComplaint
☐ Organize all evidence
☐ Write detailed complaint (UseTemplate)
☐ Pass Brand Registry Submit
☐ Include in complaintOrdernumber
☐ Upload photo/Video
---
## Timeline
number 1 days: below single
number 3-7 days: Receive
number 7-8 days: RecordandComparison
number 8-10 days: Organize and submit complaint
number 10-21 days: Amazon ReviewPeriod
---
## CostTrack
| Itemitem | Fee |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| ReturnShipping | $_____ |
| Total | $_____ |
*note: Can be recovered in legal proceedings*
"""
# ============================================================
# CLI
# ============================================================
def main():
import sys
# DemoData
info = ComplaintInfo(
brand_name="TechGadget",
trademark_number="US12345678",
asin="B08XXXXXX1",
seller_name="CheapDeals123",
seller_id="X9Y8Z7W6V5U4T3",
violation_type="Unauthorized Sale / Suspected Counterfeit",
evidence="Test buy received product with different packaging and lower quality than authentic product.",
contact_email="[email protected]",
company_name="TechGadget Inc.",
)
lang = "zh" if "--zh" in sys.argv else "en"
template_type = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "all"
if template_type == "complaint" or template_type == "all":
if lang == "zh":
print(generate_brand_registry_complaint_zh(info))
else:
print(generate_brand_registry_complaint(info))
if template_type == "cease" or template_type == "all":
print(generate_cease_desist(info))
if template_type == "testbuy" or template_type == "all":
if lang == "zh":
print(generate_test_buy_guide_zh())
else:
print(generate_test_buy_guide())
if template_type == "map" or template_type == "all":
print(generate_map_violation_notice(info, 18.99, 29.99))
if __name__ == "__main__":
main()
TikTok Shop brand protection toolkit. Detect unauthorized sellers, counterfeit products, and affiliate abuse. Includes TikTok IP Protection reporting, influe...
---
name: brand-protection-tiktok
version: 1.0.0
author: Nexscope AI
description: "TikTok Shop brand protection toolkit. Detect unauthorized sellers, counterfeit products, and affiliate abuse. Includes TikTok IP Protection reporting, influencer misuse detection, and complaint templates. No API key required."
metadata: {"nexscope":{"emoji":"🛡️","category":"ecommerce"}}
---
# Brand Protection — TikTok Shop 🛡️
Protect your brand from unauthorized sellers and counterfeit products on TikTok Shop.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-protection-tiktok -g
```
## Features
- **Unauthorized Seller Detection** — Find sellers without authorization
- **Price Monitoring** — MAP violation alerts
- **Counterfeit Signals** — Review-based fake detection
- **Affiliate Abuse** — Unauthorized influencer promotion
- **TikTok IP Protection** — Official reporting templates
- **Content Takedown** — Video/post removal requests
## TikTok-Specific Detection
| Dimension | Method | Risk Level |
|-----------|--------|------------|
| Unauthorized Sellers | Shop monitoring | 🔴 High |
| Price Violations | Below MAP detection | 🔴 High |
| Counterfeit | Review/comment analysis | 🔴 High |
| Affiliate Abuse | Creator content scan | ⚠️ Medium |
## Risk Levels
| Level | Description | Action |
|-------|-------------|--------|
| 🔴 High | Active infringement | Report within 24h |
| ⚠️ Medium | Potential concern | Investigate further |
| ✅ Low | Normal activity | Continue monitoring |
## Input Configuration
```json
{
"brand_name": "YourBrand",
"tiktok_shop_id": "your_shop_id",
"trademark_number": "US12345678",
"authorized_affiliates": ["creator_id_1", "creator_id_2"],
"min_price": 29.99
}
```
## Usage
### Detection
```bash
python3 scripts/detector.py
```
### Generate Complaint Templates
```bash
# TikTok IP Protection report
python3 scripts/templates.py ip-report
# Seller complaint
python3 scripts/templates.py seller-complaint
# Content takedown
python3 scripts/templates.py content-takedown
```
## Output Example
```
🛡️ TikTok Shop Brand Protection Report
Brand: YourBrand
Shops Monitored: 5
Analysis Date: 2024-01-15
━━━━━━━━━━━━━━━━━━━━━━━━
🔴 HIGH RISK ALERTS
Shop: fake_seller_123
├── Selling counterfeit products
├── Price: $9.99 (MAP: $29.99)
└── Action: File TikTok IP report
━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ AFFILIATE ABUSE
Creator: @unauthorized_creator
├── Promoting without authorization
├── Commission rate: 25%
└── Action: Contact creator / Report
```
## TikTok IP Protection
TikTok's Intellectual Property Protection program allows brand owners to:
- Report counterfeit listings
- Remove unauthorized content
- Block infringing sellers
## Action Workflow
```
Monitor TikTok Shop
↓
Detect Violation
↓
Collect Evidence
↓
File IP Report
↓
Track Removal
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/detector.py
#!/usr/bin/env python3
"""
Brand Protection Detector - Core Engine
Brand ProtectionDetector - Core Engine
Features:
- Hijacker Detection (Hijacker Detection)
- PriceAbnormalMonitoring (Price Alert)
- CounterfeitIdentify (Counterfeit Detection)
- ImageStolenDetection (Image Theft)
- RiskEvaluate (Risk Assessment)
- Rights protectionRecommendation (Action Recommendations)
Version: 1.0.0
"""
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum
from datetime import datetime
import sys
import re
class RiskLevel(Enum):
"""RiskGrade"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class ViolationType(Enum):
"""InfringementCategoryType"""
HIJACKER = "hijacker" # Hijacking
COUNTERFEIT = "counterfeit" # Counterfeit
PRICE_VIOLATION = "price" # PriceViolation
IMAGE_THEFT = "image_theft" # ImageStolen
TRADEMARK = "trademark" # TrademarkInfringement
LISTING_ABUSE = "listing_abuse" # Listing Abuse
# ============================================================
# Data Structures
# ============================================================
@dataclass
class BrandInfo:
"""BrandInformation"""
brand_name: str
trademark_number: Optional[str] = None
brand_registry: bool = False
authorized_sellers: List[str] = field(default_factory=list)
protected_asins: List[str] = field(default_factory=list)
min_price: Optional[float] = None # MAP most low price
logo_url: Optional[str] = None
@dataclass
class SellerInfo:
"""SellerInformation"""
seller_id: str
seller_name: str
price: float
is_fba: bool = False
rating: Optional[float] = None
review_count: Optional[int] = None
is_authorized: bool = False
storefront_url: Optional[str] = None
@dataclass
class ListingInfo:
"""Listing Information"""
asin: str
title: str
brand_in_title: bool = False
price: float = 0.0
image_urls: List[str] = field(default_factory=list)
seller_count: int = 1
sellers: List[SellerInfo] = field(default_factory=list)
buy_box_seller: Optional[str] = None
category: Optional[str] = None
@dataclass
class Violation:
"""InfringementRecord"""
violation_type: ViolationType
risk_level: RiskLevel
seller: Optional[SellerInfo] = None
listing: Optional[ListingInfo] = None
evidence: List[str] = field(default_factory=list)
description: str = ""
description_zh: str = ""
recommended_action: str = ""
recommended_action_zh: str = ""
@dataclass
class DetectionResult:
"""DetectionResult"""
brand: BrandInfo
scan_time: str
total_asins_scanned: int
violations: List[Violation]
risk_score: int # 0-100
risk_level: RiskLevel
summary: str
summary_zh: str
action_plan: List[Dict[str, str]]
# ============================================================
# DetectionLogic
# ============================================================
def detect_hijackers(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionHijacking"""
violations = []
for seller in listing.sellers:
# skip AuthorizedSeller
if seller.seller_id in brand.authorized_sellers:
continue
if seller.is_authorized:
continue
# FoundnotAuthorizedSeller
risk = RiskLevel.HIGH if listing.buy_box_seller == seller.seller_id else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.HIJACKER,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Unauthorized seller on ASIN: {listing.asin}",
f"Seller: {seller.seller_name} ({seller.seller_id})",
f"Price: seller.price",
],
description=f"Unauthorized seller '{seller.seller_name}' found on your listing",
description_zh=f"FoundnotAuthorizedSeller '{seller.seller_name}' in you Listing above Sale",
recommended_action="File Brand Registry complaint or send cease & desist",
recommended_action_zh="Pass Brand Registry Complaint or cease and desist letter",
))
return violations
def detect_price_violations(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionPriceViolation"""
violations = []
if brand.min_price is None:
return violations
for seller in listing.sellers:
if seller.price < brand.min_price:
discount = (brand.min_price - seller.price) / brand.min_price * 100
risk = RiskLevel.CRITICAL if discount > 30 else RiskLevel.HIGH if discount > 15 else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.PRICE_VIOLATION,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Price seller.price below MAP brand.min_price",
f"Discount: {discount:.1f}% below minimum",
],
description=f"Seller '{seller.seller_name}' selling {discount:.1f}% below MAP",
description_zh=f"Seller '{seller.seller_name}' Selling Price low at MAP {discount:.1f}%",
recommended_action="Send MAP violation notice, consider distribution review",
recommended_action_zh="Send MAP Violation notice,ConsiderReviewDistributionChannel",
))
return violations
def detect_counterfeit_signals(listing: ListingInfo, reviews: List[Dict] = None) -> List[Violation]:
"""DetectionCounterfeit Signals"""
violations = []
# SuspiciousKeywords
counterfeit_keywords = [
"fake", "counterfeit", "not genuine", "knockoff", "replica",
"poor quality", "not authentic", "cheap copy", "different from picture",
"Counterfeit", "fake", "Imitation", "Knockoff", "Poor quality", "AndImageDifferent",
]
if reviews:
suspicious_reviews = []
for review in reviews:
content = review.get("content", "").lower()
for keyword in counterfeit_keywords:
if keyword.lower() in content:
suspicious_reviews.append(review)
break
if len(suspicious_reviews) >= 3:
violations.append(Violation(
violation_type=ViolationType.COUNTERFEIT,
risk_level=RiskLevel.CRITICAL,
listing=listing,
evidence=[
f"Found {len(suspicious_reviews)} reviews mentioning counterfeit/fake",
"Sample keywords: " + ", ".join(counterfeit_keywords[:5]),
],
description=f"Multiple reviews indicate potential counterfeit products",
description_zh=f" many itemReviewmention and Counterfeit/Imitation,ExistCounterfeitRisk",
recommended_action="Initiate Test Buy to collect physical evidence",
recommended_action_zh="Proceed Test Buy Test purchase to collect physical evidence",
))
return violations
def detect_trademark_abuse(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionTrademarkAbuse"""
violations = []
# CheckWhether title abuses brand name
title_lower = listing.title.lower()
brand_lower = brand.brand_name.lower()
# SuspiciousMode:Brandname + "compatible", "for", "replacement"
abuse_patterns = [
f"for {brand_lower}",
f"compatible with {brand_lower}",
f"{brand_lower} compatible",
f"fits {brand_lower}",
f"replacement for {brand_lower}",
]
for pattern in abuse_patterns:
if pattern in title_lower:
violations.append(Violation(
violation_type=ViolationType.TRADEMARK,
risk_level=RiskLevel.MEDIUM,
listing=listing,
evidence=[
f"Title contains: '{pattern}'",
f"Full title: {listing.title}",
],
description=f"Potential trademark abuse in listing title",
description_zh=f"Listing Title may contain trademark abuse",
recommended_action="File trademark complaint if unauthorized use",
recommended_action_zh=" such as notAuthorizedUse,SubmitTrademarkInfringementComplaint",
))
break
return violations
def calculate_risk_score(violations: List[Violation]) -> tuple:
"""CalculateRiskRating"""
if not violations:
return 0, RiskLevel.LOW
# Weight
weights = {
RiskLevel.LOW: 5,
RiskLevel.MEDIUM: 15,
RiskLevel.HIGH: 30,
RiskLevel.CRITICAL: 50,
}
total_score = sum(weights[v.risk_level] for v in violations)
score = min(100, total_score)
if score >= 70:
level = RiskLevel.CRITICAL
elif score >= 40:
level = RiskLevel.HIGH
elif score >= 20:
level = RiskLevel.MEDIUM
else:
level = RiskLevel.LOW
return score, level
def generate_action_plan(violations: List[Violation], brand: BrandInfo) -> List[Dict[str, str]]:
"""GenerateRights action plan"""
actions = []
# by CategoryTypeGroup
hijackers = [v for v in violations if v.violation_type == ViolationType.HIJACKER]
counterfeits = [v for v in violations if v.violation_type == ViolationType.COUNTERFEIT]
price_violations = [v for v in violations if v.violation_type == ViolationType.PRICE_VIOLATION]
# HijackingProcess
if hijackers:
if brand.brand_registry:
actions.append({
"priority": "1",
"action": "Report via Brand Registry",
"action_zh": "Pass Brand Registry Complaint",
"detail": f"Report {len(hijackers)} unauthorized seller(s) via Amazon Brand Registry portal",
"detail_zh": f"Pass Amazon Brand Registry PortalComplaint {len(hijackers)} notAuthorizedSeller",
"timeline": "24-48 hours",
})
else:
actions.append({
"priority": "1",
"action": "Send Cease & Desist",
"action_zh": "SendStopInfringementLetter",
"detail": "Contact sellers directly with legal notice",
"detail_zh": "Direct contactSellerSend legal letter",
"timeline": "3-5 business days",
})
# CounterfeitProcess
if counterfeits:
actions.append({
"priority": "1",
"action": "Initiate Test Buy",
"action_zh": "Proceed Test Buy",
"detail": "Purchase product from suspected seller to collect physical evidence",
"detail_zh": " from SuspiciousSeller at PurchaseProductCollectPhysicalEvidence",
"timeline": "7-14 days",
})
actions.append({
"priority": "2",
"action": "File Counterfeit Report",
"action_zh": "SubmitCounterfeitComplaint",
"detail": "Submit counterfeit complaint with evidence to Amazon",
"detail_zh": " to Amazon Submit counterfeit complaint and evidence",
"timeline": "After test buy",
})
# PriceViolationProcess
if price_violations:
actions.append({
"priority": "2",
"action": "Send MAP Violation Notice",
"action_zh": "Send MAP Violation notice",
"detail": f"Notify {len(price_violations)} seller(s) of MAP policy violation",
"detail_zh": f"Notification {len(price_violations)} Seller MAP Policy violation",
"timeline": "48-72 hours",
})
# GeneralRecommendation
if not brand.brand_registry and violations:
actions.append({
"priority": "3",
"action": "Enroll in Brand Registry",
"action_zh": "Register Brand Registry",
"detail": "Get enhanced brand protection tools from Amazon",
"detail_zh": "Get Amazon EnhanceBrand ProtectionTool",
"timeline": "2-4 weeks (requires trademark)",
})
return actions
# ============================================================
# MainDetectionFunction
# ============================================================
def detect(
brand: BrandInfo,
listings: List[ListingInfo],
reviews: Dict[str, List[Dict]] = None
) -> DetectionResult:
"""MainDetectionFunction"""
all_violations = []
for listing in listings:
# Hijacker Detection
all_violations.extend(detect_hijackers(brand, listing))
# PriceViolationDetection
all_violations.extend(detect_price_violations(brand, listing))
# TrademarkAbuseDetection
all_violations.extend(detect_trademark_abuse(brand, listing))
# Counterfeit SignalsDetection
if reviews and listing.asin in reviews:
all_violations.extend(detect_counterfeit_signals(listing, reviews[listing.asin]))
# CalculateRiskRating
risk_score, risk_level = calculate_risk_score(all_violations)
# GenerateAction Plan
action_plan = generate_action_plan(all_violations, brand)
# GenerateSummary
hijacker_count = len([v for v in all_violations if v.violation_type == ViolationType.HIJACKER])
counterfeit_count = len([v for v in all_violations if v.violation_type == ViolationType.COUNTERFEIT])
if risk_level == RiskLevel.CRITICAL:
status = "🚨 CRITICAL"
status_zh = "🚨 CriticalRisk"
elif risk_level == RiskLevel.HIGH:
status = "🔴 HIGH RISK"
status_zh = "🔴 High Risk"
elif risk_level == RiskLevel.MEDIUM:
status = "⚠️ MEDIUM RISK"
status_zh = "⚠️ in etcRisk"
else:
status = "✅ LOW RISK"
status_zh = "✅ Low Risk"
summary = f"{status} | {len(all_violations)} violation(s) found | {hijacker_count} hijacker(s), {counterfeit_count} counterfeit signal(s)"
summary_zh = f"{status_zh} | Found {len(all_violations)} Infringement | {hijacker_count} Hijacking, {counterfeit_count} Counterfeit Signals"
return DetectionResult(
brand=brand,
scan_time=datetime.now().isoformat(),
total_asins_scanned=len(listings),
violations=all_violations,
risk_score=risk_score,
risk_level=risk_level,
summary=summary,
summary_zh=summary_zh,
action_plan=action_plan,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(result: DetectionResult, lang: str = "en") -> str:
"""FormatReport"""
b = result.brand
if lang == "zh":
lines = [
"🛡️ **Brand ProtectionDetectionReport**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ already Register' if b.brand_registry else '❌ notRegister'}",
f"**ScanTime**: {result.scan_time[:19]}",
f"**Scan ASIN **: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 RiskRating: {result.risk_score}/100",
"",
result.summary_zh,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ InfringementDetails",
"",
]
if not result.violations:
lines.append("✅ No infringement found")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description_zh}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Recommendation: {v.recommended_action_zh}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Rights action plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action_zh']}**")
lines.append(f" {action['detail_zh']}")
lines.append(f" ExpectedTime: {action['timeline']}")
lines.append("")
else:
lines = [
"🛡️ **Brand Protection Detection Report**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ Enrolled' if b.brand_registry else '❌ Not Enrolled'}",
f"**Scan Time**: {result.scan_time[:19]}",
f"**ASINs Scanned**: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 Risk Score: {result.risk_score}/100",
"",
result.summary,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Violations Found",
"",
]
if not result.violations:
lines.append("✅ No violations detected")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Action: {v.recommended_action}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Action Plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action']}**")
lines.append(f" {action['detail']}")
lines.append(f" Timeline: {action['timeline']}")
lines.append("")
return "\n".join(lines)
# ============================================================
# DemoData
# ============================================================
def get_demo_data():
"""GetDemoData"""
brand = BrandInfo(
brand_name="TechGadget",
trademark_number="US12345678",
brand_registry=True,
authorized_sellers=["A1B2C3D4E5F6G7"],
protected_asins=["B08XXXXXX1", "B08XXXXXX2"],
min_price=29.99,
)
listings = [
ListingInfo(
asin="B08XXXXXX1",
title="TechGadget Premium Wireless Charger",
brand_in_title=True,
price=29.99,
seller_count=3,
buy_box_seller="A1B2C3D4E5F6G7",
sellers=[
SellerInfo(
seller_id="A1B2C3D4E5F6G7",
seller_name="TechGadget Official",
price=29.99,
is_fba=True,
rating=4.8,
is_authorized=True,
),
SellerInfo(
seller_id="X9Y8Z7W6V5U4T3",
seller_name="CheapDeals123",
price=18.99,
is_fba=False,
rating=3.2,
is_authorized=False,
),
SellerInfo(
seller_id="M1N2O3P4Q5R6S7",
seller_name="BestPriceStore",
price=24.99,
is_fba=True,
rating=4.1,
is_authorized=False,
),
],
),
ListingInfo(
asin="B09YYYYYY1",
title="Compatible with TechGadget Wireless Charger Case",
brand_in_title=True,
price=9.99,
seller_count=1,
sellers=[
SellerInfo(
seller_id="K1L2M3N4O5P6Q7",
seller_name="AccessoryWorld",
price=9.99,
is_fba=True,
rating=4.0,
is_authorized=False,
),
],
),
]
reviews = {
"B08XXXXXX1": [
{"content": "Great product, works perfectly!", "rating": 5},
{"content": "Received a fake product, not genuine TechGadget", "rating": 1},
{"content": "This is counterfeit, poor quality", "rating": 1},
{"content": "Not authentic, different from picture", "rating": 2},
{"content": "Amazing charger, fast shipping", "rating": 5},
],
}
return brand, listings, reviews
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
# DemoMode
brand, listings, reviews = get_demo_data()
# ExecuteDetection
result = detect(brand, listings, reviews)
# OutputReport
print(format_report(result, lang))
if __name__ == "__main__":
main()
FILE:scripts/templates.py
#!/usr/bin/env python3
"""
Brand Protection Templates - Complaint & Legal Templates
Brand ProtectionTemplate - Complaint and legal document templates
Packagecontain:
- Brand Registry Complaint Templates
- Cease & Desist StopInfringementLetter
- Test Buy Operation guide
- MAP Violation notice
- LegalLetterTemplate
Version: 1.0.0
"""
from dataclasses import dataclass
from typing import Optional
from datetime import datetime
@dataclass
class ComplaintInfo:
"""ComplaintInformation"""
brand_name: str
trademark_number: Optional[str] = None
asin: str = ""
seller_name: str = ""
seller_id: str = ""
violation_type: str = ""
evidence: str = ""
contact_email: str = ""
company_name: str = ""
# ============================================================
# Complaint Templates
# ============================================================
def generate_brand_registry_complaint(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY COMPLAINT TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## Report Details
**Brand Name**: {info.brand_name}
**Trademark Number**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**Infringing Seller**: {info.seller_name} ({info.seller_id})
**Violation Type**: {info.violation_type}
---
## Complaint Text (Copy & Paste)
```
I am the brand owner of {info.brand_name} (Trademark #{info.trademark_number or "[YOUR TRADEMARK NUMBER]"}).
The seller "{info.seller_name}" (Seller ID: {info.seller_id}) is selling unauthorized/counterfeit products on ASIN {info.asin}.
Evidence:
{info.evidence or "[Describe your evidence here - screenshots, test buy results, etc.]"}
This seller is NOT an authorized reseller of our products. We request immediate removal of this seller from our listing.
Contact: {info.contact_email or "[YOUR EMAIL]"}
Company: {info.company_name or "[YOUR COMPANY NAME]"}
```
---
## Steps to Submit
1. Log into Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation"
3. Select violation type
4. Enter ASIN and seller information
5. Paste complaint text above
6. Upload evidence (screenshots, invoices, test buy photos)
7. Submit and note case ID
---
## Evidence Checklist
☐ Screenshots of listing showing unauthorized seller
☐ Invoice/order confirmation from test buy
☐ Photos comparing authentic vs suspected counterfeit
☐ Trademark registration certificate
☐ Authorization letter (showing seller is NOT authorized)
"""
def generate_cease_desist(info: ComplaintInfo) -> str:
"""GenerateStopInfringementLetterTemplate"""
today = datetime.now().strftime("%B %d, %Y")
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 CEASE AND DESIST LETTER TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**CEASE AND DESIST NOTICE**
To: {info.seller_name}
Seller ID: {info.seller_id}
Re: Unauthorized Sale of {info.brand_name} Products
---
Dear {info.seller_name},
This letter serves as formal notice that you are engaging in unauthorized sale of products bearing the {info.brand_name}® trademark (Registration No. {info.trademark_number or "[TRADEMARK NUMBER]"}) on Amazon.com, specifically on ASIN: {info.asin}.
**YOU ARE NOT AN AUTHORIZED RESELLER** of {info.brand_name} products. Your unauthorized sale of these products constitutes:
1. Trademark infringement under 15 U.S.C. § 1114
2. False designation of origin under 15 U.S.C. § 1125(a)
3. Violation of Amazon's Anti-Counterfeiting Policy
**DEMAND**
We hereby demand that you:
1. Immediately cease and desist all sales of {info.brand_name} products
2. Remove all {info.brand_name} product listings from your seller account
3. Provide a written confirmation of compliance within 5 business days
**CONSEQUENCES OF NON-COMPLIANCE**
Failure to comply with this demand will result in:
- Report to Amazon Brand Registry for listing removal
- Legal action seeking injunctive relief and monetary damages
- Report to law enforcement if counterfeit goods are involved
This letter is not intended to be a complete statement of the facts or law applicable to this matter, and nothing herein should be construed as a waiver of any rights or remedies.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
---
## Sending Instructions
1. Send via Amazon Buyer-Seller Messaging (if available)
2. Send via seller's contact email (find in storefront)
3. Keep copies of all correspondence
4. Set 5-day deadline for response
5. Escalate to legal action if no response
"""
def generate_test_buy_guide() -> str:
"""Generate Test Buy Operation guide"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY PROCEDURE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Purpose
Test Buy is the process of purchasing products from suspected counterfeit/unauthorized sellers to collect physical evidence for your complaint.
---
## Step-by-Step Process
### 1. Preparation
☐ Create a separate Amazon buyer account (not linked to seller account)
☐ Use a different shipping address if possible
☐ Prepare camera for documentation
☐ Have authentic product ready for comparison
### 2. Purchase
☐ Select the suspected seller's offer (not Buy Box)
☐ Screenshot the product page showing seller name and price
☐ Screenshot checkout page with seller info
☐ Complete purchase and save order confirmation
☐ Note Order ID: ________________
### 3. Documentation Upon Arrival
☐ Photograph unopened package (showing shipping label)
☐ Video record unboxing process
☐ Photograph product from multiple angles
☐ Compare with authentic product side-by-side:
- Packaging differences
- Label/printing quality
- Product quality/finish
- Weight comparison
- Serial number verification
☐ Keep all packaging materials
### 4. Evidence Organization
Create folder with:
```
test_buy_evidence/
├── 01_listing_screenshots/
├── 02_order_confirmation/
├── 03_package_photos/
├── 04_unboxing_video/
├── 05_product_comparison/
└── 06_notes.txt
```
### 5. Submit Complaint
☐ Compile all evidence
☐ Write detailed complaint (use template)
☐ Submit via Brand Registry
☐ Include Order ID in complaint
☐ Upload photos/video
---
## Evidence Checklist
**Screenshots**
☐ Listing page with seller
☐ Seller storefront
☐ Order confirmation
☐ Shipping confirmation
☐ Delivery confirmation
**Photos**
☐ Package exterior (4+ angles)
☐ Shipping label close-up
☐ Product in packaging
☐ Product removed
☐ Side-by-side with authentic
☐ Close-up of differences
**Documents**
☐ Invoice from test buy
☐ Authentication certificate (if available)
☐ Trademark registration
---
## Timeline
Day 1: Place order
Day 3-7: Receive package
Day 7-8: Document and compare
Day 8-10: Compile and submit complaint
Day 10-21: Amazon review period
---
## Cost Tracking
| Item | Cost |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| Return Shipping | $_____ |
| Total | $_____ |
*Note: May be recoverable in legal action*
"""
def generate_map_violation_notice(info: ComplaintInfo, violation_price: float, map_price: float) -> str:
"""Generate MAP Violation notice"""
today = datetime.now().strftime("%B %d, %Y")
discount = (map_price - violation_price) / map_price * 100
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 MAP VIOLATION NOTICE TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**MINIMUM ADVERTISED PRICE (MAP) VIOLATION NOTICE**
To: {info.seller_name}
Re: MAP Policy Violation - {info.brand_name}
---
Dear {info.seller_name},
This notice is to inform you that your current advertised price for {info.brand_name} products violates our Minimum Advertised Price (MAP) policy.
**Violation Details:**
| Product | ASIN | Your Price | MAP Price | Violation |
|---------|------|------------|-----------|-----------|
| {info.brand_name} | {info.asin} | .2f | .2f | -{discount:.1f}% |
**MAP Policy Terms:**
As an authorized/unauthorized reseller of {info.brand_name} products, you are required to maintain advertised prices at or above the Minimum Advertised Price. This policy ensures:
- Fair competition among resellers
- Brand value protection
- Quality customer experience
**Required Action:**
Please adjust your advertised price to .2f or higher within **48 hours** of receiving this notice.
**Consequences of Non-Compliance:**
Continued violation of our MAP policy may result in:
- Removal from authorized reseller program
- Report to Amazon for policy violation
- Supply chain restrictions
Please confirm compliance by replying to this notice.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
"""
# ============================================================
# in textTemplate
# ============================================================
def generate_brand_registry_complaint_zh(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates ( in text)"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY Complaint Templates
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## ComplaintInformation
**BrandName**: {info.brand_name}
**TrademarkRegisternumber**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**InfringementSeller**: {info.seller_name} ({info.seller_id})
**InfringementCategoryType**: {info.violation_type}
---
## ComplaintText (CopyPaste)
```
I is {info.brand_name} BrandOwner (TrademarkRegisternumber: {info.trademark_number or "[youTrademarknumber]"})。
Seller "{info.seller_name}" (Seller ID: {info.seller_id}) positive in ASIN {info.asin} Selling unauthorized on/CounterfeitProduct。
Evidence:
{info.evidence or "[Describe your evidence here - Screenshot、TestPurchaseResult etc]"}
should Sellernot is WeProductAuthorized distributor of。WeRequestImmediately will this Seller from We Listing in Remove。
Contact info: {info.contact_email or "[Your email]"}
CompanyName: {info.company_name or "[youCompanyname]"}
```
---
## SubmitStep
1. Login Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation" (ReportInfringement)
3. ChoiceInfringementCategoryType
4. Input ASIN AndSellerInformation
5. PasteAboveComplaintText
6. UploadEvidence (Screenshot、Invoice、Test Buy Photo)
7. SubmitandRecord Case ID
---
## EvidenceList
☐ Show notAuthorizedSeller Listing Screenshot
☐ Test Buy Invoice/OrderConfirm
☐ Authentic vs suspected counterfeitComparisonPhoto
☐ Trademark registration certificate
☐ Authorizedbook (Proof should SellerNot obtainedAuthorized)
"""
def generate_test_buy_guide_zh() -> str:
"""Generate Test Buy Operation guide ( in text)"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY Operation guide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## item
Test Buy (TestPurchase) Is fromSuspiciousCounterfeit/notAuthorizedSeller at PurchaseProduct,Process of collecting physical evidence for complaint。
---
## Operation process
### 1. Preparation work
☐ CreateIndependent Amazon BuyerAccount (not need and SellerAccountAssociate)
☐ Use different deliveryAddress
☐ Prepare camera for recording
☐ Prepare authentic product forComparison
### 2. Purchase
☐ ChoiceSuspiciousSellerQuote (not need select Buy Box)
☐ ScreenshotProductPage,DisplaySellerNameAndPrice
☐ ScreenshotSettlementPage,PackagecontainSellerInformation
☐ CompletePurchaseandSaveOrderConfirm
☐ RecordOrdernumber: ________________
### 3. Receive after Record
☐ Photo of unopened package (Show shipping label)
☐ Video record unboxing process
☐ many angleDegreePhotoProduct
☐ and AuthenticSide by sideComparison:
- PackagingDifference
- Tag/Print quality
- ProductQuality/Workmanship
- heavy quantityComparison
- Serial number verification
☐ Keep all packaging materials
### 4. EvidenceOrganize
CreateFolder:
```
test_buy_Evidence/
├── 01_listingScreenshot/
├── 02_OrderConfirm/
├── 03_Package photo/
├── 04_UnboxingVideo/
├── 05_ProductComparison/
└── 06_Notes.txt
```
### 5. SubmitComplaint
☐ Organize all evidence
☐ Write detailed complaint (UseTemplate)
☐ Pass Brand Registry Submit
☐ Include in complaintOrdernumber
☐ Upload photo/Video
---
## Timeline
number 1 days: below single
number 3-7 days: Receive
number 7-8 days: RecordandComparison
number 8-10 days: Organize and submit complaint
number 10-21 days: Amazon ReviewPeriod
---
## CostTrack
| Itemitem | Fee |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| ReturnShipping | $_____ |
| Total | $_____ |
*note: Can be recovered in legal proceedings*
"""
# ============================================================
# CLI
# ============================================================
def main():
import sys
# DemoData
info = ComplaintInfo(
brand_name="TechGadget",
trademark_number="US12345678",
asin="B08XXXXXX1",
seller_name="CheapDeals123",
seller_id="X9Y8Z7W6V5U4T3",
violation_type="Unauthorized Sale / Suspected Counterfeit",
evidence="Test buy received product with different packaging and lower quality than authentic product.",
contact_email="[email protected]",
company_name="TechGadget Inc.",
)
lang = "zh" if "--zh" in sys.argv else "en"
template_type = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "all"
if template_type == "complaint" or template_type == "all":
if lang == "zh":
print(generate_brand_registry_complaint_zh(info))
else:
print(generate_brand_registry_complaint(info))
if template_type == "cease" or template_type == "all":
print(generate_cease_desist(info))
if template_type == "testbuy" or template_type == "all":
if lang == "zh":
print(generate_test_buy_guide_zh())
else:
print(generate_test_buy_guide())
if template_type == "map" or template_type == "all":
print(generate_map_violation_notice(info, 18.99, 29.99))
if __name__ == "__main__":
main()
Shopify/DTC brand protection toolkit. Detect counterfeit stores, unauthorized resellers, and trademark violations. Includes DMCA takedown templates, domain m...
---
name: brand-protection-shopify
version: 1.0.0
author: Nexscope AI
description: "Shopify/DTC brand protection toolkit. Detect counterfeit stores, unauthorized resellers, and trademark violations. Includes DMCA takedown templates, domain monitoring, and social media infringement detection. No API key required."
metadata: {"nexscope":{"emoji":"🛡️","category":"ecommerce"}}
---
# Brand Protection — Shopify/DTC 🛡️
Protect your brand from counterfeit stores and unauthorized resellers in the DTC space.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-protection-shopify -g
```
## Features
- **Counterfeit Store Detection** — Find fake stores copying your brand
- **Domain Monitoring** — Track similar/typosquatting domains
- **Social Media Infringement** — Detect unauthorized ads/posts
- **Trademark Abuse** — Logo and brand name misuse
- **DMCA Takedown Templates** — Copyright infringement removal
- **Cease & Desist Letters** — Legal notice templates
## DTC-Specific Detection
| Dimension | Method | Risk Level |
|-----------|--------|------------|
| Fake Stores | Domain + content matching | 🔴 High |
| Unauthorized Resellers | Price/image tracking | 🔴 High |
| Social Ads | Ad library monitoring | ⚠️ Medium |
| Trademark | Logo/name detection | 🔴 High |
## Risk Levels
| Level | Description | Action |
|-------|-------------|--------|
| 🔴 High | Active infringement | DMCA within 24h |
| ⚠️ Medium | Potential concern | Investigate further |
| ✅ Low | Normal activity | Continue monitoring |
## Input Configuration
```json
{
"brand_name": "YourBrand",
"official_domain": "yourbrand.com",
"trademark_number": "US12345678",
"logo_url": "https://yourbrand.com/logo.png",
"social_handles": {
"instagram": "@yourbrand",
"facebook": "yourbrand",
"tiktok": "@yourbrand"
}
}
```
## Usage
### Detection
```bash
python3 scripts/detector.py
```
### Generate Takedown Templates
```bash
# DMCA takedown
python3 scripts/templates.py dmca
# Cease & Desist letter
python3 scripts/templates.py cease-desist
# Platform report (Shopify)
python3 scripts/templates.py platform-report
```
## Output Example
```
🛡️ Shopify/DTC Brand Protection Report
Brand: YourBrand
Official Domain: yourbrand.com
Analysis Date: 2024-01-15
━━━━━━━━━━━━━━━━━━━━━━━━
🔴 HIGH RISK ALERTS
Fake Store Detected:
├── Domain: your-brand-sale.com
├── Copying: Product images, descriptions
└── Action: File DMCA + domain complaint
━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ SOCIAL MEDIA INFRINGEMENT
Instagram: 2 unauthorized ads detected
Facebook: 1 fake page found
Recommendation: Report to platforms
```
## Takedown Templates Included
| Template | Use Case |
|----------|----------|
| DMCA Takedown | Hosting provider removal |
| Cease & Desist | Direct legal notice |
| Platform Report | Shopify abuse report |
| Social Report | Instagram/Facebook/TikTok |
| Domain Complaint | Registrar abuse report |
## Action Workflow
```
Monitor Web/Social
↓
Detect Infringement
↓
Document Evidence
↓
Send DMCA/C&D
↓
Report to Platforms
↓
Track Resolution
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/detector.py
#!/usr/bin/env python3
"""
Brand Protection Detector - Core Engine
Brand ProtectionDetector - Core Engine
Features:
- Hijacker Detection (Hijacker Detection)
- PriceAbnormalMonitoring (Price Alert)
- CounterfeitIdentify (Counterfeit Detection)
- ImageStolenDetection (Image Theft)
- RiskEvaluate (Risk Assessment)
- Rights protectionRecommendation (Action Recommendations)
Version: 1.0.0
"""
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum
from datetime import datetime
import sys
import re
class RiskLevel(Enum):
"""RiskGrade"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class ViolationType(Enum):
"""InfringementCategoryType"""
HIJACKER = "hijacker" # Hijacking
COUNTERFEIT = "counterfeit" # Counterfeit
PRICE_VIOLATION = "price" # PriceViolation
IMAGE_THEFT = "image_theft" # ImageStolen
TRADEMARK = "trademark" # TrademarkInfringement
LISTING_ABUSE = "listing_abuse" # Listing Abuse
# ============================================================
# Data Structures
# ============================================================
@dataclass
class BrandInfo:
"""BrandInformation"""
brand_name: str
trademark_number: Optional[str] = None
brand_registry: bool = False
authorized_sellers: List[str] = field(default_factory=list)
protected_asins: List[str] = field(default_factory=list)
min_price: Optional[float] = None # MAP most low price
logo_url: Optional[str] = None
@dataclass
class SellerInfo:
"""SellerInformation"""
seller_id: str
seller_name: str
price: float
is_fba: bool = False
rating: Optional[float] = None
review_count: Optional[int] = None
is_authorized: bool = False
storefront_url: Optional[str] = None
@dataclass
class ListingInfo:
"""Listing Information"""
asin: str
title: str
brand_in_title: bool = False
price: float = 0.0
image_urls: List[str] = field(default_factory=list)
seller_count: int = 1
sellers: List[SellerInfo] = field(default_factory=list)
buy_box_seller: Optional[str] = None
category: Optional[str] = None
@dataclass
class Violation:
"""InfringementRecord"""
violation_type: ViolationType
risk_level: RiskLevel
seller: Optional[SellerInfo] = None
listing: Optional[ListingInfo] = None
evidence: List[str] = field(default_factory=list)
description: str = ""
description_zh: str = ""
recommended_action: str = ""
recommended_action_zh: str = ""
@dataclass
class DetectionResult:
"""DetectionResult"""
brand: BrandInfo
scan_time: str
total_asins_scanned: int
violations: List[Violation]
risk_score: int # 0-100
risk_level: RiskLevel
summary: str
summary_zh: str
action_plan: List[Dict[str, str]]
# ============================================================
# DetectionLogic
# ============================================================
def detect_hijackers(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionHijacking"""
violations = []
for seller in listing.sellers:
# skip AuthorizedSeller
if seller.seller_id in brand.authorized_sellers:
continue
if seller.is_authorized:
continue
# FoundnotAuthorizedSeller
risk = RiskLevel.HIGH if listing.buy_box_seller == seller.seller_id else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.HIJACKER,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Unauthorized seller on ASIN: {listing.asin}",
f"Seller: {seller.seller_name} ({seller.seller_id})",
f"Price: seller.price",
],
description=f"Unauthorized seller '{seller.seller_name}' found on your listing",
description_zh=f"FoundnotAuthorizedSeller '{seller.seller_name}' in you Listing above Sale",
recommended_action="File Brand Registry complaint or send cease & desist",
recommended_action_zh="Pass Brand Registry Complaint or cease and desist letter",
))
return violations
def detect_price_violations(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionPriceViolation"""
violations = []
if brand.min_price is None:
return violations
for seller in listing.sellers:
if seller.price < brand.min_price:
discount = (brand.min_price - seller.price) / brand.min_price * 100
risk = RiskLevel.CRITICAL if discount > 30 else RiskLevel.HIGH if discount > 15 else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.PRICE_VIOLATION,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Price seller.price below MAP brand.min_price",
f"Discount: {discount:.1f}% below minimum",
],
description=f"Seller '{seller.seller_name}' selling {discount:.1f}% below MAP",
description_zh=f"Seller '{seller.seller_name}' Selling Price low at MAP {discount:.1f}%",
recommended_action="Send MAP violation notice, consider distribution review",
recommended_action_zh="Send MAP Violation notice,ConsiderReviewDistributionChannel",
))
return violations
def detect_counterfeit_signals(listing: ListingInfo, reviews: List[Dict] = None) -> List[Violation]:
"""DetectionCounterfeit Signals"""
violations = []
# SuspiciousKeywords
counterfeit_keywords = [
"fake", "counterfeit", "not genuine", "knockoff", "replica",
"poor quality", "not authentic", "cheap copy", "different from picture",
"Counterfeit", "fake", "Imitation", "Knockoff", "Poor quality", "AndImageDifferent",
]
if reviews:
suspicious_reviews = []
for review in reviews:
content = review.get("content", "").lower()
for keyword in counterfeit_keywords:
if keyword.lower() in content:
suspicious_reviews.append(review)
break
if len(suspicious_reviews) >= 3:
violations.append(Violation(
violation_type=ViolationType.COUNTERFEIT,
risk_level=RiskLevel.CRITICAL,
listing=listing,
evidence=[
f"Found {len(suspicious_reviews)} reviews mentioning counterfeit/fake",
"Sample keywords: " + ", ".join(counterfeit_keywords[:5]),
],
description=f"Multiple reviews indicate potential counterfeit products",
description_zh=f" many itemReviewmention and Counterfeit/Imitation,ExistCounterfeitRisk",
recommended_action="Initiate Test Buy to collect physical evidence",
recommended_action_zh="Proceed Test Buy Test purchase to collect physical evidence",
))
return violations
def detect_trademark_abuse(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionTrademarkAbuse"""
violations = []
# CheckWhether title abuses brand name
title_lower = listing.title.lower()
brand_lower = brand.brand_name.lower()
# SuspiciousMode:Brandname + "compatible", "for", "replacement"
abuse_patterns = [
f"for {brand_lower}",
f"compatible with {brand_lower}",
f"{brand_lower} compatible",
f"fits {brand_lower}",
f"replacement for {brand_lower}",
]
for pattern in abuse_patterns:
if pattern in title_lower:
violations.append(Violation(
violation_type=ViolationType.TRADEMARK,
risk_level=RiskLevel.MEDIUM,
listing=listing,
evidence=[
f"Title contains: '{pattern}'",
f"Full title: {listing.title}",
],
description=f"Potential trademark abuse in listing title",
description_zh=f"Listing Title may contain trademark abuse",
recommended_action="File trademark complaint if unauthorized use",
recommended_action_zh=" such as notAuthorizedUse,SubmitTrademarkInfringementComplaint",
))
break
return violations
def calculate_risk_score(violations: List[Violation]) -> tuple:
"""CalculateRiskRating"""
if not violations:
return 0, RiskLevel.LOW
# Weight
weights = {
RiskLevel.LOW: 5,
RiskLevel.MEDIUM: 15,
RiskLevel.HIGH: 30,
RiskLevel.CRITICAL: 50,
}
total_score = sum(weights[v.risk_level] for v in violations)
score = min(100, total_score)
if score >= 70:
level = RiskLevel.CRITICAL
elif score >= 40:
level = RiskLevel.HIGH
elif score >= 20:
level = RiskLevel.MEDIUM
else:
level = RiskLevel.LOW
return score, level
def generate_action_plan(violations: List[Violation], brand: BrandInfo) -> List[Dict[str, str]]:
"""GenerateRights action plan"""
actions = []
# by CategoryTypeGroup
hijackers = [v for v in violations if v.violation_type == ViolationType.HIJACKER]
counterfeits = [v for v in violations if v.violation_type == ViolationType.COUNTERFEIT]
price_violations = [v for v in violations if v.violation_type == ViolationType.PRICE_VIOLATION]
# HijackingProcess
if hijackers:
if brand.brand_registry:
actions.append({
"priority": "1",
"action": "Report via Brand Registry",
"action_zh": "Pass Brand Registry Complaint",
"detail": f"Report {len(hijackers)} unauthorized seller(s) via Amazon Brand Registry portal",
"detail_zh": f"Pass Amazon Brand Registry PortalComplaint {len(hijackers)} notAuthorizedSeller",
"timeline": "24-48 hours",
})
else:
actions.append({
"priority": "1",
"action": "Send Cease & Desist",
"action_zh": "SendStopInfringementLetter",
"detail": "Contact sellers directly with legal notice",
"detail_zh": "Direct contactSellerSend legal letter",
"timeline": "3-5 business days",
})
# CounterfeitProcess
if counterfeits:
actions.append({
"priority": "1",
"action": "Initiate Test Buy",
"action_zh": "Proceed Test Buy",
"detail": "Purchase product from suspected seller to collect physical evidence",
"detail_zh": " from SuspiciousSeller at PurchaseProductCollectPhysicalEvidence",
"timeline": "7-14 days",
})
actions.append({
"priority": "2",
"action": "File Counterfeit Report",
"action_zh": "SubmitCounterfeitComplaint",
"detail": "Submit counterfeit complaint with evidence to Amazon",
"detail_zh": " to Amazon Submit counterfeit complaint and evidence",
"timeline": "After test buy",
})
# PriceViolationProcess
if price_violations:
actions.append({
"priority": "2",
"action": "Send MAP Violation Notice",
"action_zh": "Send MAP Violation notice",
"detail": f"Notify {len(price_violations)} seller(s) of MAP policy violation",
"detail_zh": f"Notification {len(price_violations)} Seller MAP Policy violation",
"timeline": "48-72 hours",
})
# GeneralRecommendation
if not brand.brand_registry and violations:
actions.append({
"priority": "3",
"action": "Enroll in Brand Registry",
"action_zh": "Register Brand Registry",
"detail": "Get enhanced brand protection tools from Amazon",
"detail_zh": "Get Amazon EnhanceBrand ProtectionTool",
"timeline": "2-4 weeks (requires trademark)",
})
return actions
# ============================================================
# MainDetectionFunction
# ============================================================
def detect(
brand: BrandInfo,
listings: List[ListingInfo],
reviews: Dict[str, List[Dict]] = None
) -> DetectionResult:
"""MainDetectionFunction"""
all_violations = []
for listing in listings:
# Hijacker Detection
all_violations.extend(detect_hijackers(brand, listing))
# PriceViolationDetection
all_violations.extend(detect_price_violations(brand, listing))
# TrademarkAbuseDetection
all_violations.extend(detect_trademark_abuse(brand, listing))
# Counterfeit SignalsDetection
if reviews and listing.asin in reviews:
all_violations.extend(detect_counterfeit_signals(listing, reviews[listing.asin]))
# CalculateRiskRating
risk_score, risk_level = calculate_risk_score(all_violations)
# GenerateAction Plan
action_plan = generate_action_plan(all_violations, brand)
# GenerateSummary
hijacker_count = len([v for v in all_violations if v.violation_type == ViolationType.HIJACKER])
counterfeit_count = len([v for v in all_violations if v.violation_type == ViolationType.COUNTERFEIT])
if risk_level == RiskLevel.CRITICAL:
status = "🚨 CRITICAL"
status_zh = "🚨 CriticalRisk"
elif risk_level == RiskLevel.HIGH:
status = "🔴 HIGH RISK"
status_zh = "🔴 High Risk"
elif risk_level == RiskLevel.MEDIUM:
status = "⚠️ MEDIUM RISK"
status_zh = "⚠️ in etcRisk"
else:
status = "✅ LOW RISK"
status_zh = "✅ Low Risk"
summary = f"{status} | {len(all_violations)} violation(s) found | {hijacker_count} hijacker(s), {counterfeit_count} counterfeit signal(s)"
summary_zh = f"{status_zh} | Found {len(all_violations)} Infringement | {hijacker_count} Hijacking, {counterfeit_count} Counterfeit Signals"
return DetectionResult(
brand=brand,
scan_time=datetime.now().isoformat(),
total_asins_scanned=len(listings),
violations=all_violations,
risk_score=risk_score,
risk_level=risk_level,
summary=summary,
summary_zh=summary_zh,
action_plan=action_plan,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(result: DetectionResult, lang: str = "en") -> str:
"""FormatReport"""
b = result.brand
if lang == "zh":
lines = [
"🛡️ **Brand ProtectionDetectionReport**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ already Register' if b.brand_registry else '❌ notRegister'}",
f"**ScanTime**: {result.scan_time[:19]}",
f"**Scan ASIN **: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 RiskRating: {result.risk_score}/100",
"",
result.summary_zh,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ InfringementDetails",
"",
]
if not result.violations:
lines.append("✅ No infringement found")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description_zh}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Recommendation: {v.recommended_action_zh}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Rights action plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action_zh']}**")
lines.append(f" {action['detail_zh']}")
lines.append(f" ExpectedTime: {action['timeline']}")
lines.append("")
else:
lines = [
"🛡️ **Brand Protection Detection Report**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ Enrolled' if b.brand_registry else '❌ Not Enrolled'}",
f"**Scan Time**: {result.scan_time[:19]}",
f"**ASINs Scanned**: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 Risk Score: {result.risk_score}/100",
"",
result.summary,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Violations Found",
"",
]
if not result.violations:
lines.append("✅ No violations detected")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Action: {v.recommended_action}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Action Plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action']}**")
lines.append(f" {action['detail']}")
lines.append(f" Timeline: {action['timeline']}")
lines.append("")
return "\n".join(lines)
# ============================================================
# DemoData
# ============================================================
def get_demo_data():
"""GetDemoData"""
brand = BrandInfo(
brand_name="TechGadget",
trademark_number="US12345678",
brand_registry=True,
authorized_sellers=["A1B2C3D4E5F6G7"],
protected_asins=["B08XXXXXX1", "B08XXXXXX2"],
min_price=29.99,
)
listings = [
ListingInfo(
asin="B08XXXXXX1",
title="TechGadget Premium Wireless Charger",
brand_in_title=True,
price=29.99,
seller_count=3,
buy_box_seller="A1B2C3D4E5F6G7",
sellers=[
SellerInfo(
seller_id="A1B2C3D4E5F6G7",
seller_name="TechGadget Official",
price=29.99,
is_fba=True,
rating=4.8,
is_authorized=True,
),
SellerInfo(
seller_id="X9Y8Z7W6V5U4T3",
seller_name="CheapDeals123",
price=18.99,
is_fba=False,
rating=3.2,
is_authorized=False,
),
SellerInfo(
seller_id="M1N2O3P4Q5R6S7",
seller_name="BestPriceStore",
price=24.99,
is_fba=True,
rating=4.1,
is_authorized=False,
),
],
),
ListingInfo(
asin="B09YYYYYY1",
title="Compatible with TechGadget Wireless Charger Case",
brand_in_title=True,
price=9.99,
seller_count=1,
sellers=[
SellerInfo(
seller_id="K1L2M3N4O5P6Q7",
seller_name="AccessoryWorld",
price=9.99,
is_fba=True,
rating=4.0,
is_authorized=False,
),
],
),
]
reviews = {
"B08XXXXXX1": [
{"content": "Great product, works perfectly!", "rating": 5},
{"content": "Received a fake product, not genuine TechGadget", "rating": 1},
{"content": "This is counterfeit, poor quality", "rating": 1},
{"content": "Not authentic, different from picture", "rating": 2},
{"content": "Amazing charger, fast shipping", "rating": 5},
],
}
return brand, listings, reviews
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
# DemoMode
brand, listings, reviews = get_demo_data()
# ExecuteDetection
result = detect(brand, listings, reviews)
# OutputReport
print(format_report(result, lang))
if __name__ == "__main__":
main()
FILE:scripts/templates.py
#!/usr/bin/env python3
"""
Brand Protection Templates - Complaint & Legal Templates
Brand ProtectionTemplate - Complaint and legal document templates
Packagecontain:
- Brand Registry Complaint Templates
- Cease & Desist StopInfringementLetter
- Test Buy Operation guide
- MAP Violation notice
- LegalLetterTemplate
Version: 1.0.0
"""
from dataclasses import dataclass
from typing import Optional
from datetime import datetime
@dataclass
class ComplaintInfo:
"""ComplaintInformation"""
brand_name: str
trademark_number: Optional[str] = None
asin: str = ""
seller_name: str = ""
seller_id: str = ""
violation_type: str = ""
evidence: str = ""
contact_email: str = ""
company_name: str = ""
# ============================================================
# Complaint Templates
# ============================================================
def generate_brand_registry_complaint(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY COMPLAINT TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## Report Details
**Brand Name**: {info.brand_name}
**Trademark Number**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**Infringing Seller**: {info.seller_name} ({info.seller_id})
**Violation Type**: {info.violation_type}
---
## Complaint Text (Copy & Paste)
```
I am the brand owner of {info.brand_name} (Trademark #{info.trademark_number or "[YOUR TRADEMARK NUMBER]"}).
The seller "{info.seller_name}" (Seller ID: {info.seller_id}) is selling unauthorized/counterfeit products on ASIN {info.asin}.
Evidence:
{info.evidence or "[Describe your evidence here - screenshots, test buy results, etc.]"}
This seller is NOT an authorized reseller of our products. We request immediate removal of this seller from our listing.
Contact: {info.contact_email or "[YOUR EMAIL]"}
Company: {info.company_name or "[YOUR COMPANY NAME]"}
```
---
## Steps to Submit
1. Log into Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation"
3. Select violation type
4. Enter ASIN and seller information
5. Paste complaint text above
6. Upload evidence (screenshots, invoices, test buy photos)
7. Submit and note case ID
---
## Evidence Checklist
☐ Screenshots of listing showing unauthorized seller
☐ Invoice/order confirmation from test buy
☐ Photos comparing authentic vs suspected counterfeit
☐ Trademark registration certificate
☐ Authorization letter (showing seller is NOT authorized)
"""
def generate_cease_desist(info: ComplaintInfo) -> str:
"""GenerateStopInfringementLetterTemplate"""
today = datetime.now().strftime("%B %d, %Y")
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 CEASE AND DESIST LETTER TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**CEASE AND DESIST NOTICE**
To: {info.seller_name}
Seller ID: {info.seller_id}
Re: Unauthorized Sale of {info.brand_name} Products
---
Dear {info.seller_name},
This letter serves as formal notice that you are engaging in unauthorized sale of products bearing the {info.brand_name}® trademark (Registration No. {info.trademark_number or "[TRADEMARK NUMBER]"}) on Amazon.com, specifically on ASIN: {info.asin}.
**YOU ARE NOT AN AUTHORIZED RESELLER** of {info.brand_name} products. Your unauthorized sale of these products constitutes:
1. Trademark infringement under 15 U.S.C. § 1114
2. False designation of origin under 15 U.S.C. § 1125(a)
3. Violation of Amazon's Anti-Counterfeiting Policy
**DEMAND**
We hereby demand that you:
1. Immediately cease and desist all sales of {info.brand_name} products
2. Remove all {info.brand_name} product listings from your seller account
3. Provide a written confirmation of compliance within 5 business days
**CONSEQUENCES OF NON-COMPLIANCE**
Failure to comply with this demand will result in:
- Report to Amazon Brand Registry for listing removal
- Legal action seeking injunctive relief and monetary damages
- Report to law enforcement if counterfeit goods are involved
This letter is not intended to be a complete statement of the facts or law applicable to this matter, and nothing herein should be construed as a waiver of any rights or remedies.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
---
## Sending Instructions
1. Send via Amazon Buyer-Seller Messaging (if available)
2. Send via seller's contact email (find in storefront)
3. Keep copies of all correspondence
4. Set 5-day deadline for response
5. Escalate to legal action if no response
"""
def generate_test_buy_guide() -> str:
"""Generate Test Buy Operation guide"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY PROCEDURE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Purpose
Test Buy is the process of purchasing products from suspected counterfeit/unauthorized sellers to collect physical evidence for your complaint.
---
## Step-by-Step Process
### 1. Preparation
☐ Create a separate Amazon buyer account (not linked to seller account)
☐ Use a different shipping address if possible
☐ Prepare camera for documentation
☐ Have authentic product ready for comparison
### 2. Purchase
☐ Select the suspected seller's offer (not Buy Box)
☐ Screenshot the product page showing seller name and price
☐ Screenshot checkout page with seller info
☐ Complete purchase and save order confirmation
☐ Note Order ID: ________________
### 3. Documentation Upon Arrival
☐ Photograph unopened package (showing shipping label)
☐ Video record unboxing process
☐ Photograph product from multiple angles
☐ Compare with authentic product side-by-side:
- Packaging differences
- Label/printing quality
- Product quality/finish
- Weight comparison
- Serial number verification
☐ Keep all packaging materials
### 4. Evidence Organization
Create folder with:
```
test_buy_evidence/
├── 01_listing_screenshots/
├── 02_order_confirmation/
├── 03_package_photos/
├── 04_unboxing_video/
├── 05_product_comparison/
└── 06_notes.txt
```
### 5. Submit Complaint
☐ Compile all evidence
☐ Write detailed complaint (use template)
☐ Submit via Brand Registry
☐ Include Order ID in complaint
☐ Upload photos/video
---
## Evidence Checklist
**Screenshots**
☐ Listing page with seller
☐ Seller storefront
☐ Order confirmation
☐ Shipping confirmation
☐ Delivery confirmation
**Photos**
☐ Package exterior (4+ angles)
☐ Shipping label close-up
☐ Product in packaging
☐ Product removed
☐ Side-by-side with authentic
☐ Close-up of differences
**Documents**
☐ Invoice from test buy
☐ Authentication certificate (if available)
☐ Trademark registration
---
## Timeline
Day 1: Place order
Day 3-7: Receive package
Day 7-8: Document and compare
Day 8-10: Compile and submit complaint
Day 10-21: Amazon review period
---
## Cost Tracking
| Item | Cost |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| Return Shipping | $_____ |
| Total | $_____ |
*Note: May be recoverable in legal action*
"""
def generate_map_violation_notice(info: ComplaintInfo, violation_price: float, map_price: float) -> str:
"""Generate MAP Violation notice"""
today = datetime.now().strftime("%B %d, %Y")
discount = (map_price - violation_price) / map_price * 100
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 MAP VIOLATION NOTICE TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**MINIMUM ADVERTISED PRICE (MAP) VIOLATION NOTICE**
To: {info.seller_name}
Re: MAP Policy Violation - {info.brand_name}
---
Dear {info.seller_name},
This notice is to inform you that your current advertised price for {info.brand_name} products violates our Minimum Advertised Price (MAP) policy.
**Violation Details:**
| Product | ASIN | Your Price | MAP Price | Violation |
|---------|------|------------|-----------|-----------|
| {info.brand_name} | {info.asin} | .2f | .2f | -{discount:.1f}% |
**MAP Policy Terms:**
As an authorized/unauthorized reseller of {info.brand_name} products, you are required to maintain advertised prices at or above the Minimum Advertised Price. This policy ensures:
- Fair competition among resellers
- Brand value protection
- Quality customer experience
**Required Action:**
Please adjust your advertised price to .2f or higher within **48 hours** of receiving this notice.
**Consequences of Non-Compliance:**
Continued violation of our MAP policy may result in:
- Removal from authorized reseller program
- Report to Amazon for policy violation
- Supply chain restrictions
Please confirm compliance by replying to this notice.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
"""
# ============================================================
# in textTemplate
# ============================================================
def generate_brand_registry_complaint_zh(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates ( in text)"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY Complaint Templates
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## ComplaintInformation
**BrandName**: {info.brand_name}
**TrademarkRegisternumber**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**InfringementSeller**: {info.seller_name} ({info.seller_id})
**InfringementCategoryType**: {info.violation_type}
---
## ComplaintText (CopyPaste)
```
I is {info.brand_name} BrandOwner (TrademarkRegisternumber: {info.trademark_number or "[youTrademarknumber]"})。
Seller "{info.seller_name}" (Seller ID: {info.seller_id}) positive in ASIN {info.asin} Selling unauthorized on/CounterfeitProduct。
Evidence:
{info.evidence or "[Describe your evidence here - Screenshot、TestPurchaseResult etc]"}
should Sellernot is WeProductAuthorized distributor of。WeRequestImmediately will this Seller from We Listing in Remove。
Contact info: {info.contact_email or "[Your email]"}
CompanyName: {info.company_name or "[youCompanyname]"}
```
---
## SubmitStep
1. Login Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation" (ReportInfringement)
3. ChoiceInfringementCategoryType
4. Input ASIN AndSellerInformation
5. PasteAboveComplaintText
6. UploadEvidence (Screenshot、Invoice、Test Buy Photo)
7. SubmitandRecord Case ID
---
## EvidenceList
☐ Show notAuthorizedSeller Listing Screenshot
☐ Test Buy Invoice/OrderConfirm
☐ Authentic vs suspected counterfeitComparisonPhoto
☐ Trademark registration certificate
☐ Authorizedbook (Proof should SellerNot obtainedAuthorized)
"""
def generate_test_buy_guide_zh() -> str:
"""Generate Test Buy Operation guide ( in text)"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY Operation guide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## item
Test Buy (TestPurchase) Is fromSuspiciousCounterfeit/notAuthorizedSeller at PurchaseProduct,Process of collecting physical evidence for complaint。
---
## Operation process
### 1. Preparation work
☐ CreateIndependent Amazon BuyerAccount (not need and SellerAccountAssociate)
☐ Use different deliveryAddress
☐ Prepare camera for recording
☐ Prepare authentic product forComparison
### 2. Purchase
☐ ChoiceSuspiciousSellerQuote (not need select Buy Box)
☐ ScreenshotProductPage,DisplaySellerNameAndPrice
☐ ScreenshotSettlementPage,PackagecontainSellerInformation
☐ CompletePurchaseandSaveOrderConfirm
☐ RecordOrdernumber: ________________
### 3. Receive after Record
☐ Photo of unopened package (Show shipping label)
☐ Video record unboxing process
☐ many angleDegreePhotoProduct
☐ and AuthenticSide by sideComparison:
- PackagingDifference
- Tag/Print quality
- ProductQuality/Workmanship
- heavy quantityComparison
- Serial number verification
☐ Keep all packaging materials
### 4. EvidenceOrganize
CreateFolder:
```
test_buy_Evidence/
├── 01_listingScreenshot/
├── 02_OrderConfirm/
├── 03_Package photo/
├── 04_UnboxingVideo/
├── 05_ProductComparison/
└── 06_Notes.txt
```
### 5. SubmitComplaint
☐ Organize all evidence
☐ Write detailed complaint (UseTemplate)
☐ Pass Brand Registry Submit
☐ Include in complaintOrdernumber
☐ Upload photo/Video
---
## Timeline
number 1 days: below single
number 3-7 days: Receive
number 7-8 days: RecordandComparison
number 8-10 days: Organize and submit complaint
number 10-21 days: Amazon ReviewPeriod
---
## CostTrack
| Itemitem | Fee |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| ReturnShipping | $_____ |
| Total | $_____ |
*note: Can be recovered in legal proceedings*
"""
# ============================================================
# CLI
# ============================================================
def main():
import sys
# DemoData
info = ComplaintInfo(
brand_name="TechGadget",
trademark_number="US12345678",
asin="B08XXXXXX1",
seller_name="CheapDeals123",
seller_id="X9Y8Z7W6V5U4T3",
violation_type="Unauthorized Sale / Suspected Counterfeit",
evidence="Test buy received product with different packaging and lower quality than authentic product.",
contact_email="[email protected]",
company_name="TechGadget Inc.",
)
lang = "zh" if "--zh" in sys.argv else "en"
template_type = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "all"
if template_type == "complaint" or template_type == "all":
if lang == "zh":
print(generate_brand_registry_complaint_zh(info))
else:
print(generate_brand_registry_complaint(info))
if template_type == "cease" or template_type == "all":
print(generate_cease_desist(info))
if template_type == "testbuy" or template_type == "all":
if lang == "zh":
print(generate_test_buy_guide_zh())
else:
print(generate_test_buy_guide())
if template_type == "map" or template_type == "all":
print(generate_map_violation_notice(info, 18.99, 29.99))
if __name__ == "__main__":
main()
eBay brand protection toolkit. Detect unauthorized sellers, counterfeits, and VeRO violations. Includes price monitoring, trademark abuse detection, VeRO com...
---
name: brand-protection-ebay
version: 1.0.0
description: "eBay brand protection toolkit. Detect unauthorized sellers, counterfeits, and VeRO violations. Includes price monitoring, trademark abuse detection, VeRO complaint templates, and enforcement guides. No API key required."
metadata: {"nexscope":{"emoji":"🛡️","category":"ecommerce"}}
---
# Brand Protection — eBay 🛡️
Protect your brand from unauthorized sellers and counterfeits on eBay.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-protection-ebay -g
```
## Features
- **Unauthorized Seller Detection** — Find sellers without authorization
- **Price Monitoring** — MAP violation alerts
- **Counterfeit Signals** — Feedback-based fake detection
- **Trademark Abuse** — Listing title/description infringement
- **VeRO Complaint Templates** — eBay's rights owner program
- **Enforcement Guide** — Step-by-step takedown process
## eBay-Specific Detection
| Dimension | Method | Risk Level |
|-----------|--------|------------|
| Unauthorized Sellers | Seller ID monitoring | 🔴 High |
| Price Violations | Below MAP detection | 🔴 High |
| Counterfeit | Feedback keyword analysis | 🔴 High |
| Trademark | Title pattern matching | ⚠️ Medium |
## Risk Levels
| Level | Description | Action |
|-------|-------------|--------|
| 🔴 High | Immediate threat | File VeRO within 24h |
| ⚠️ Medium | Potential concern | Monitor and investigate |
| ✅ Low | Normal activity | Continue monitoring |
## Input Configuration
```json
{
"brand_name": "YourBrand",
"trademark_number": "US12345678",
"vero_enrolled": true,
"authorized_sellers": ["seller_id_1", "seller_id_2"],
"protected_item_ids": ["123456789012"],
"min_price": 29.99
}
```
## Usage
### Detection
```bash
python3 scripts/detector.py
```
### Generate Complaint Templates
```bash
# VeRO complaint
python3 scripts/templates.py vero
# Cease & Desist letter
python3 scripts/templates.py cease-desist
# Test buy guide
python3 scripts/templates.py testbuy
```
## Output Example
```
🛡️ eBay Brand Protection Report
Brand: YourBrand
Items Monitored: 8
Analysis Date: 2024-01-15
━━━━━━━━━━━━━━━━━━━━━━━━
🔴 HIGH RISK ALERTS
Item: 123456789012
├── Unauthorized seller detected
├── Price: $15.99 (MAP: $29.99)
└── Action: File VeRO complaint
━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ COUNTERFEIT SIGNALS
Feedback mentioning "fake": 3
Feedback mentioning "not genuine": 2
Recommendation: Order test buy
```
## VeRO Program
eBay's Verified Rights Owner Program allows brand owners to:
- Report counterfeit listings
- Remove trademark violations
- Protect intellectual property
## Action Workflow
```
Monitor Listings
↓
Detect Violation
↓
Collect Evidence
↓
File VeRO Complaint
↓
Track Removal
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/detector.py
#!/usr/bin/env python3
"""
Brand Protection Detector - Core Engine
Brand ProtectionDetector - Core Engine
Features:
- Hijacker Detection (Hijacker Detection)
- PriceAbnormalMonitoring (Price Alert)
- CounterfeitIdentify (Counterfeit Detection)
- ImageStolenDetection (Image Theft)
- RiskEvaluate (Risk Assessment)
- Rights protectionRecommendation (Action Recommendations)
Version: 1.0.0
"""
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum
from datetime import datetime
import sys
import re
class RiskLevel(Enum):
"""RiskGrade"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class ViolationType(Enum):
"""InfringementCategoryType"""
HIJACKER = "hijacker" # Hijacking
COUNTERFEIT = "counterfeit" # Counterfeit
PRICE_VIOLATION = "price" # PriceViolation
IMAGE_THEFT = "image_theft" # ImageStolen
TRADEMARK = "trademark" # TrademarkInfringement
LISTING_ABUSE = "listing_abuse" # Listing Abuse
# ============================================================
# Data Structures
# ============================================================
@dataclass
class BrandInfo:
"""BrandInformation"""
brand_name: str
trademark_number: Optional[str] = None
brand_registry: bool = False
authorized_sellers: List[str] = field(default_factory=list)
protected_asins: List[str] = field(default_factory=list)
min_price: Optional[float] = None # MAP most low price
logo_url: Optional[str] = None
@dataclass
class SellerInfo:
"""SellerInformation"""
seller_id: str
seller_name: str
price: float
is_fba: bool = False
rating: Optional[float] = None
review_count: Optional[int] = None
is_authorized: bool = False
storefront_url: Optional[str] = None
@dataclass
class ListingInfo:
"""Listing Information"""
asin: str
title: str
brand_in_title: bool = False
price: float = 0.0
image_urls: List[str] = field(default_factory=list)
seller_count: int = 1
sellers: List[SellerInfo] = field(default_factory=list)
buy_box_seller: Optional[str] = None
category: Optional[str] = None
@dataclass
class Violation:
"""InfringementRecord"""
violation_type: ViolationType
risk_level: RiskLevel
seller: Optional[SellerInfo] = None
listing: Optional[ListingInfo] = None
evidence: List[str] = field(default_factory=list)
description: str = ""
description_zh: str = ""
recommended_action: str = ""
recommended_action_zh: str = ""
@dataclass
class DetectionResult:
"""DetectionResult"""
brand: BrandInfo
scan_time: str
total_asins_scanned: int
violations: List[Violation]
risk_score: int # 0-100
risk_level: RiskLevel
summary: str
summary_zh: str
action_plan: List[Dict[str, str]]
# ============================================================
# DetectionLogic
# ============================================================
def detect_hijackers(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionHijacking"""
violations = []
for seller in listing.sellers:
# skip AuthorizedSeller
if seller.seller_id in brand.authorized_sellers:
continue
if seller.is_authorized:
continue
# FoundnotAuthorizedSeller
risk = RiskLevel.HIGH if listing.buy_box_seller == seller.seller_id else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.HIJACKER,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Unauthorized seller on ASIN: {listing.asin}",
f"Seller: {seller.seller_name} ({seller.seller_id})",
f"Price: seller.price",
],
description=f"Unauthorized seller '{seller.seller_name}' found on your listing",
description_zh=f"FoundnotAuthorizedSeller '{seller.seller_name}' in you Listing above Sale",
recommended_action="File Brand Registry complaint or send cease & desist",
recommended_action_zh="Pass Brand Registry Complaint or cease and desist letter",
))
return violations
def detect_price_violations(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionPriceViolation"""
violations = []
if brand.min_price is None:
return violations
for seller in listing.sellers:
if seller.price < brand.min_price:
discount = (brand.min_price - seller.price) / brand.min_price * 100
risk = RiskLevel.CRITICAL if discount > 30 else RiskLevel.HIGH if discount > 15 else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.PRICE_VIOLATION,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Price seller.price below MAP brand.min_price",
f"Discount: {discount:.1f}% below minimum",
],
description=f"Seller '{seller.seller_name}' selling {discount:.1f}% below MAP",
description_zh=f"Seller '{seller.seller_name}' Selling Price low at MAP {discount:.1f}%",
recommended_action="Send MAP violation notice, consider distribution review",
recommended_action_zh="Send MAP Violation notice,ConsiderReviewDistributionChannel",
))
return violations
def detect_counterfeit_signals(listing: ListingInfo, reviews: List[Dict] = None) -> List[Violation]:
"""DetectionCounterfeit Signals"""
violations = []
# SuspiciousKeywords
counterfeit_keywords = [
"fake", "counterfeit", "not genuine", "knockoff", "replica",
"poor quality", "not authentic", "cheap copy", "different from picture",
"Counterfeit", "fake", "Imitation", "Knockoff", "Poor quality", "AndImageDifferent",
]
if reviews:
suspicious_reviews = []
for review in reviews:
content = review.get("content", "").lower()
for keyword in counterfeit_keywords:
if keyword.lower() in content:
suspicious_reviews.append(review)
break
if len(suspicious_reviews) >= 3:
violations.append(Violation(
violation_type=ViolationType.COUNTERFEIT,
risk_level=RiskLevel.CRITICAL,
listing=listing,
evidence=[
f"Found {len(suspicious_reviews)} reviews mentioning counterfeit/fake",
"Sample keywords: " + ", ".join(counterfeit_keywords[:5]),
],
description=f"Multiple reviews indicate potential counterfeit products",
description_zh=f" many itemReviewmention and Counterfeit/Imitation,ExistCounterfeitRisk",
recommended_action="Initiate Test Buy to collect physical evidence",
recommended_action_zh="Proceed Test Buy Test purchase to collect physical evidence",
))
return violations
def detect_trademark_abuse(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionTrademarkAbuse"""
violations = []
# CheckWhether title abuses brand name
title_lower = listing.title.lower()
brand_lower = brand.brand_name.lower()
# SuspiciousMode:Brandname + "compatible", "for", "replacement"
abuse_patterns = [
f"for {brand_lower}",
f"compatible with {brand_lower}",
f"{brand_lower} compatible",
f"fits {brand_lower}",
f"replacement for {brand_lower}",
]
for pattern in abuse_patterns:
if pattern in title_lower:
violations.append(Violation(
violation_type=ViolationType.TRADEMARK,
risk_level=RiskLevel.MEDIUM,
listing=listing,
evidence=[
f"Title contains: '{pattern}'",
f"Full title: {listing.title}",
],
description=f"Potential trademark abuse in listing title",
description_zh=f"Listing Title may contain trademark abuse",
recommended_action="File trademark complaint if unauthorized use",
recommended_action_zh=" such as notAuthorizedUse,SubmitTrademarkInfringementComplaint",
))
break
return violations
def calculate_risk_score(violations: List[Violation]) -> tuple:
"""CalculateRiskRating"""
if not violations:
return 0, RiskLevel.LOW
# Weight
weights = {
RiskLevel.LOW: 5,
RiskLevel.MEDIUM: 15,
RiskLevel.HIGH: 30,
RiskLevel.CRITICAL: 50,
}
total_score = sum(weights[v.risk_level] for v in violations)
score = min(100, total_score)
if score >= 70:
level = RiskLevel.CRITICAL
elif score >= 40:
level = RiskLevel.HIGH
elif score >= 20:
level = RiskLevel.MEDIUM
else:
level = RiskLevel.LOW
return score, level
def generate_action_plan(violations: List[Violation], brand: BrandInfo) -> List[Dict[str, str]]:
"""GenerateRights action plan"""
actions = []
# by CategoryTypeGroup
hijackers = [v for v in violations if v.violation_type == ViolationType.HIJACKER]
counterfeits = [v for v in violations if v.violation_type == ViolationType.COUNTERFEIT]
price_violations = [v for v in violations if v.violation_type == ViolationType.PRICE_VIOLATION]
# HijackingProcess
if hijackers:
if brand.brand_registry:
actions.append({
"priority": "1",
"action": "Report via Brand Registry",
"action_zh": "Pass Brand Registry Complaint",
"detail": f"Report {len(hijackers)} unauthorized seller(s) via Amazon Brand Registry portal",
"detail_zh": f"Pass Amazon Brand Registry PortalComplaint {len(hijackers)} notAuthorizedSeller",
"timeline": "24-48 hours",
})
else:
actions.append({
"priority": "1",
"action": "Send Cease & Desist",
"action_zh": "SendStopInfringementLetter",
"detail": "Contact sellers directly with legal notice",
"detail_zh": "Direct contactSellerSend legal letter",
"timeline": "3-5 business days",
})
# CounterfeitProcess
if counterfeits:
actions.append({
"priority": "1",
"action": "Initiate Test Buy",
"action_zh": "Proceed Test Buy",
"detail": "Purchase product from suspected seller to collect physical evidence",
"detail_zh": " from SuspiciousSeller at PurchaseProductCollectPhysicalEvidence",
"timeline": "7-14 days",
})
actions.append({
"priority": "2",
"action": "File Counterfeit Report",
"action_zh": "SubmitCounterfeitComplaint",
"detail": "Submit counterfeit complaint with evidence to Amazon",
"detail_zh": " to Amazon Submit counterfeit complaint and evidence",
"timeline": "After test buy",
})
# PriceViolationProcess
if price_violations:
actions.append({
"priority": "2",
"action": "Send MAP Violation Notice",
"action_zh": "Send MAP Violation notice",
"detail": f"Notify {len(price_violations)} seller(s) of MAP policy violation",
"detail_zh": f"Notification {len(price_violations)} Seller MAP Policy violation",
"timeline": "48-72 hours",
})
# GeneralRecommendation
if not brand.brand_registry and violations:
actions.append({
"priority": "3",
"action": "Enroll in Brand Registry",
"action_zh": "Register Brand Registry",
"detail": "Get enhanced brand protection tools from Amazon",
"detail_zh": "Get Amazon EnhanceBrand ProtectionTool",
"timeline": "2-4 weeks (requires trademark)",
})
return actions
# ============================================================
# MainDetectionFunction
# ============================================================
def detect(
brand: BrandInfo,
listings: List[ListingInfo],
reviews: Dict[str, List[Dict]] = None
) -> DetectionResult:
"""MainDetectionFunction"""
all_violations = []
for listing in listings:
# Hijacker Detection
all_violations.extend(detect_hijackers(brand, listing))
# PriceViolationDetection
all_violations.extend(detect_price_violations(brand, listing))
# TrademarkAbuseDetection
all_violations.extend(detect_trademark_abuse(brand, listing))
# Counterfeit SignalsDetection
if reviews and listing.asin in reviews:
all_violations.extend(detect_counterfeit_signals(listing, reviews[listing.asin]))
# CalculateRiskRating
risk_score, risk_level = calculate_risk_score(all_violations)
# GenerateAction Plan
action_plan = generate_action_plan(all_violations, brand)
# GenerateSummary
hijacker_count = len([v for v in all_violations if v.violation_type == ViolationType.HIJACKER])
counterfeit_count = len([v for v in all_violations if v.violation_type == ViolationType.COUNTERFEIT])
if risk_level == RiskLevel.CRITICAL:
status = "🚨 CRITICAL"
status_zh = "🚨 CriticalRisk"
elif risk_level == RiskLevel.HIGH:
status = "🔴 HIGH RISK"
status_zh = "🔴 High Risk"
elif risk_level == RiskLevel.MEDIUM:
status = "⚠️ MEDIUM RISK"
status_zh = "⚠️ in etcRisk"
else:
status = "✅ LOW RISK"
status_zh = "✅ Low Risk"
summary = f"{status} | {len(all_violations)} violation(s) found | {hijacker_count} hijacker(s), {counterfeit_count} counterfeit signal(s)"
summary_zh = f"{status_zh} | Found {len(all_violations)} Infringement | {hijacker_count} Hijacking, {counterfeit_count} Counterfeit Signals"
return DetectionResult(
brand=brand,
scan_time=datetime.now().isoformat(),
total_asins_scanned=len(listings),
violations=all_violations,
risk_score=risk_score,
risk_level=risk_level,
summary=summary,
summary_zh=summary_zh,
action_plan=action_plan,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(result: DetectionResult, lang: str = "en") -> str:
"""FormatReport"""
b = result.brand
if lang == "zh":
lines = [
"🛡️ **Brand ProtectionDetectionReport**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ already Register' if b.brand_registry else '❌ notRegister'}",
f"**ScanTime**: {result.scan_time[:19]}",
f"**Scan ASIN **: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 RiskRating: {result.risk_score}/100",
"",
result.summary_zh,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ InfringementDetails",
"",
]
if not result.violations:
lines.append("✅ No infringement found")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description_zh}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Recommendation: {v.recommended_action_zh}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Rights action plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action_zh']}**")
lines.append(f" {action['detail_zh']}")
lines.append(f" ExpectedTime: {action['timeline']}")
lines.append("")
else:
lines = [
"🛡️ **Brand Protection Detection Report**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ Enrolled' if b.brand_registry else '❌ Not Enrolled'}",
f"**Scan Time**: {result.scan_time[:19]}",
f"**ASINs Scanned**: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 Risk Score: {result.risk_score}/100",
"",
result.summary,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Violations Found",
"",
]
if not result.violations:
lines.append("✅ No violations detected")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Action: {v.recommended_action}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Action Plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action']}**")
lines.append(f" {action['detail']}")
lines.append(f" Timeline: {action['timeline']}")
lines.append("")
return "\n".join(lines)
# ============================================================
# DemoData
# ============================================================
def get_demo_data():
"""GetDemoData"""
brand = BrandInfo(
brand_name="TechGadget",
trademark_number="US12345678",
brand_registry=True,
authorized_sellers=["A1B2C3D4E5F6G7"],
protected_asins=["B08XXXXXX1", "B08XXXXXX2"],
min_price=29.99,
)
listings = [
ListingInfo(
asin="B08XXXXXX1",
title="TechGadget Premium Wireless Charger",
brand_in_title=True,
price=29.99,
seller_count=3,
buy_box_seller="A1B2C3D4E5F6G7",
sellers=[
SellerInfo(
seller_id="A1B2C3D4E5F6G7",
seller_name="TechGadget Official",
price=29.99,
is_fba=True,
rating=4.8,
is_authorized=True,
),
SellerInfo(
seller_id="X9Y8Z7W6V5U4T3",
seller_name="CheapDeals123",
price=18.99,
is_fba=False,
rating=3.2,
is_authorized=False,
),
SellerInfo(
seller_id="M1N2O3P4Q5R6S7",
seller_name="BestPriceStore",
price=24.99,
is_fba=True,
rating=4.1,
is_authorized=False,
),
],
),
ListingInfo(
asin="B09YYYYYY1",
title="Compatible with TechGadget Wireless Charger Case",
brand_in_title=True,
price=9.99,
seller_count=1,
sellers=[
SellerInfo(
seller_id="K1L2M3N4O5P6Q7",
seller_name="AccessoryWorld",
price=9.99,
is_fba=True,
rating=4.0,
is_authorized=False,
),
],
),
]
reviews = {
"B08XXXXXX1": [
{"content": "Great product, works perfectly!", "rating": 5},
{"content": "Received a fake product, not genuine TechGadget", "rating": 1},
{"content": "This is counterfeit, poor quality", "rating": 1},
{"content": "Not authentic, different from picture", "rating": 2},
{"content": "Amazing charger, fast shipping", "rating": 5},
],
}
return brand, listings, reviews
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
# DemoMode
brand, listings, reviews = get_demo_data()
# ExecuteDetection
result = detect(brand, listings, reviews)
# OutputReport
print(format_report(result, lang))
if __name__ == "__main__":
main()
FILE:scripts/templates.py
#!/usr/bin/env python3
"""
Brand Protection Templates - Complaint & Legal Templates
Brand ProtectionTemplate - Complaint and legal document templates
Packagecontain:
- Brand Registry Complaint Templates
- Cease & Desist StopInfringementLetter
- Test Buy Operation guide
- MAP Violation notice
- LegalLetterTemplate
Version: 1.0.0
"""
from dataclasses import dataclass
from typing import Optional
from datetime import datetime
@dataclass
class ComplaintInfo:
"""ComplaintInformation"""
brand_name: str
trademark_number: Optional[str] = None
asin: str = ""
seller_name: str = ""
seller_id: str = ""
violation_type: str = ""
evidence: str = ""
contact_email: str = ""
company_name: str = ""
# ============================================================
# Complaint Templates
# ============================================================
def generate_brand_registry_complaint(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY COMPLAINT TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## Report Details
**Brand Name**: {info.brand_name}
**Trademark Number**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**Infringing Seller**: {info.seller_name} ({info.seller_id})
**Violation Type**: {info.violation_type}
---
## Complaint Text (Copy & Paste)
```
I am the brand owner of {info.brand_name} (Trademark #{info.trademark_number or "[YOUR TRADEMARK NUMBER]"}).
The seller "{info.seller_name}" (Seller ID: {info.seller_id}) is selling unauthorized/counterfeit products on ASIN {info.asin}.
Evidence:
{info.evidence or "[Describe your evidence here - screenshots, test buy results, etc.]"}
This seller is NOT an authorized reseller of our products. We request immediate removal of this seller from our listing.
Contact: {info.contact_email or "[YOUR EMAIL]"}
Company: {info.company_name or "[YOUR COMPANY NAME]"}
```
---
## Steps to Submit
1. Log into Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation"
3. Select violation type
4. Enter ASIN and seller information
5. Paste complaint text above
6. Upload evidence (screenshots, invoices, test buy photos)
7. Submit and note case ID
---
## Evidence Checklist
☐ Screenshots of listing showing unauthorized seller
☐ Invoice/order confirmation from test buy
☐ Photos comparing authentic vs suspected counterfeit
☐ Trademark registration certificate
☐ Authorization letter (showing seller is NOT authorized)
"""
def generate_cease_desist(info: ComplaintInfo) -> str:
"""GenerateStopInfringementLetterTemplate"""
today = datetime.now().strftime("%B %d, %Y")
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 CEASE AND DESIST LETTER TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**CEASE AND DESIST NOTICE**
To: {info.seller_name}
Seller ID: {info.seller_id}
Re: Unauthorized Sale of {info.brand_name} Products
---
Dear {info.seller_name},
This letter serves as formal notice that you are engaging in unauthorized sale of products bearing the {info.brand_name}® trademark (Registration No. {info.trademark_number or "[TRADEMARK NUMBER]"}) on Amazon.com, specifically on ASIN: {info.asin}.
**YOU ARE NOT AN AUTHORIZED RESELLER** of {info.brand_name} products. Your unauthorized sale of these products constitutes:
1. Trademark infringement under 15 U.S.C. § 1114
2. False designation of origin under 15 U.S.C. § 1125(a)
3. Violation of Amazon's Anti-Counterfeiting Policy
**DEMAND**
We hereby demand that you:
1. Immediately cease and desist all sales of {info.brand_name} products
2. Remove all {info.brand_name} product listings from your seller account
3. Provide a written confirmation of compliance within 5 business days
**CONSEQUENCES OF NON-COMPLIANCE**
Failure to comply with this demand will result in:
- Report to Amazon Brand Registry for listing removal
- Legal action seeking injunctive relief and monetary damages
- Report to law enforcement if counterfeit goods are involved
This letter is not intended to be a complete statement of the facts or law applicable to this matter, and nothing herein should be construed as a waiver of any rights or remedies.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
---
## Sending Instructions
1. Send via Amazon Buyer-Seller Messaging (if available)
2. Send via seller's contact email (find in storefront)
3. Keep copies of all correspondence
4. Set 5-day deadline for response
5. Escalate to legal action if no response
"""
def generate_test_buy_guide() -> str:
"""Generate Test Buy Operation guide"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY PROCEDURE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Purpose
Test Buy is the process of purchasing products from suspected counterfeit/unauthorized sellers to collect physical evidence for your complaint.
---
## Step-by-Step Process
### 1. Preparation
☐ Create a separate Amazon buyer account (not linked to seller account)
☐ Use a different shipping address if possible
☐ Prepare camera for documentation
☐ Have authentic product ready for comparison
### 2. Purchase
☐ Select the suspected seller's offer (not Buy Box)
☐ Screenshot the product page showing seller name and price
☐ Screenshot checkout page with seller info
☐ Complete purchase and save order confirmation
☐ Note Order ID: ________________
### 3. Documentation Upon Arrival
☐ Photograph unopened package (showing shipping label)
☐ Video record unboxing process
☐ Photograph product from multiple angles
☐ Compare with authentic product side-by-side:
- Packaging differences
- Label/printing quality
- Product quality/finish
- Weight comparison
- Serial number verification
☐ Keep all packaging materials
### 4. Evidence Organization
Create folder with:
```
test_buy_evidence/
├── 01_listing_screenshots/
├── 02_order_confirmation/
├── 03_package_photos/
├── 04_unboxing_video/
├── 05_product_comparison/
└── 06_notes.txt
```
### 5. Submit Complaint
☐ Compile all evidence
☐ Write detailed complaint (use template)
☐ Submit via Brand Registry
☐ Include Order ID in complaint
☐ Upload photos/video
---
## Evidence Checklist
**Screenshots**
☐ Listing page with seller
☐ Seller storefront
☐ Order confirmation
☐ Shipping confirmation
☐ Delivery confirmation
**Photos**
☐ Package exterior (4+ angles)
☐ Shipping label close-up
☐ Product in packaging
☐ Product removed
☐ Side-by-side with authentic
☐ Close-up of differences
**Documents**
☐ Invoice from test buy
☐ Authentication certificate (if available)
☐ Trademark registration
---
## Timeline
Day 1: Place order
Day 3-7: Receive package
Day 7-8: Document and compare
Day 8-10: Compile and submit complaint
Day 10-21: Amazon review period
---
## Cost Tracking
| Item | Cost |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| Return Shipping | $_____ |
| Total | $_____ |
*Note: May be recoverable in legal action*
"""
def generate_map_violation_notice(info: ComplaintInfo, violation_price: float, map_price: float) -> str:
"""Generate MAP Violation notice"""
today = datetime.now().strftime("%B %d, %Y")
discount = (map_price - violation_price) / map_price * 100
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 MAP VIOLATION NOTICE TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**MINIMUM ADVERTISED PRICE (MAP) VIOLATION NOTICE**
To: {info.seller_name}
Re: MAP Policy Violation - {info.brand_name}
---
Dear {info.seller_name},
This notice is to inform you that your current advertised price for {info.brand_name} products violates our Minimum Advertised Price (MAP) policy.
**Violation Details:**
| Product | ASIN | Your Price | MAP Price | Violation |
|---------|------|------------|-----------|-----------|
| {info.brand_name} | {info.asin} | .2f | .2f | -{discount:.1f}% |
**MAP Policy Terms:**
As an authorized/unauthorized reseller of {info.brand_name} products, you are required to maintain advertised prices at or above the Minimum Advertised Price. This policy ensures:
- Fair competition among resellers
- Brand value protection
- Quality customer experience
**Required Action:**
Please adjust your advertised price to .2f or higher within **48 hours** of receiving this notice.
**Consequences of Non-Compliance:**
Continued violation of our MAP policy may result in:
- Removal from authorized reseller program
- Report to Amazon for policy violation
- Supply chain restrictions
Please confirm compliance by replying to this notice.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
"""
# ============================================================
# in textTemplate
# ============================================================
def generate_brand_registry_complaint_zh(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates ( in text)"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY Complaint Templates
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## ComplaintInformation
**BrandName**: {info.brand_name}
**TrademarkRegisternumber**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**InfringementSeller**: {info.seller_name} ({info.seller_id})
**InfringementCategoryType**: {info.violation_type}
---
## ComplaintText (CopyPaste)
```
I is {info.brand_name} BrandOwner (TrademarkRegisternumber: {info.trademark_number or "[youTrademarknumber]"})。
Seller "{info.seller_name}" (Seller ID: {info.seller_id}) positive in ASIN {info.asin} Selling unauthorized on/CounterfeitProduct。
Evidence:
{info.evidence or "[Describe your evidence here - Screenshot、TestPurchaseResult etc]"}
should Sellernot is WeProductAuthorized distributor of。WeRequestImmediately will this Seller from We Listing in Remove。
Contact info: {info.contact_email or "[Your email]"}
CompanyName: {info.company_name or "[youCompanyname]"}
```
---
## SubmitStep
1. Login Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation" (ReportInfringement)
3. ChoiceInfringementCategoryType
4. Input ASIN AndSellerInformation
5. PasteAboveComplaintText
6. UploadEvidence (Screenshot、Invoice、Test Buy Photo)
7. SubmitandRecord Case ID
---
## EvidenceList
☐ Show notAuthorizedSeller Listing Screenshot
☐ Test Buy Invoice/OrderConfirm
☐ Authentic vs suspected counterfeitComparisonPhoto
☐ Trademark registration certificate
☐ Authorizedbook (Proof should SellerNot obtainedAuthorized)
"""
def generate_test_buy_guide_zh() -> str:
"""Generate Test Buy Operation guide ( in text)"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY Operation guide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## item
Test Buy (TestPurchase) Is fromSuspiciousCounterfeit/notAuthorizedSeller at PurchaseProduct,Process of collecting physical evidence for complaint。
---
## Operation process
### 1. Preparation work
☐ CreateIndependent Amazon BuyerAccount (not need and SellerAccountAssociate)
☐ Use different deliveryAddress
☐ Prepare camera for recording
☐ Prepare authentic product forComparison
### 2. Purchase
☐ ChoiceSuspiciousSellerQuote (not need select Buy Box)
☐ ScreenshotProductPage,DisplaySellerNameAndPrice
☐ ScreenshotSettlementPage,PackagecontainSellerInformation
☐ CompletePurchaseandSaveOrderConfirm
☐ RecordOrdernumber: ________________
### 3. Receive after Record
☐ Photo of unopened package (Show shipping label)
☐ Video record unboxing process
☐ many angleDegreePhotoProduct
☐ and AuthenticSide by sideComparison:
- PackagingDifference
- Tag/Print quality
- ProductQuality/Workmanship
- heavy quantityComparison
- Serial number verification
☐ Keep all packaging materials
### 4. EvidenceOrganize
CreateFolder:
```
test_buy_Evidence/
├── 01_listingScreenshot/
├── 02_OrderConfirm/
├── 03_Package photo/
├── 04_UnboxingVideo/
├── 05_ProductComparison/
└── 06_Notes.txt
```
### 5. SubmitComplaint
☐ Organize all evidence
☐ Write detailed complaint (UseTemplate)
☐ Pass Brand Registry Submit
☐ Include in complaintOrdernumber
☐ Upload photo/Video
---
## Timeline
number 1 days: below single
number 3-7 days: Receive
number 7-8 days: RecordandComparison
number 8-10 days: Organize and submit complaint
number 10-21 days: Amazon ReviewPeriod
---
## CostTrack
| Itemitem | Fee |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| ReturnShipping | $_____ |
| Total | $_____ |
*note: Can be recovered in legal proceedings*
"""
# ============================================================
# CLI
# ============================================================
def main():
import sys
# DemoData
info = ComplaintInfo(
brand_name="TechGadget",
trademark_number="US12345678",
asin="B08XXXXXX1",
seller_name="CheapDeals123",
seller_id="X9Y8Z7W6V5U4T3",
violation_type="Unauthorized Sale / Suspected Counterfeit",
evidence="Test buy received product with different packaging and lower quality than authentic product.",
contact_email="[email protected]",
company_name="TechGadget Inc.",
)
lang = "zh" if "--zh" in sys.argv else "en"
template_type = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "all"
if template_type == "complaint" or template_type == "all":
if lang == "zh":
print(generate_brand_registry_complaint_zh(info))
else:
print(generate_brand_registry_complaint(info))
if template_type == "cease" or template_type == "all":
print(generate_cease_desist(info))
if template_type == "testbuy" or template_type == "all":
if lang == "zh":
print(generate_test_buy_guide_zh())
else:
print(generate_test_buy_guide())
if template_type == "map" or template_type == "all":
print(generate_map_violation_notice(info, 18.99, 29.99))
if __name__ == "__main__":
main()
Amazon brand protection toolkit. Detect hijackers, counterfeits, and unauthorized sellers. Includes MAP violation monitoring, trademark abuse detection, comp...
---
name: brand-protection-amazon
version: 1.0.0
description: "Amazon brand protection toolkit. Detect hijackers, counterfeits, and unauthorized sellers. Includes MAP violation monitoring, trademark abuse detection, complaint templates for Brand Registry, and test buy evidence collection guides. No API key required."
metadata: {"nexscope":{"emoji":"🛡️","category":"ecommerce"}}
---
# Brand Protection — Amazon 🛡️
Protect your brand from hijackers, counterfeits, and unauthorized sellers on Amazon.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-protection-amazon -g
```
## Features
- **Hijacker Detection** — Find unauthorized sellers on your listings
- **Price Monitoring** — MAP violation alerts
- **Counterfeit Signals** — Review-based fake detection
- **Trademark Abuse** — Title/keyword infringement detection
- **Complaint Templates** — Brand Registry, C&D letters
- **Test Buy Guide** — Evidence collection procedure
## Detection Dimensions
| Dimension | Method | Risk Level |
|-----------|--------|------------|
| Hijackers | Seller count monitoring | 🔴 High |
| Price Violations | Below MAP detection | 🔴 High |
| Counterfeit | Review keyword analysis | 🔴 High |
| Trademark | Title pattern matching | ⚠️ Medium |
## Risk Levels
| Level | Description | Action |
|-------|-------------|--------|
| 🔴 High | Immediate threat to brand | Take action within 24h |
| ⚠️ Medium | Potential concern | Monitor and investigate |
| ✅ Low | Normal activity | Continue monitoring |
## Input Configuration
```json
{
"brand_name": "YourBrand",
"trademark_number": "US12345678",
"brand_registry": true,
"authorized_sellers": ["A1B2C3D4E5F6G7"],
"protected_asins": ["B08XXXXXX1"],
"min_price": 29.99
}
```
## Usage
### Hijacker Detection
```bash
python3 scripts/detector.py
```
### Generate Complaint Templates
```bash
# Brand Registry complaint
python3 scripts/templates.py complaint
# Cease & Desist letter
python3 scripts/templates.py cease-desist
# Test buy guide
python3 scripts/templates.py testbuy
```
## Output Example
```
🛡️ Brand Protection Report
Brand: YourBrand
ASINs Monitored: 5
Analysis Date: 2024-01-15
━━━━━━━━━━━━━━━━━━━━━━━━
🔴 HIGH RISK ALERTS
ASIN: B08XXXXXX1
├── 3 unauthorized sellers detected
├── Lowest price: $19.99 (MAP: $29.99)
└── Action: File Brand Registry complaint
━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ COUNTERFEIT SIGNALS
Reviews mentioning "fake": 5
Reviews mentioning "not authentic": 2
Recommendation: Order test buy
```
## Complaint Templates Included
| Template | Use Case |
|----------|----------|
| Brand Registry | Report to Amazon |
| Cease & Desist | Direct seller contact |
| Test Buy Report | Evidence documentation |
| DMCA Takedown | Copyright infringement |
## Action Workflow
```
Monitor Listings
↓
Detect Violation
↓
Collect Evidence (Test Buy)
↓
Generate Complaint
↓
Submit to Amazon / Send C&D
↓
Track Resolution
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/detector.py
#!/usr/bin/env python3
"""
Brand Protection Detector - Core Engine
Brand ProtectionDetector - Core Engine
Features:
- Hijacker Detection (Hijacker Detection)
- PriceAbnormalMonitoring (Price Alert)
- CounterfeitIdentify (Counterfeit Detection)
- ImageStolenDetection (Image Theft)
- RiskEvaluate (Risk Assessment)
- Rights protectionRecommendation (Action Recommendations)
Version: 1.0.0
"""
import json
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from enum import Enum
from datetime import datetime
import sys
import re
class RiskLevel(Enum):
"""RiskGrade"""
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class ViolationType(Enum):
"""InfringementCategoryType"""
HIJACKER = "hijacker" # Hijacking
COUNTERFEIT = "counterfeit" # Counterfeit
PRICE_VIOLATION = "price" # PriceViolation
IMAGE_THEFT = "image_theft" # ImageStolen
TRADEMARK = "trademark" # TrademarkInfringement
LISTING_ABUSE = "listing_abuse" # Listing Abuse
# ============================================================
# Data Structures
# ============================================================
@dataclass
class BrandInfo:
"""BrandInformation"""
brand_name: str
trademark_number: Optional[str] = None
brand_registry: bool = False
authorized_sellers: List[str] = field(default_factory=list)
protected_asins: List[str] = field(default_factory=list)
min_price: Optional[float] = None # MAP most low price
logo_url: Optional[str] = None
@dataclass
class SellerInfo:
"""SellerInformation"""
seller_id: str
seller_name: str
price: float
is_fba: bool = False
rating: Optional[float] = None
review_count: Optional[int] = None
is_authorized: bool = False
storefront_url: Optional[str] = None
@dataclass
class ListingInfo:
"""Listing Information"""
asin: str
title: str
brand_in_title: bool = False
price: float = 0.0
image_urls: List[str] = field(default_factory=list)
seller_count: int = 1
sellers: List[SellerInfo] = field(default_factory=list)
buy_box_seller: Optional[str] = None
category: Optional[str] = None
@dataclass
class Violation:
"""InfringementRecord"""
violation_type: ViolationType
risk_level: RiskLevel
seller: Optional[SellerInfo] = None
listing: Optional[ListingInfo] = None
evidence: List[str] = field(default_factory=list)
description: str = ""
description_zh: str = ""
recommended_action: str = ""
recommended_action_zh: str = ""
@dataclass
class DetectionResult:
"""DetectionResult"""
brand: BrandInfo
scan_time: str
total_asins_scanned: int
violations: List[Violation]
risk_score: int # 0-100
risk_level: RiskLevel
summary: str
summary_zh: str
action_plan: List[Dict[str, str]]
# ============================================================
# DetectionLogic
# ============================================================
def detect_hijackers(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionHijacking"""
violations = []
for seller in listing.sellers:
# skip AuthorizedSeller
if seller.seller_id in brand.authorized_sellers:
continue
if seller.is_authorized:
continue
# FoundnotAuthorizedSeller
risk = RiskLevel.HIGH if listing.buy_box_seller == seller.seller_id else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.HIJACKER,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Unauthorized seller on ASIN: {listing.asin}",
f"Seller: {seller.seller_name} ({seller.seller_id})",
f"Price: seller.price",
],
description=f"Unauthorized seller '{seller.seller_name}' found on your listing",
description_zh=f"FoundnotAuthorizedSeller '{seller.seller_name}' in you Listing above Sale",
recommended_action="File Brand Registry complaint or send cease & desist",
recommended_action_zh="Pass Brand Registry Complaint or cease and desist letter",
))
return violations
def detect_price_violations(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionPriceViolation"""
violations = []
if brand.min_price is None:
return violations
for seller in listing.sellers:
if seller.price < brand.min_price:
discount = (brand.min_price - seller.price) / brand.min_price * 100
risk = RiskLevel.CRITICAL if discount > 30 else RiskLevel.HIGH if discount > 15 else RiskLevel.MEDIUM
violations.append(Violation(
violation_type=ViolationType.PRICE_VIOLATION,
risk_level=risk,
seller=seller,
listing=listing,
evidence=[
f"Price seller.price below MAP brand.min_price",
f"Discount: {discount:.1f}% below minimum",
],
description=f"Seller '{seller.seller_name}' selling {discount:.1f}% below MAP",
description_zh=f"Seller '{seller.seller_name}' Selling Price low at MAP {discount:.1f}%",
recommended_action="Send MAP violation notice, consider distribution review",
recommended_action_zh="Send MAP Violation notice,ConsiderReviewDistributionChannel",
))
return violations
def detect_counterfeit_signals(listing: ListingInfo, reviews: List[Dict] = None) -> List[Violation]:
"""DetectionCounterfeit Signals"""
violations = []
# SuspiciousKeywords
counterfeit_keywords = [
"fake", "counterfeit", "not genuine", "knockoff", "replica",
"poor quality", "not authentic", "cheap copy", "different from picture",
"Counterfeit", "fake", "Imitation", "Knockoff", "Poor quality", "AndImageDifferent",
]
if reviews:
suspicious_reviews = []
for review in reviews:
content = review.get("content", "").lower()
for keyword in counterfeit_keywords:
if keyword.lower() in content:
suspicious_reviews.append(review)
break
if len(suspicious_reviews) >= 3:
violations.append(Violation(
violation_type=ViolationType.COUNTERFEIT,
risk_level=RiskLevel.CRITICAL,
listing=listing,
evidence=[
f"Found {len(suspicious_reviews)} reviews mentioning counterfeit/fake",
"Sample keywords: " + ", ".join(counterfeit_keywords[:5]),
],
description=f"Multiple reviews indicate potential counterfeit products",
description_zh=f" many itemReviewmention and Counterfeit/Imitation,ExistCounterfeitRisk",
recommended_action="Initiate Test Buy to collect physical evidence",
recommended_action_zh="Proceed Test Buy Test purchase to collect physical evidence",
))
return violations
def detect_trademark_abuse(brand: BrandInfo, listing: ListingInfo) -> List[Violation]:
"""DetectionTrademarkAbuse"""
violations = []
# CheckWhether title abuses brand name
title_lower = listing.title.lower()
brand_lower = brand.brand_name.lower()
# SuspiciousMode:Brandname + "compatible", "for", "replacement"
abuse_patterns = [
f"for {brand_lower}",
f"compatible with {brand_lower}",
f"{brand_lower} compatible",
f"fits {brand_lower}",
f"replacement for {brand_lower}",
]
for pattern in abuse_patterns:
if pattern in title_lower:
violations.append(Violation(
violation_type=ViolationType.TRADEMARK,
risk_level=RiskLevel.MEDIUM,
listing=listing,
evidence=[
f"Title contains: '{pattern}'",
f"Full title: {listing.title}",
],
description=f"Potential trademark abuse in listing title",
description_zh=f"Listing Title may contain trademark abuse",
recommended_action="File trademark complaint if unauthorized use",
recommended_action_zh=" such as notAuthorizedUse,SubmitTrademarkInfringementComplaint",
))
break
return violations
def calculate_risk_score(violations: List[Violation]) -> tuple:
"""CalculateRiskRating"""
if not violations:
return 0, RiskLevel.LOW
# Weight
weights = {
RiskLevel.LOW: 5,
RiskLevel.MEDIUM: 15,
RiskLevel.HIGH: 30,
RiskLevel.CRITICAL: 50,
}
total_score = sum(weights[v.risk_level] for v in violations)
score = min(100, total_score)
if score >= 70:
level = RiskLevel.CRITICAL
elif score >= 40:
level = RiskLevel.HIGH
elif score >= 20:
level = RiskLevel.MEDIUM
else:
level = RiskLevel.LOW
return score, level
def generate_action_plan(violations: List[Violation], brand: BrandInfo) -> List[Dict[str, str]]:
"""GenerateRights action plan"""
actions = []
# by CategoryTypeGroup
hijackers = [v for v in violations if v.violation_type == ViolationType.HIJACKER]
counterfeits = [v for v in violations if v.violation_type == ViolationType.COUNTERFEIT]
price_violations = [v for v in violations if v.violation_type == ViolationType.PRICE_VIOLATION]
# HijackingProcess
if hijackers:
if brand.brand_registry:
actions.append({
"priority": "1",
"action": "Report via Brand Registry",
"action_zh": "Pass Brand Registry Complaint",
"detail": f"Report {len(hijackers)} unauthorized seller(s) via Amazon Brand Registry portal",
"detail_zh": f"Pass Amazon Brand Registry PortalComplaint {len(hijackers)} notAuthorizedSeller",
"timeline": "24-48 hours",
})
else:
actions.append({
"priority": "1",
"action": "Send Cease & Desist",
"action_zh": "SendStopInfringementLetter",
"detail": "Contact sellers directly with legal notice",
"detail_zh": "Direct contactSellerSend legal letter",
"timeline": "3-5 business days",
})
# CounterfeitProcess
if counterfeits:
actions.append({
"priority": "1",
"action": "Initiate Test Buy",
"action_zh": "Proceed Test Buy",
"detail": "Purchase product from suspected seller to collect physical evidence",
"detail_zh": " from SuspiciousSeller at PurchaseProductCollectPhysicalEvidence",
"timeline": "7-14 days",
})
actions.append({
"priority": "2",
"action": "File Counterfeit Report",
"action_zh": "SubmitCounterfeitComplaint",
"detail": "Submit counterfeit complaint with evidence to Amazon",
"detail_zh": " to Amazon Submit counterfeit complaint and evidence",
"timeline": "After test buy",
})
# PriceViolationProcess
if price_violations:
actions.append({
"priority": "2",
"action": "Send MAP Violation Notice",
"action_zh": "Send MAP Violation notice",
"detail": f"Notify {len(price_violations)} seller(s) of MAP policy violation",
"detail_zh": f"Notification {len(price_violations)} Seller MAP Policy violation",
"timeline": "48-72 hours",
})
# GeneralRecommendation
if not brand.brand_registry and violations:
actions.append({
"priority": "3",
"action": "Enroll in Brand Registry",
"action_zh": "Register Brand Registry",
"detail": "Get enhanced brand protection tools from Amazon",
"detail_zh": "Get Amazon EnhanceBrand ProtectionTool",
"timeline": "2-4 weeks (requires trademark)",
})
return actions
# ============================================================
# MainDetectionFunction
# ============================================================
def detect(
brand: BrandInfo,
listings: List[ListingInfo],
reviews: Dict[str, List[Dict]] = None
) -> DetectionResult:
"""MainDetectionFunction"""
all_violations = []
for listing in listings:
# Hijacker Detection
all_violations.extend(detect_hijackers(brand, listing))
# PriceViolationDetection
all_violations.extend(detect_price_violations(brand, listing))
# TrademarkAbuseDetection
all_violations.extend(detect_trademark_abuse(brand, listing))
# Counterfeit SignalsDetection
if reviews and listing.asin in reviews:
all_violations.extend(detect_counterfeit_signals(listing, reviews[listing.asin]))
# CalculateRiskRating
risk_score, risk_level = calculate_risk_score(all_violations)
# GenerateAction Plan
action_plan = generate_action_plan(all_violations, brand)
# GenerateSummary
hijacker_count = len([v for v in all_violations if v.violation_type == ViolationType.HIJACKER])
counterfeit_count = len([v for v in all_violations if v.violation_type == ViolationType.COUNTERFEIT])
if risk_level == RiskLevel.CRITICAL:
status = "🚨 CRITICAL"
status_zh = "🚨 CriticalRisk"
elif risk_level == RiskLevel.HIGH:
status = "🔴 HIGH RISK"
status_zh = "🔴 High Risk"
elif risk_level == RiskLevel.MEDIUM:
status = "⚠️ MEDIUM RISK"
status_zh = "⚠️ in etcRisk"
else:
status = "✅ LOW RISK"
status_zh = "✅ Low Risk"
summary = f"{status} | {len(all_violations)} violation(s) found | {hijacker_count} hijacker(s), {counterfeit_count} counterfeit signal(s)"
summary_zh = f"{status_zh} | Found {len(all_violations)} Infringement | {hijacker_count} Hijacking, {counterfeit_count} Counterfeit Signals"
return DetectionResult(
brand=brand,
scan_time=datetime.now().isoformat(),
total_asins_scanned=len(listings),
violations=all_violations,
risk_score=risk_score,
risk_level=risk_level,
summary=summary,
summary_zh=summary_zh,
action_plan=action_plan,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(result: DetectionResult, lang: str = "en") -> str:
"""FormatReport"""
b = result.brand
if lang == "zh":
lines = [
"🛡️ **Brand ProtectionDetectionReport**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ already Register' if b.brand_registry else '❌ notRegister'}",
f"**ScanTime**: {result.scan_time[:19]}",
f"**Scan ASIN **: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 RiskRating: {result.risk_score}/100",
"",
result.summary_zh,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ InfringementDetails",
"",
]
if not result.violations:
lines.append("✅ No infringement found")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description_zh}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Recommendation: {v.recommended_action_zh}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Rights action plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action_zh']}**")
lines.append(f" {action['detail_zh']}")
lines.append(f" ExpectedTime: {action['timeline']}")
lines.append("")
else:
lines = [
"🛡️ **Brand Protection Detection Report**",
"",
f"**Brand**: {b.brand_name}",
f"**Brand Registry**: {'✅ Enrolled' if b.brand_registry else '❌ Not Enrolled'}",
f"**Scan Time**: {result.scan_time[:19]}",
f"**ASINs Scanned**: {result.total_asins_scanned}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
f"## 🎯 Risk Score: {result.risk_score}/100",
"",
result.summary,
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Violations Found",
"",
]
if not result.violations:
lines.append("✅ No violations detected")
else:
for i, v in enumerate(result.violations[:10], 1):
risk_icon = {"critical": "🚨", "high": "🔴", "medium": "⚠️", "low": "✅"}[v.risk_level.value]
lines.append(f"**{i}. [{v.violation_type.value.upper()}] {risk_icon}**")
lines.append(f" {v.description}")
if v.seller:
lines.append(f" Seller: {v.seller.seller_name} | Price: v.seller.price")
lines.append(f" Action: {v.recommended_action}")
lines.append("")
if result.action_plan:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📋 Action Plan",
"",
])
for action in result.action_plan:
lines.append(f"**[P{action['priority']}] {action['action']}**")
lines.append(f" {action['detail']}")
lines.append(f" Timeline: {action['timeline']}")
lines.append("")
return "\n".join(lines)
# ============================================================
# DemoData
# ============================================================
def get_demo_data():
"""GetDemoData"""
brand = BrandInfo(
brand_name="TechGadget",
trademark_number="US12345678",
brand_registry=True,
authorized_sellers=["A1B2C3D4E5F6G7"],
protected_asins=["B08XXXXXX1", "B08XXXXXX2"],
min_price=29.99,
)
listings = [
ListingInfo(
asin="B08XXXXXX1",
title="TechGadget Premium Wireless Charger",
brand_in_title=True,
price=29.99,
seller_count=3,
buy_box_seller="A1B2C3D4E5F6G7",
sellers=[
SellerInfo(
seller_id="A1B2C3D4E5F6G7",
seller_name="TechGadget Official",
price=29.99,
is_fba=True,
rating=4.8,
is_authorized=True,
),
SellerInfo(
seller_id="X9Y8Z7W6V5U4T3",
seller_name="CheapDeals123",
price=18.99,
is_fba=False,
rating=3.2,
is_authorized=False,
),
SellerInfo(
seller_id="M1N2O3P4Q5R6S7",
seller_name="BestPriceStore",
price=24.99,
is_fba=True,
rating=4.1,
is_authorized=False,
),
],
),
ListingInfo(
asin="B09YYYYYY1",
title="Compatible with TechGadget Wireless Charger Case",
brand_in_title=True,
price=9.99,
seller_count=1,
sellers=[
SellerInfo(
seller_id="K1L2M3N4O5P6Q7",
seller_name="AccessoryWorld",
price=9.99,
is_fba=True,
rating=4.0,
is_authorized=False,
),
],
),
]
reviews = {
"B08XXXXXX1": [
{"content": "Great product, works perfectly!", "rating": 5},
{"content": "Received a fake product, not genuine TechGadget", "rating": 1},
{"content": "This is counterfeit, poor quality", "rating": 1},
{"content": "Not authentic, different from picture", "rating": 2},
{"content": "Amazing charger, fast shipping", "rating": 5},
],
}
return brand, listings, reviews
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
# DemoMode
brand, listings, reviews = get_demo_data()
# ExecuteDetection
result = detect(brand, listings, reviews)
# OutputReport
print(format_report(result, lang))
if __name__ == "__main__":
main()
FILE:scripts/templates.py
#!/usr/bin/env python3
"""
Brand Protection Templates - Complaint & Legal Templates
Brand ProtectionTemplate - Complaint and legal document templates
Packagecontain:
- Brand Registry Complaint Templates
- Cease & Desist StopInfringementLetter
- Test Buy Operation guide
- MAP Violation notice
- LegalLetterTemplate
Version: 1.0.0
"""
from dataclasses import dataclass
from typing import Optional
from datetime import datetime
@dataclass
class ComplaintInfo:
"""ComplaintInformation"""
brand_name: str
trademark_number: Optional[str] = None
asin: str = ""
seller_name: str = ""
seller_id: str = ""
violation_type: str = ""
evidence: str = ""
contact_email: str = ""
company_name: str = ""
# ============================================================
# Complaint Templates
# ============================================================
def generate_brand_registry_complaint(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY COMPLAINT TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## Report Details
**Brand Name**: {info.brand_name}
**Trademark Number**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**Infringing Seller**: {info.seller_name} ({info.seller_id})
**Violation Type**: {info.violation_type}
---
## Complaint Text (Copy & Paste)
```
I am the brand owner of {info.brand_name} (Trademark #{info.trademark_number or "[YOUR TRADEMARK NUMBER]"}).
The seller "{info.seller_name}" (Seller ID: {info.seller_id}) is selling unauthorized/counterfeit products on ASIN {info.asin}.
Evidence:
{info.evidence or "[Describe your evidence here - screenshots, test buy results, etc.]"}
This seller is NOT an authorized reseller of our products. We request immediate removal of this seller from our listing.
Contact: {info.contact_email or "[YOUR EMAIL]"}
Company: {info.company_name or "[YOUR COMPANY NAME]"}
```
---
## Steps to Submit
1. Log into Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation"
3. Select violation type
4. Enter ASIN and seller information
5. Paste complaint text above
6. Upload evidence (screenshots, invoices, test buy photos)
7. Submit and note case ID
---
## Evidence Checklist
☐ Screenshots of listing showing unauthorized seller
☐ Invoice/order confirmation from test buy
☐ Photos comparing authentic vs suspected counterfeit
☐ Trademark registration certificate
☐ Authorization letter (showing seller is NOT authorized)
"""
def generate_cease_desist(info: ComplaintInfo) -> str:
"""GenerateStopInfringementLetterTemplate"""
today = datetime.now().strftime("%B %d, %Y")
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 CEASE AND DESIST LETTER TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**CEASE AND DESIST NOTICE**
To: {info.seller_name}
Seller ID: {info.seller_id}
Re: Unauthorized Sale of {info.brand_name} Products
---
Dear {info.seller_name},
This letter serves as formal notice that you are engaging in unauthorized sale of products bearing the {info.brand_name}® trademark (Registration No. {info.trademark_number or "[TRADEMARK NUMBER]"}) on Amazon.com, specifically on ASIN: {info.asin}.
**YOU ARE NOT AN AUTHORIZED RESELLER** of {info.brand_name} products. Your unauthorized sale of these products constitutes:
1. Trademark infringement under 15 U.S.C. § 1114
2. False designation of origin under 15 U.S.C. § 1125(a)
3. Violation of Amazon's Anti-Counterfeiting Policy
**DEMAND**
We hereby demand that you:
1. Immediately cease and desist all sales of {info.brand_name} products
2. Remove all {info.brand_name} product listings from your seller account
3. Provide a written confirmation of compliance within 5 business days
**CONSEQUENCES OF NON-COMPLIANCE**
Failure to comply with this demand will result in:
- Report to Amazon Brand Registry for listing removal
- Legal action seeking injunctive relief and monetary damages
- Report to law enforcement if counterfeit goods are involved
This letter is not intended to be a complete statement of the facts or law applicable to this matter, and nothing herein should be construed as a waiver of any rights or remedies.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
---
## Sending Instructions
1. Send via Amazon Buyer-Seller Messaging (if available)
2. Send via seller's contact email (find in storefront)
3. Keep copies of all correspondence
4. Set 5-day deadline for response
5. Escalate to legal action if no response
"""
def generate_test_buy_guide() -> str:
"""Generate Test Buy Operation guide"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY PROCEDURE GUIDE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## Purpose
Test Buy is the process of purchasing products from suspected counterfeit/unauthorized sellers to collect physical evidence for your complaint.
---
## Step-by-Step Process
### 1. Preparation
☐ Create a separate Amazon buyer account (not linked to seller account)
☐ Use a different shipping address if possible
☐ Prepare camera for documentation
☐ Have authentic product ready for comparison
### 2. Purchase
☐ Select the suspected seller's offer (not Buy Box)
☐ Screenshot the product page showing seller name and price
☐ Screenshot checkout page with seller info
☐ Complete purchase and save order confirmation
☐ Note Order ID: ________________
### 3. Documentation Upon Arrival
☐ Photograph unopened package (showing shipping label)
☐ Video record unboxing process
☐ Photograph product from multiple angles
☐ Compare with authentic product side-by-side:
- Packaging differences
- Label/printing quality
- Product quality/finish
- Weight comparison
- Serial number verification
☐ Keep all packaging materials
### 4. Evidence Organization
Create folder with:
```
test_buy_evidence/
├── 01_listing_screenshots/
├── 02_order_confirmation/
├── 03_package_photos/
├── 04_unboxing_video/
├── 05_product_comparison/
└── 06_notes.txt
```
### 5. Submit Complaint
☐ Compile all evidence
☐ Write detailed complaint (use template)
☐ Submit via Brand Registry
☐ Include Order ID in complaint
☐ Upload photos/video
---
## Evidence Checklist
**Screenshots**
☐ Listing page with seller
☐ Seller storefront
☐ Order confirmation
☐ Shipping confirmation
☐ Delivery confirmation
**Photos**
☐ Package exterior (4+ angles)
☐ Shipping label close-up
☐ Product in packaging
☐ Product removed
☐ Side-by-side with authentic
☐ Close-up of differences
**Documents**
☐ Invoice from test buy
☐ Authentication certificate (if available)
☐ Trademark registration
---
## Timeline
Day 1: Place order
Day 3-7: Receive package
Day 7-8: Document and compare
Day 8-10: Compile and submit complaint
Day 10-21: Amazon review period
---
## Cost Tracking
| Item | Cost |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| Return Shipping | $_____ |
| Total | $_____ |
*Note: May be recoverable in legal action*
"""
def generate_map_violation_notice(info: ComplaintInfo, violation_price: float, map_price: float) -> str:
"""Generate MAP Violation notice"""
today = datetime.now().strftime("%B %d, %Y")
discount = (map_price - violation_price) / map_price * 100
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 MAP VIOLATION NOTICE TEMPLATE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Date**: {today}
---
**MINIMUM ADVERTISED PRICE (MAP) VIOLATION NOTICE**
To: {info.seller_name}
Re: MAP Policy Violation - {info.brand_name}
---
Dear {info.seller_name},
This notice is to inform you that your current advertised price for {info.brand_name} products violates our Minimum Advertised Price (MAP) policy.
**Violation Details:**
| Product | ASIN | Your Price | MAP Price | Violation |
|---------|------|------------|-----------|-----------|
| {info.brand_name} | {info.asin} | .2f | .2f | -{discount:.1f}% |
**MAP Policy Terms:**
As an authorized/unauthorized reseller of {info.brand_name} products, you are required to maintain advertised prices at or above the Minimum Advertised Price. This policy ensures:
- Fair competition among resellers
- Brand value protection
- Quality customer experience
**Required Action:**
Please adjust your advertised price to .2f or higher within **48 hours** of receiving this notice.
**Consequences of Non-Compliance:**
Continued violation of our MAP policy may result in:
- Removal from authorized reseller program
- Report to Amazon for policy violation
- Supply chain restrictions
Please confirm compliance by replying to this notice.
Sincerely,
{info.company_name or "[YOUR COMPANY NAME]"}
{info.contact_email or "[YOUR EMAIL]"}
"""
# ============================================================
# in textTemplate
# ============================================================
def generate_brand_registry_complaint_zh(info: ComplaintInfo) -> str:
"""Generate Brand Registry Complaint Templates ( in text)"""
return f"""
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 BRAND REGISTRY Complaint Templates
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
**Platform**: Amazon Brand Registry Portal
**URL**: https://brandregistry.amazon.com/
---
## ComplaintInformation
**BrandName**: {info.brand_name}
**TrademarkRegisternumber**: {info.trademark_number or "N/A"}
**ASIN**: {info.asin}
**InfringementSeller**: {info.seller_name} ({info.seller_id})
**InfringementCategoryType**: {info.violation_type}
---
## ComplaintText (CopyPaste)
```
I is {info.brand_name} BrandOwner (TrademarkRegisternumber: {info.trademark_number or "[youTrademarknumber]"})。
Seller "{info.seller_name}" (Seller ID: {info.seller_id}) positive in ASIN {info.asin} Selling unauthorized on/CounterfeitProduct。
Evidence:
{info.evidence or "[Describe your evidence here - Screenshot、TestPurchaseResult etc]"}
should Sellernot is WeProductAuthorized distributor of。WeRequestImmediately will this Seller from We Listing in Remove。
Contact info: {info.contact_email or "[Your email]"}
CompanyName: {info.company_name or "[youCompanyname]"}
```
---
## SubmitStep
1. Login Brand Registry: https://brandregistry.amazon.com/
2. Click "Report a Violation" (ReportInfringement)
3. ChoiceInfringementCategoryType
4. Input ASIN AndSellerInformation
5. PasteAboveComplaintText
6. UploadEvidence (Screenshot、Invoice、Test Buy Photo)
7. SubmitandRecord Case ID
---
## EvidenceList
☐ Show notAuthorizedSeller Listing Screenshot
☐ Test Buy Invoice/OrderConfirm
☐ Authentic vs suspected counterfeitComparisonPhoto
☐ Trademark registration certificate
☐ Authorizedbook (Proof should SellerNot obtainedAuthorized)
"""
def generate_test_buy_guide_zh() -> str:
"""Generate Test Buy Operation guide ( in text)"""
return """
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 TEST BUY Operation guide
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
## item
Test Buy (TestPurchase) Is fromSuspiciousCounterfeit/notAuthorizedSeller at PurchaseProduct,Process of collecting physical evidence for complaint。
---
## Operation process
### 1. Preparation work
☐ CreateIndependent Amazon BuyerAccount (not need and SellerAccountAssociate)
☐ Use different deliveryAddress
☐ Prepare camera for recording
☐ Prepare authentic product forComparison
### 2. Purchase
☐ ChoiceSuspiciousSellerQuote (not need select Buy Box)
☐ ScreenshotProductPage,DisplaySellerNameAndPrice
☐ ScreenshotSettlementPage,PackagecontainSellerInformation
☐ CompletePurchaseandSaveOrderConfirm
☐ RecordOrdernumber: ________________
### 3. Receive after Record
☐ Photo of unopened package (Show shipping label)
☐ Video record unboxing process
☐ many angleDegreePhotoProduct
☐ and AuthenticSide by sideComparison:
- PackagingDifference
- Tag/Print quality
- ProductQuality/Workmanship
- heavy quantityComparison
- Serial number verification
☐ Keep all packaging materials
### 4. EvidenceOrganize
CreateFolder:
```
test_buy_Evidence/
├── 01_listingScreenshot/
├── 02_OrderConfirm/
├── 03_Package photo/
├── 04_UnboxingVideo/
├── 05_ProductComparison/
└── 06_Notes.txt
```
### 5. SubmitComplaint
☐ Organize all evidence
☐ Write detailed complaint (UseTemplate)
☐ Pass Brand Registry Submit
☐ Include in complaintOrdernumber
☐ Upload photo/Video
---
## Timeline
number 1 days: below single
number 3-7 days: Receive
number 7-8 days: RecordandComparison
number 8-10 days: Organize and submit complaint
number 10-21 days: Amazon ReviewPeriod
---
## CostTrack
| Itemitem | Fee |
|------|------|
| Test Buy Product | $_____ |
| Shipping | $_____ |
| ReturnShipping | $_____ |
| Total | $_____ |
*note: Can be recovered in legal proceedings*
"""
# ============================================================
# CLI
# ============================================================
def main():
import sys
# DemoData
info = ComplaintInfo(
brand_name="TechGadget",
trademark_number="US12345678",
asin="B08XXXXXX1",
seller_name="CheapDeals123",
seller_id="X9Y8Z7W6V5U4T3",
violation_type="Unauthorized Sale / Suspected Counterfeit",
evidence="Test buy received product with different packaging and lower quality than authentic product.",
contact_email="[email protected]",
company_name="TechGadget Inc.",
)
lang = "zh" if "--zh" in sys.argv else "en"
template_type = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "all"
if template_type == "complaint" or template_type == "all":
if lang == "zh":
print(generate_brand_registry_complaint_zh(info))
else:
print(generate_brand_registry_complaint(info))
if template_type == "cease" or template_type == "all":
print(generate_cease_desist(info))
if template_type == "testbuy" or template_type == "all":
if lang == "zh":
print(generate_test_buy_guide_zh())
else:
print(generate_test_buy_guide())
if template_type == "map" or template_type == "all":
print(generate_map_violation_notice(info, 18.99, 29.99))
if __name__ == "__main__":
main()
Brand monitoring tool for tracking mentions across social media platforms. Monitor Reddit, Google News, YouTube, and DuckDuckGo for brand mentions. Includes...
---
name: brand-monitoring
version: 1.0.0
author: Nexscope AI
description: "Brand monitoring tool for tracking mentions across social media platforms. Monitor Reddit, Google News, YouTube, and DuckDuckGo for brand mentions. Includes sentiment analysis, trend tracking, crisis detection, and competitor comparison. No API key required for basic monitoring."
metadata: {"nexscope":{"emoji":"📡","category":"ecommerce"}}
---
# Brand Monitoring 📡
Track brand mentions across social media platforms and analyze sentiment.
## Installation
```bash
npx skills add nexscope-ai/eCommerce-Skills --skill brand-monitoring -g
```
## Features
- **Mention Monitoring** — Track brand mentions across platforms
- **Sentiment Analysis** — Positive/negative/neutral classification
- **Trend Tracking** — Monitor mention volume changes
- **Crisis Detection** — Alerts for negative spikes or crisis keywords
- **Competitor Comparison** — Share of voice analysis
- **Keyword Extraction** — Identify trending topics
- **Report Generation** — Weekly/monthly reports
## Supported Platforms
| Platform | Method | Stability |
|----------|--------|-----------|
| Reddit | Public JSON API | ⚠️ Rate limited |
| Google News | RSS Feed | ✅ Stable |
| DuckDuckGo | Instant Answer API | ✅ Stable |
| YouTube | HTML/RSS | ⚠️ Unstable |
## Analysis Dimensions
| Dimension | Method | Output |
|-----------|--------|--------|
| Volume | Mention count | Trend graph |
| Sentiment | NLP analysis | Sentiment score |
| Sources | Platform breakdown | Source distribution |
| Keywords | Topic extraction | Word cloud |
| Competitors | Share of voice | Comparison chart |
## Usage
### Basic Monitoring
```bash
python3 scripts/monitor.py "YourBrand"
```
### With Competitors
```bash
python3 scripts/monitor.py '{
"brand": "YourBrand",
"competitors": ["CompA", "CompB"],
"platforms": ["reddit", "google_news"]
}'
```
### Demo Mode
```bash
python3 scripts/monitor.py --demo
```
## Output Example
```
📡 Brand Monitoring Report
Brand: YourBrand
Period: Last 7 days
Platforms: Reddit, Google News, YouTube
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 MENTION OVERVIEW
Total Mentions: 127
├── Reddit: 82 (65%)
├── Google News: 35 (28%)
└── YouTube: 10 (8%)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
😊 SENTIMENT ANALYSIS
Positive: 45% ████████░░
Neutral: 38% ███████░░░
Negative: 17% ███░░░░░░░
Overall Score: 7.2/10 ✅
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 TREND (7 days)
Mon ████████ 25
Tue ██████ 18
Wed ███████ 21
Thu █████████ 28
Fri ████████ 22
Sat ███ 8
Sun ██ 5
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔥 TRENDING KEYWORDS
1. quality (32x)
2. shipping (28x)
3. customer service (22x)
4. price (18x)
5. recommended (15x)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ ALERTS
🔴 Negative spike on Thursday (+40%)
Related to: shipping delays
Recommendation: Monitor and respond
```
## Crisis Detection
| Alert Level | Trigger | Action |
|-------------|---------|--------|
| 🟢 Normal | < 20% negative | Continue monitoring |
| 🟡 Warning | 20-40% negative | Investigate sources |
| 🔴 Crisis | > 40% negative | Immediate response needed |
## Monitoring Workflow
```
Set up brand keywords
↓
Monitor platforms
↓
Analyze sentiment
↓
Detect anomalies
↓
Generate alerts
↓
Weekly report
```
---
**Part of [Nexscope AI](https://www.nexscope.ai/) — AI tools for e-commerce sellers.**
FILE:scripts/monitor.py
#!/usr/bin/env python3
"""
Brand Monitoring - Core Engine
Brand Monitoring - Core Engine
Features:
- BrandMention Monitoring
- SentimentAnalyze (positive/negative/ in )
- TrendTrack
- Abnormal/Crisis Detection
- CompetitorVolumeComparison
- Keyword Extraction
- ReportGenerate
Datasource (Lite):
- Reddit (PublicSearch)
- Google ( new news/Blog)
- YouTube (Review)
- ManualInput
Version: 1.0.0
"""
import json
import re
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Tuple
from enum import Enum
from datetime import datetime, timedelta
from collections import Counter
import sys
class Sentiment(Enum):
"""SentimentCategoryType"""
POSITIVE = "positive"
NEGATIVE = "negative"
NEUTRAL = "neutral"
class Platform(Enum):
"""PlatformCategoryType"""
REDDIT = "reddit"
TWITTER = "twitter"
YOUTUBE = "youtube"
AMAZON = "amazon"
GOOGLE = "google"
TIKTOK = "tiktok"
FACEBOOK = "facebook"
FORUM = "forum"
NEWS = "news"
OTHER = "other"
class AlertLevel(Enum):
"""AlertLevelother"""
INFO = "info"
WARNING = "warning"
CRITICAL = "critical"
# ============================================================
# SentimentKeywordsLibrary
# ============================================================
POSITIVE_KEYWORDS = {
"en": [
"love", "great", "amazing", "awesome", "excellent", "perfect", "best",
"fantastic", "wonderful", "recommend", "happy", "satisfied", "quality",
"worth", "impressed", "reliable", "favorite", "brilliant", "superb"
],
"zh": [
"Like", " very good ", "great", "Excellent", "Perfect", " most good ", "Recommended", "Satisfied", "Quality good ",
"Value ", "Impressive", "Canrely", " most love", "Excellent"
]
}
NEGATIVE_KEYWORDS = {
"en": [
"hate", "terrible", "awful", "worst", "bad", "horrible", "disappointed",
"waste", "scam", "fake", "poor", "broken", "useless", "regret", "avoid",
"never", "refund", "complaint", "problem", "issue", "sucks"
],
"zh": [
"Hate", "Terrible", "difference", " most difference", " bad ", "Disappointed", "Waste", "Scammer", "Counterfeit",
"Poor", " bad ", "Useless", " after regret", "Avoid", "Refund", "Complaint", "Issue"
]
}
CRISIS_KEYWORDS = {
"en": [
"lawsuit", "recall", "investigation", "fraud", "scandal", "danger",
"safety", "warning", "banned", "illegal", "death", "injury", "toxic"
],
"zh": [
"Lawsuit", "Recall", "Investigation", "Fraud", "Scandal", "Danger", "safe all ", "Warning",
"Prohibited", "Illegal", "Death", "Harm", " has toxic"
]
}
# ============================================================
# Data Structures
# ============================================================
@dataclass
class Mention:
"""Brandmention and """
content: str
platform: Platform
url: str = ""
author: str = ""
date: Optional[datetime] = None
engagement: int = 0 # Interactivequantity (likes, comments, shares)
sentiment: Sentiment = Sentiment.NEUTRAL
sentiment_score: float = 0.0
keywords: List[str] = field(default_factory=list)
is_influential: bool = False
@dataclass
class BrandMetrics:
"""BrandMetrics"""
total_mentions: int = 0
positive_count: int = 0
negative_count: int = 0
neutral_count: int = 0
avg_sentiment_score: float = 0.0
total_engagement: int = 0
top_keywords: List[Tuple[str, int]] = field(default_factory=list)
platform_distribution: Dict[str, int] = field(default_factory=dict)
daily_trend: Dict[str, int] = field(default_factory=dict)
@dataclass
class Alert:
"""Alert"""
level: AlertLevel
title: str
title_zh: str
description: str
description_zh: str
trigger: str
timestamp: datetime = field(default_factory=datetime.now)
@dataclass
class CompetitorComparison:
"""CompetitorComparison"""
brand: str
metrics: BrandMetrics
share_of_voice: float = 0.0
@dataclass
class MonitoringReport:
"""MonitoringReport"""
brand_name: str
period_start: datetime
period_end: datetime
metrics: BrandMetrics
mentions: List[Mention]
alerts: List[Alert]
competitors: List[CompetitorComparison]
top_positive: List[Mention]
top_negative: List[Mention]
summary: str
summary_zh: str
# ============================================================
# SentimentAnalyze
# ============================================================
def analyze_sentiment(text: str, lang: str = "en") -> Tuple[Sentiment, float]:
"""AnalyzeTextSentiment"""
text_lower = text.lower()
positive_score = 0
negative_score = 0
# KeywordsMatch
for keyword in POSITIVE_KEYWORDS.get(lang, []) + POSITIVE_KEYWORDS.get("en", []):
if keyword.lower() in text_lower:
positive_score += 1
for keyword in NEGATIVE_KEYWORDS.get(lang, []) + NEGATIVE_KEYWORDS.get("en", []):
if keyword.lower() in text_lower:
negative_score += 1
# CalculateScore (-1 to +1)
total = positive_score + negative_score
if total == 0:
return Sentiment.NEUTRAL, 0.0
score = (positive_score - negative_score) / max(total, 1)
if score > 0.2:
sentiment = Sentiment.POSITIVE
elif score < -0.2:
sentiment = Sentiment.NEGATIVE
else:
sentiment = Sentiment.NEUTRAL
return sentiment, round(score, 2)
def extract_keywords(text: str, top_n: int = 5) -> List[str]:
"""ExtractKeywords"""
# SimpleWord frequencyStatistics
words = re.findall(r'\b[a-zA-Z]{4,}\b', text.lower())
# FilterStop words
stopwords = {"this", "that", "with", "have", "from", "they", "been", "were", "will", "would", "could", "should", "about", "their", "there", "which", "when", "what", "your", "just", "some", "more", "very", "really"}
words = [w for w in words if w not in stopwords]
counter = Counter(words)
return [word for word, count in counter.most_common(top_n)]
def detect_crisis(text: str) -> bool:
"""DetectionCrisisKeywords"""
text_lower = text.lower()
for keyword in CRISIS_KEYWORDS.get("en", []):
if keyword in text_lower:
return True
return False
# ============================================================
# DataCollect (Lite - Simulate/Demo)
# ============================================================
def search_reddit(brand_name: str, limit: int = 20) -> List[Mention]:
"""Search Reddit (Lite: SimulateData)"""
# In real implementation, this in will Use Reddit API or Crawler
# Lite versionUse pushshift.io or CategorySeemingly free service
print(f"[Reddit] Searching for: {brand_name}")
return []
def search_google_news(brand_name: str, limit: int = 20) -> List[Mention]:
"""Search Google News (Lite: SimulateData)"""
print(f"[Google News] Searching for: {brand_name}")
return []
def get_demo_mentions(brand_name: str) -> List[Mention]:
"""GetDemoData"""
now = datetime.now()
return [
Mention(
content=f"Just got my {brand_name} product and I absolutely love it! Best purchase this year.",
platform=Platform.REDDIT,
url="https://reddit.com/r/product/xxx",
author="happy_customer",
date=now - timedelta(hours=2),
engagement=150,
),
Mention(
content=f"Has anyone tried {brand_name}? Looking for honest reviews before buying.",
platform=Platform.REDDIT,
url="https://reddit.com/r/product/yyy",
author="curious_buyer",
date=now - timedelta(hours=5),
engagement=45,
),
Mention(
content=f"Disappointed with {brand_name} quality. The product broke after 2 weeks. Waste of money!",
platform=Platform.TWITTER,
url="https://twitter.com/user/status/xxx",
author="angry_buyer",
date=now - timedelta(hours=8),
engagement=320,
),
Mention(
content=f"Comparing {brand_name} vs competitors - honest review video coming soon!",
platform=Platform.YOUTUBE,
url="https://youtube.com/watch?v=xxx",
author="tech_reviewer",
date=now - timedelta(days=1),
engagement=5000,
),
Mention(
content=f"{brand_name} announces new product line with improved features",
platform=Platform.NEWS,
url="https://news.example.com/article",
author="TechNews",
date=now - timedelta(days=1),
engagement=200,
),
Mention(
content=f"I've been using {brand_name} for 6 months now. Highly recommend for anyone looking for quality.",
platform=Platform.REDDIT,
url="https://reddit.com/r/reviews/xxx",
author="long_time_user",
date=now - timedelta(days=2),
engagement=89,
),
Mention(
content=f"Warning: {brand_name} customer service is terrible. Been waiting 3 weeks for refund!",
platform=Platform.TWITTER,
url="https://twitter.com/user/status/yyy",
author="frustrated_customer",
date=now - timedelta(days=2),
engagement=180,
),
Mention(
content=f"Just saw {brand_name} at the store. The packaging looks premium!",
platform=Platform.TIKTOK,
url="https://tiktok.com/@user/video/xxx",
author="shopping_vlog",
date=now - timedelta(days=3),
engagement=2500,
),
]
# ============================================================
# CoreAnalyze
# ============================================================
def analyze_mentions(mentions: List[Mention]) -> Tuple[List[Mention], BrandMetrics]:
"""Analyzemention and Data"""
# SentimentAnalyze
for mention in mentions:
sentiment, score = analyze_sentiment(mention.content)
mention.sentiment = sentiment
mention.sentiment_score = score
mention.keywords = extract_keywords(mention.content)
mention.is_influential = mention.engagement > 1000
# CalculateMetrics
metrics = BrandMetrics()
metrics.total_mentions = len(mentions)
metrics.positive_count = len([m for m in mentions if m.sentiment == Sentiment.POSITIVE])
metrics.negative_count = len([m for m in mentions if m.sentiment == Sentiment.NEGATIVE])
metrics.neutral_count = len([m for m in mentions if m.sentiment == Sentiment.NEUTRAL])
if mentions:
metrics.avg_sentiment_score = round(sum(m.sentiment_score for m in mentions) / len(mentions), 2)
metrics.total_engagement = sum(m.engagement for m in mentions)
# PlatformDistribution
for mention in mentions:
platform = mention.platform.value
metrics.platform_distribution[platform] = metrics.platform_distribution.get(platform, 0) + 1
# KeywordsStatistics
all_keywords = []
for mention in mentions:
all_keywords.extend(mention.keywords)
metrics.top_keywords = Counter(all_keywords).most_common(10)
return mentions, metrics
def generate_alerts(mentions: List[Mention], metrics: BrandMetrics) -> List[Alert]:
"""GenerateAlert"""
alerts = []
# NegativeSentimentProportionAlert
if metrics.total_mentions > 0:
negative_ratio = metrics.negative_count / metrics.total_mentions
if negative_ratio > 0.4:
alerts.append(Alert(
level=AlertLevel.CRITICAL,
title="High Negative Sentiment",
title_zh="NegativeSentiment High",
description=f"Negative mentions at {negative_ratio*100:.1f}% - above 40% threshold",
description_zh=f"Negativemention and Proportion {negative_ratio*100:.1f}% - super 40% Threshold",
trigger=f"negative_ratio > 0.4",
))
elif negative_ratio > 0.3:
alerts.append(Alert(
level=AlertLevel.WARNING,
title="Elevated Negative Sentiment",
title_zh="NegativeEmotion riseHigh",
description=f"Negative mentions at {negative_ratio*100:.1f}% - above 30% threshold",
description_zh=f"Negativemention and Proportion {negative_ratio*100:.1f}% - super 30% Threshold",
trigger=f"negative_ratio > 0.3",
))
# HighImpactpowerNegativemention and
influential_negative = [m for m in mentions if m.is_influential and m.sentiment == Sentiment.NEGATIVE]
if influential_negative:
alerts.append(Alert(
level=AlertLevel.CRITICAL,
title="Influential Negative Mention",
title_zh="HighImpactpowerNegativemention and ",
description=f"Found {len(influential_negative)} negative mention(s) with high engagement",
description_zh=f"Found {len(influential_negative)} itemHighInteractivequantityNegativemention and ",
trigger="engagement > 1000 AND sentiment = negative",
))
# CrisisKeywordsDetection
crisis_mentions = [m for m in mentions if detect_crisis(m.content)]
if crisis_mentions:
alerts.append(Alert(
level=AlertLevel.CRITICAL,
title="Potential Crisis Detected",
title_zh="potential in Crisis Detection",
description=f"Found {len(crisis_mentions)} mention(s) with crisis keywords",
description_zh=f"Found {len(crisis_mentions)} Contains crisisKeywordsmention and ",
trigger="crisis_keywords detected",
))
return alerts
def monitor_brand(
brand_name: str,
competitors: List[str] = None,
mentions: List[Mention] = None,
) -> MonitoringReport:
"""Brand MonitoringMainFunction"""
now = datetime.now()
period_start = now - timedelta(days=7)
# GetData
if mentions is None:
mentions = get_demo_mentions(brand_name)
# Analyze
mentions, metrics = analyze_mentions(mentions)
# GenerateAlert
alerts = generate_alerts(mentions, metrics)
# CompetitorComparison
competitor_data = []
if competitors:
total_mentions = metrics.total_mentions
for comp in competitors:
comp_mentions = get_demo_mentions(comp)[:3] # Demo: few quantityData
_, comp_metrics = analyze_mentions(comp_mentions)
sov = comp_metrics.total_mentions / (total_mentions + comp_metrics.total_mentions) if total_mentions > 0 else 0
competitor_data.append(CompetitorComparison(
brand=comp,
metrics=comp_metrics,
share_of_voice=round(sov, 2),
))
# Top mention and
sorted_positive = sorted([m for m in mentions if m.sentiment == Sentiment.POSITIVE], key=lambda x: -x.engagement)
sorted_negative = sorted([m for m in mentions if m.sentiment == Sentiment.NEGATIVE], key=lambda x: -x.engagement)
# Summary
pos_pct = metrics.positive_count / metrics.total_mentions * 100 if metrics.total_mentions > 0 else 0
neg_pct = metrics.negative_count / metrics.total_mentions * 100 if metrics.total_mentions > 0 else 0
summary = f"📊 {metrics.total_mentions} mentions | 😊 {pos_pct:.0f}% positive | 😠 {neg_pct:.0f}% negative | ⚠️ {len(alerts)} alerts"
summary_zh = f"📊 {metrics.total_mentions} Item mention and | 😊 {pos_pct:.0f}% Positive | 😠 {neg_pct:.0f}% Negative | ⚠️ {len(alerts)} itemAlert"
return MonitoringReport(
brand_name=brand_name,
period_start=period_start,
period_end=now,
metrics=metrics,
mentions=mentions,
alerts=alerts,
competitors=competitor_data,
top_positive=sorted_positive[:3],
top_negative=sorted_negative[:3],
summary=summary,
summary_zh=summary_zh,
)
# ============================================================
# OutputFormat
# ============================================================
def format_report(report: MonitoringReport, lang: str = "en") -> str:
"""FormatReport"""
m = report.metrics
if lang == "zh":
lines = [
"📡 **Brand MonitoringReport**",
"",
f"**Brand**: {report.brand_name}",
f"**MonitoringweeksPeriod**: {report.period_start.strftime('%Y-%m-%d')} ~ {report.period_end.strftime('%Y-%m-%d')}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📊 OverallMetrics",
"",
f"| Metrics | Value |",
f"|------|------|",
f"| Total mention and | {m.total_mentions} |",
f"| Positivemention and | {m.positive_count} ({m.positive_count/m.total_mentions*100:.0f}%) |" if m.total_mentions > 0 else f"| Positivemention and | 0 |",
f"| Negativemention and | {m.negative_count} ({m.negative_count/m.total_mentions*100:.0f}%) |" if m.total_mentions > 0 else f"| Negativemention and | 0 |",
f"| Neutralmention and | {m.neutral_count} |",
f"| AverageSentiment score | {m.avg_sentiment_score} |",
f"| Total engagement | {m.total_engagement:,} |",
"",
]
# Alert
if report.alerts:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## ⚠️ Alert",
"",
])
for alert in report.alerts:
level_icon = "🚨" if alert.level == AlertLevel.CRITICAL else "⚠️" if alert.level == AlertLevel.WARNING else "ℹ️"
lines.append(f"**{level_icon} {alert.title_zh}**")
lines.append(f" {alert.description_zh}")
lines.append("")
# PlatformDistribution
if m.platform_distribution:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📱 PlatformDistribution",
"",
])
for platform, count in sorted(m.platform_distribution.items(), key=lambda x: -x[1]):
pct = count / m.total_mentions * 100 if m.total_mentions > 0 else 0
lines.append(f"- **{platform}**: {count} ({pct:.0f}%)")
lines.append("")
# PopularKeywords
if m.top_keywords:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 🔑 PopularKeywords",
"",
", ".join([f"`{word}` ({count})" for word, count in m.top_keywords[:8]]),
"",
])
# Top Positivemention and
if report.top_positive:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 😊 PopularPositivemention and ",
"",
])
for i, mention in enumerate(report.top_positive[:3], 1):
lines.append(f"**{i}. [{mention.platform.value}]** Interactive: {mention.engagement:,}")
lines.append(f" \"{mention.content[:80]}...\"")
lines.append("")
# Top Negativemention and
if report.top_negative:
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 😠 need AttentionNegativemention and ",
"",
])
for i, mention in enumerate(report.top_negative[:3], 1):
lines.append(f"**{i}. [{mention.platform.value}]** Interactive: {mention.engagement:,}")
lines.append(f" \"{mention.content[:80]}...\"")
lines.append("")
lines.extend([
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
report.summary_zh,
])
else:
# English version
lines = [
"📡 **Brand Monitoring Report**",
"",
f"**Brand**: {report.brand_name}",
f"**Period**: {report.period_start.strftime('%Y-%m-%d')} ~ {report.period_end.strftime('%Y-%m-%d')}",
"",
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
"",
"## 📊 Overview Metrics",
"",
f"| Metric | Value |",
f"|--------|-------|",
f"| Total Mentions | {m.total_mentions} |",
f"| Positive | {m.positive_count} ({m.positive_count/m.total_mentions*100:.0f}%) |" if m.total_mentions > 0 else "| Positive | 0 |",
f"| Negative | {m.negative_count} ({m.negative_count/m.total_mentions*100:.0f}%) |" if m.total_mentions > 0 else "| Negative | 0 |",
f"| Neutral | {m.neutral_count} |",
f"| Avg Sentiment | {m.avg_sentiment_score} |",
f"| Total Engagement | {m.total_engagement:,} |",
"",
]
if report.alerts:
lines.extend(["## ⚠️ Alerts", ""])
for alert in report.alerts:
level_icon = "🚨" if alert.level == AlertLevel.CRITICAL else "⚠️"
lines.append(f"**{level_icon} {alert.title}**: {alert.description}")
lines.append("")
if m.platform_distribution:
lines.extend(["## 📱 Platform Distribution", ""])
for platform, count in sorted(m.platform_distribution.items(), key=lambda x: -x[1]):
lines.append(f"- **{platform}**: {count}")
lines.append("")
lines.extend(["", report.summary])
return "\n".join(lines)
# ============================================================
# CLI
# ============================================================
def main():
lang = "zh" if "--zh" in sys.argv else "en"
brand = sys.argv[1] if len(sys.argv) > 1 and not sys.argv[1].startswith("--") else "TechBrand"
report = monitor_brand(brand, competitors=["CompetitorA", "CompetitorB"])
print(format_report(report, lang))
if __name__ == "__main__":
main()
FILE:scripts/scrapers.py
#!/usr/bin/env python3
"""
Brand Monitoring - Data Scrapers (Lite)
Brand Monitoring - DataCollect (Free version)
Datasource:
- Reddit (PublicSearch/Pushshift)
- Google News (RSS)
- YouTube (PublicSearch)
- DuckDuckGo (Search)
Note: Please comply withPlatformUseTerms
Version: 1.0.0
"""
import json
import re
import urllib.request
import urllib.parse
from typing import List, Dict, Optional
from dataclasses import dataclass
from datetime import datetime
import time
import sys
@dataclass
class SearchResult:
"""SearchResult"""
title: str
content: str
url: str
source: str
date: Optional[str] = None
author: Optional[str] = None
engagement: int = 0
class RedditScraper:
"""Reddit Search (UsePublic JSON Interface)"""
BASE_URL = "https://www.reddit.com"
def search(self, query: str, limit: int = 25, sort: str = "relevance") -> List[SearchResult]:
"""Search Reddit"""
results = []
try:
# Use Reddit Public JSON Interface
encoded_query = urllib.parse.quote(query)
url = f"{self.BASE_URL}/search.json?q={encoded_query}&limit={limit}&sort={sort}"
req = urllib.request.Request(url, headers={
"User-Agent": "Mozilla/5.0 (compatible; BrandMonitor/1.0)"
})
print(f"[Reddit] Searching: {query}")
# Note:ActualUseNeedProcess rate limiting
# with urllib.request.urlopen(req, timeout=10) as response:
# data = json.loads(response.read().decode())
# for post in data.get("data", {}).get("children", []):
# post_data = post.get("data", {})
# results.append(SearchResult(
# title=post_data.get("title", ""),
# content=post_data.get("selftext", "")[:500],
# url=f"https://reddit.com{post_data.get('permalink', '')}",
# source="reddit",
# author=post_data.get("author", ""),
# engagement=post_data.get("score", 0) + post_data.get("num_comments", 0),
# ))
print(f"[Reddit] Note: Enable actual API call in production")
except Exception as e:
print(f"[Reddit] Error: {e}")
return results
class GoogleNewsScraper:
"""Google News Search (Use RSS)"""
RSS_URL = "https://news.google.com/rss/search"
def search(self, query: str, limit: int = 20) -> List[SearchResult]:
"""Search Google News"""
results = []
try:
encoded_query = urllib.parse.quote(query)
url = f"{self.RSS_URL}?q={encoded_query}&hl=en-US&gl=US&ceid=US:en"
req = urllib.request.Request(url, headers={
"User-Agent": "Mozilla/5.0 (compatible; BrandMonitor/1.0)"
})
print(f"[Google News] Searching: {query}")
# Note:Actual implementation requiresParse RSS XML
# with urllib.request.urlopen(req, timeout=10) as response:
# # Parse RSS XML
# pass
print(f"[Google News] Note: Enable actual RSS parsing in production")
except Exception as e:
print(f"[Google News] Error: {e}")
return results
class DuckDuckGoScraper:
"""DuckDuckGo Search (Free,no API key)"""
# DuckDuckGo Instant Answer API
API_URL = "https://api.duckduckgo.com/"
def search(self, query: str) -> List[SearchResult]:
"""Search DuckDuckGo"""
results = []
try:
params = urllib.parse.urlencode({
"q": query,
"format": "json",
"no_html": 1,
})
url = f"{self.API_URL}?{params}"
req = urllib.request.Request(url, headers={
"User-Agent": "Mozilla/5.0 (compatible; BrandMonitor/1.0)"
})
print(f"[DuckDuckGo] Searching: {query}")
# with urllib.request.urlopen(req, timeout=10) as response:
# data = json.loads(response.read().decode())
# # ParseResult
print(f"[DuckDuckGo] Note: Enable actual API call in production")
except Exception as e:
print(f"[DuckDuckGo] Error: {e}")
return results
class YouTubeScraper:
"""YouTube Search (no API key PublicSearch)"""
SEARCH_URL = "https://www.youtube.com/results"
def search(self, query: str, limit: int = 20) -> List[SearchResult]:
"""Search YouTube (NeedParse HTML or Use API)"""
results = []
print(f"[YouTube] Searching: {query}")
print(f"[YouTube] Note: Use YouTube Data API v3 for production")
return results
class TwitterScraper:
"""Twitter/X Search (Need API v2)"""
def search(self, query: str, limit: int = 100) -> List[SearchResult]:
"""Search Twitter (Need Bearer Token)"""
results = []
print(f"[Twitter] Searching: {query}")
print(f"[Twitter] Note: Requires Twitter API v2 Bearer Token for production")
return results
# ============================================================
# UnifiedSearchInterface
# ============================================================
class BrandSearcher:
"""BrandSearchUnified interface"""
def __init__(self):
self.reddit = RedditScraper()
self.google_news = GoogleNewsScraper()
self.duckduckgo = DuckDuckGoScraper()
self.youtube = YouTubeScraper()
self.twitter = TwitterScraper()
def search_all(
self,
brand_name: str,
platforms: List[str] = None,
limit_per_platform: int = 20
) -> Dict[str, List[SearchResult]]:
"""Searchplace has Platform"""
if platforms is None:
platforms = ["reddit", "google_news", "duckduckgo"]
results = {}
for platform in platforms:
time.sleep(1) # Avoid rate limiting
if platform == "reddit":
results["reddit"] = self.reddit.search(brand_name, limit_per_platform)
elif platform == "google_news":
results["google_news"] = self.google_news.search(brand_name, limit_per_platform)
elif platform == "duckduckgo":
results["duckduckgo"] = self.duckduckgo.search(brand_name)
elif platform == "youtube":
results["youtube"] = self.youtube.search(brand_name, limit_per_platform)
elif platform == "twitter":
results["twitter"] = self.twitter.search(brand_name, limit_per_platform)
return results
def get_total_results(self, results: Dict[str, List[SearchResult]]) -> List[SearchResult]:
"""Merge allResult"""
all_results = []
for platform_results in results.values():
all_results.extend(platform_results)
return all_results
# ============================================================
# CLI
# ============================================================
def main():
brand = sys.argv[1] if len(sys.argv) > 1 else "TechBrand"
searcher = BrandSearcher()
print(f"\n🔍 Searching for brand: {brand}\n")
print("=" * 50)
results = searcher.search_all(brand)
total = sum(len(r) for r in results.values())
print(f"\n📊 Total results: {total}")
for platform, platform_results in results.items():
print(f" - {platform}: {len(platform_results)}")
print("\n⚠️ Note: Enable actual API calls in scrapers.py for production use")
print(" Current implementation is in demo mode.")
if __name__ == "__main__":
main()
Amazon keyword research and market opportunity analysis for sellers. Retrieve autocomplete suggestions (long-tail keywords), analyze competitor landscape, an...
---
name: amazon-keyword-research
description: "Amazon keyword research and market opportunity analysis for sellers. Retrieve autocomplete suggestions (long-tail keywords), analyze competitor landscape, and assess market opportunity for any keyword on 12 Amazon marketplaces (US/UK/DE/FR/IT/ES/JP/CA/AU/IN/MX/BR). No API key required. Make sure to use this skill whenever the user mentions Amazon product research, finding products to sell on Amazon, Amazon keyword ideas, niche analysis, competition analysis for Amazon, market opportunity on Amazon, comparing Amazon keywords, evaluating whether a product is worth selling, Amazon autocomplete data, seasonal demand for Amazon products, or anything related to researching what to sell on Amazon — even if they don't explicitly say 'keyword research'. Also trigger when the user asks vague questions like 'is this a good product to sell?', 'what's the competition like for X on Amazon?', 'should I sell X or Y?', or 'what are people searching for on Amazon?'."
metadata: {"clawdbot":{"emoji":"🔍"}}
---
# Amazon Keyword Research 🔍
Free keyword research for Amazon sellers. No API key — works out of the box.
## Installation
```bash
npx skills add nexscope-ai/Amazon-Skills --skill amazon-keyword-research -g
```
## Capabilities
- **Long-tail keyword mining**: Extract 100-200 real search terms from Amazon's autocomplete engine
- **Competitor landscape analysis**: Product count, price range, average rating, review distribution, top brands
- **Seasonal trend detection**: 12-month Google Trends data to identify peak seasons and demand shifts
- **Market opportunity scoring**: 1-10 score combining competition density, price room, and demand signals
- **Multi-marketplace support**: US, UK, DE, FR, IT, ES, JP, CA, AU, IN, MX, BR
- **Keyword comparison**: Side-by-side analysis of multiple keywords
## Usage Examples
Users can ask naturally. Examples:
```
Research the keyword "portable blender" on Amazon US
```
```
Find long-tail keywords for "yoga mat" on Amazon
```
```
I want to sell resistance bands. What does the Amazon keyword landscape look like?
```
```
Compare "laptop stand" vs "monitor stand" on Amazon US — which has more opportunity?
```
```
Analyze "Küchenmesser" on Amazon Germany
```
```
Research "water bottle" across Amazon US, UK, and DE
```
## Workflow
### Step 1: Gather Autocomplete Data
Run the bundled script to collect Amazon autocomplete suggestions:
```bash
<skill>/scripts/research.sh "<keyword>" [marketplace]
```
**Parameters:**
- `keyword` (required): The seed keyword to research
- `marketplace` (optional): `us` (default), `uk`, `de`, `fr`, `it`, `es`, `jp`, `ca`, `au`, `in`, `mx`, `br`
**What the script does:**
- Queries Amazon's autocomplete API with the seed keyword
- Expands with prefixes: "best [keyword]", "cheap [keyword]", "top [keyword]"
- Expands with a-z suffixes: "[keyword] a", "[keyword] b", ... "[keyword] z"
- Returns deduplicated, sorted list of real search suggestions — one per line
**Why this matters:** Amazon autocomplete reflects what real shoppers are actually typing. These aren't guesses — they're demand signals directly from Amazon's search engine. The prefix and alphabet expansion catches long-tail terms that basic autocomplete misses, which are often lower competition and higher intent.
Example:
```bash
<skill>/scripts/research.sh "portable blender" us
# Returns 100-200 long-tail keywords
```
For multi-marketplace research, run the script once per marketplace.
### Step 2: Analyze Competition
Use `web_search` to gather competitor intelligence:
1. Search `"<keyword>" site:amazon.com` — note approximate result count for competition density
2. Search `"<keyword>" amazon best sellers price review` — extract price patterns, rating averages, dominant brands
3. Summarize: total competitors, price range (min/avg/max), average star rating, top 5 brands by visibility
**Why this matters:** Raw keyword volume means nothing without competition context. A keyword with 10,000 searches but dominated by 3 entrenched brands with 10,000+ reviews each is a very different opportunity than one with the same volume but fragmented sellers. The price range reveals margin potential — if everything is under $10, margins will be razor-thin after FBA fees.
### Step 3: Check Seasonality
Use `web_fetch` on Google Trends:
```
https://trends.google.com/trends/explore?q=<keyword>&geo=US
```
If Google Trends returns a 429 error, fall back to `web_search` for seasonal data:
```
"<keyword>" seasonal trends demand peak months
```
Identify: trend direction (rising/declining/stable), seasonal peaks (which months), year-over-year change.
**Why this matters:** Seasonality determines cash flow risk. A product that sells 80% of its volume in Q4 means you need capital for inventory months in advance and may sit on dead stock the rest of the year. Rising trends mean growing demand and more room for new entrants; declining trends mean you're fighting over a shrinking pie. This context turns a keyword from a number into a business decision.
### Step 4: Synthesize Report
Combine all data into the output format below.
**Why structure matters:** Grouping keywords by intent (commercial vs informational vs niche) helps the seller understand not just what people search, but why they search it. The opportunity score condenses multiple signals into a single actionable number, but the breakdown behind it is what actually informs the decision — so always show the reasoning.
## Output Format
Present the final report in this structure:
```
## Keyword Research Report: [keyword]
**Marketplace:** Amazon [US/UK/DE/...]
**Date:** [current date]
### 1. Long-tail Keywords ([count] found)
**High Commercial Intent:**
- [keyword with "buy", "best", "vs", "for" etc.]
- ...
**Informational / Research:**
- [keyword with "how to", "what is", "review" etc.]
- ...
**Niche / Specific:**
- [long, specific keywords indicating clear purchase intent]
- ...
### 2. Competition Landscape
| Metric | Value |
|--------|-------|
| Estimated competitors | [number] |
| Price range | $[min] - $[max] |
| Average price | $[avg] |
| Average rating | [stars] |
| Top brands | [brand1, brand2, brand3...] |
### 3. Seasonal Trends
[Describe 12-month trend: peaks, valleys, stable periods]
[Note any upcoming peak seasons relevant to the keyword]
### 4. Market Opportunity Score: [X/10]
**Score breakdown:**
- Competition density: [low/medium/high] — [why]
- Price room: [low/medium/high] — [why]
- Demand trend: [growing/stable/declining] — [why]
- Niche potential: [low/medium/high] — [why]
**Recommendation:** [1-2 sentence actionable recommendation]
```
## Multi-Keyword Comparison
When the user asks to compare two or more keywords, run the full workflow (Steps 1-4) for each keyword separately, then present results in a side-by-side comparison table.
**Example user input:**
```
Compare "laptop stand" vs "monitor stand" vs "tablet stand" on Amazon US — which one should I sell?
```
**How to execute:** Run the script 3 times:
```bash
<skill>/scripts/research.sh "laptop stand" us
<skill>/scripts/research.sh "monitor stand" us
<skill>/scripts/research.sh "tablet stand" us
```
Then complete Steps 2-3 for each keyword, and output a comparison table:
| Metric | laptop stand | monitor stand | tablet stand |
|--------|-------------|---------------|-------------|
| Long-tail count | — | — | — |
| Avg price | — | — | — |
| Top brand dominance | — | — | — |
| Trend direction | — | — | — |
| Opportunity score | — | — | — |
End with a **Recommendation** stating which keyword has the best opportunity and why.
## Limitations
This skill uses publicly available data (Amazon autocomplete + web search). It does not provide exact monthly search volumes or sales estimates. For precise data, stay tuned for **[Nexscope](https://github.com/nexscope-ai)** — coming soon.
---
**Part of the [Nexscope](https://github.com/nexscope-ai) suite — AI-powered Amazon seller tools.**
FILE:_meta.json
{
"ownerId": "nexscope-ai",
"slug": "amazon-keyword-research",
"version": "1.0.0",
"publishedAt": null
}
FILE:scripts/research.sh
#!/bin/bash
# Amazon Keyword Research - Data Gathering Script
# Fetches Amazon autocomplete suggestions for a given keyword
# Usage: research.sh <keyword> [marketplace]
# Marketplace: us (default), uk, de, fr, it, es, jp, ca, au, in, mx, br
KEYWORD="?Usage: research.sh <keyword> [marketplace]"
MARKETPLACE="-us"
# Map marketplace to Amazon domain and market ID
case "$MARKETPLACE" in
us) DOMAIN="amazon.com"; MKT="ATVPDKIKX0DER" ;;
uk) DOMAIN="amazon.co.uk"; MKT="A1F83G8C2ARO7P" ;;
de) DOMAIN="amazon.de"; MKT="A1PA6795UKMFR9" ;;
fr) DOMAIN="amazon.fr"; MKT="A13V1IB3VIYZZH" ;;
it) DOMAIN="amazon.it"; MKT="APJ6JRA9NG5V4" ;;
es) DOMAIN="amazon.es"; MKT="A1RKKUPIHCS9HS" ;;
jp) DOMAIN="amazon.co.jp"; MKT="A1VC38T7YXB528" ;;
ca) DOMAIN="amazon.ca"; MKT="A2EUQ1WTGCTBG2" ;;
au) DOMAIN="amazon.com.au"; MKT="A39IBJ37TRP1C6" ;;
in) DOMAIN="amazon.in"; MKT="A21TJRUUN4KGV" ;;
mx) DOMAIN="amazon.com.mx"; MKT="A1AM78C64UM0Y8" ;;
br) DOMAIN="amazon.com.br"; MKT="A2Q3Y263D00KWC" ;;
*) echo "Unknown marketplace: $MARKETPLACE"; exit 1 ;;
esac
echo "=== Amazon Keyword Research ==="
echo "Keyword: $KEYWORD"
echo "Marketplace: $MARKETPLACE ($DOMAIN)"
echo ""
# 1. Fetch Amazon Autocomplete Suggestions
echo "--- Amazon Autocomplete Suggestions ---"
# Amazon's completion API returns search suggestions
ENCODED_KW=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$KEYWORD'))")
# Fetch autocomplete with different prefixes for more suggestions
for prefix in "" "best " "cheap " "top "; do
SEARCH_TERM="prefixKEYWORD"
ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('SEARCH_TERM'))")
RESULT=$(curl -s "https://completion.DOMAIN/api/2017/suggestions?mid=MKT&alias=aps&prefix=ENCODED" 2>/dev/null)
if [ -n "$RESULT" ]; then
echo "$RESULT" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
suggestions = data.get('suggestions', [])
for s in suggestions:
print(s.get('value', ''))
except:
pass
" 2>/dev/null
fi
done | sort -u
echo ""
echo "--- Alphabet Expansion ---"
# Expand with a-z suffixes for more long-tail keywords
for letter in a b c d e f g h i j k l m n o p q r s t u v w x y z; do
SEARCH_TERM="KEYWORD letter"
ENCODED=$(python3 -c "import urllib.parse; print(urllib.parse.quote('SEARCH_TERM'))")
RESULT=$(curl -s "https://completion.DOMAIN/api/2017/suggestions?mid=MKT&alias=aps&prefix=ENCODED" 2>/dev/null)
if [ -n "$RESULT" ]; then
echo "$RESULT" | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
suggestions = data.get('suggestions', [])
for s in suggestions:
print(s.get('value', ''))
except:
pass
" 2>/dev/null
fi
done | sort -u
echo ""
echo "=== Data collection complete ==="
Amazon listing builder and optimizer for sellers. Two modes: (A) Create — build keyword-optimized listings from scratch using keyword lists + product charact...
---
name: amazon-listing-optimization
description: "Amazon listing builder and optimizer for sellers. Two modes: (A) Create — build keyword-optimized listings from scratch using keyword lists + product characteristics + AI copywriting, (B) Optimize — audit existing listings, find keyword gaps, score across 8 dimensions, and rewrite with missing keywords. Integrates with amazon-keyword-research for keyword input. Works on 12 Amazon marketplaces. No API key required. Use when: (1) creating a new Amazon listing from keywords, (2) auditing an existing listing for SEO and conversion, (3) checking keyword coverage in title/bullets/description, (4) generating listing copy with target keywords and tone, (5) comparing listings against competitors, (6) preparing a listing for launch or relaunch."
metadata: {"clawdbot":{"emoji":"📝"}}
---
# Amazon Listing Optimization 📝
Build keyword-optimized listings from scratch, or audit and optimize existing ones. No API key — works out of the box.
## Installation
```bash
npx skills add nexscope-ai/Amazon-Skills --skill amazon-listing-optimization -g
```
## Two Modes
| Mode | When to Use | Input | Output |
|------|-------------|-------|--------|
| **A — Create** | Building a new listing | Keywords and/or competitor ASINs + product info + tone | Full listing copy + keyword coverage score |
| **B — Optimize** | Improving an existing listing | Your ASIN or URL (+ optional keywords or competitor ASINs) | Optimized listing copy + audit report + gap analysis |
## Mode A — Three Ways to Start
| Input Source | How it Works |
|-------------|-------------|
| **Keywords** | User provides keyword list → skill prioritizes and generates listing |
| **Competitor ASINs** | User provides 1-3 competitor ASINs → skill fetches their listings, extracts their keywords, then generates a listing that covers all their keywords and more |
| **Both** | User provides keywords + competitor ASINs → skill merges both sources for maximum coverage |
## Capabilities
- **Keyword-driven listing generation**: Import keywords (from amazon-keyword-research, manual list, or extracted from competitor ASINs), rank by priority, generate copy that maximizes keyword coverage
- **Competitor keyword extraction**: Fetch competitor listings and automatically extract their title/bullet keywords as your baseline
- **8-dimension audit & scoring**: Title, bullets, description, images, A+ content, pricing, reviews, SEO coverage
- **Keyword coverage tracking**: Visual map showing which keywords appear in title / bullets / description / missing
- **Tone selection**: Professional, Friendly, Urgent, Luxury — affects AI copywriting style
- **Competitive benchmarking**: Compare your listing against competitors
- **Multi-marketplace**: US, UK, DE, FR, IT, ES, JP, CA, AU, IN, MX, BR
## Usage Examples
### Mode A — Create from Keywords
```
Create a listing for a portable blender. Keywords: portable blender, smoothie maker, USB rechargeable, travel blender, personal blender. Material: BPA-free Tritan. Color: White. Capacity: 380ml. Tone: Friendly.
```
```
I have these keywords from my research: [paste keyword list]. Product: silicone kitchen utensil set, 12 pieces, heat resistant to 480°F. Generate a full listing.
```
### Mode A — Create from Competitor ASINs
```
I want to sell a dog t-shirt on Amazon US. Here are 3 competitors I want to beat: B0D72TSM62, B0ABC12345, B0XYZ67890. My product is 100% cotton, 6 colors, XS-XL, funny print. Analyze their listings and create one that's better. Friendly tone.
```
```
Create a listing for my yoga mat. Look at this competitor: B09V3KXJPB. Extract their keywords, find what they're missing, and build a listing that covers more keywords than them. Product: 6mm TPE, non-slip, carrying strap included. Tone: Professional.
```
### Mode A — Create from Keywords + Competitor ASINs
```
Use amazon-keyword-research to find keywords for "portable blender", also analyze these competitors: B0CPY1GFVZ, B0CXLF3Y19. Combine all keywords and create a listing. Product: 380ml, USB-C, BPA-free Tritan. Tone: Professional.
```
### Mode B — Optimize Existing
```
Audit the listing for ASIN B0D72TSM62 on Amazon US
```
```
Optimize B0D72TSM62 using these keywords: dog shirt, pet clothes, puppy clothing — show me what's missing and rewrite
```
```
Optimize my listing B0D72TSM62 by analyzing these competitors: B0ABC12345, B0XYZ67890. Find what keywords they have that I don't, and rewrite my listing to beat them.
```
---
## Mode A Workflow — Create Listing from Keywords
### Step A1: Collect Keywords
Keywords can come from four sources (use one or combine multiple):
1. **From [amazon-keyword-research](https://github.com/nexscope-ai/Amazon-Skills/tree/main/amazon-keyword-research) skill** (recommended): Run keyword research first, then feed results directly. Install: `npx skills add nexscope-ai/Amazon-Skills --skill amazon-keyword-research -g`
2. **From competitor ASINs**: User provides 1-3 competitor ASINs → run `<skill>/scripts/fetch-listing.sh` on each → extract keywords from their titles, bullets, and descriptions → use as your keyword baseline. This is the fastest way to start — you inherit what's already working for competitors, then add more.
3. **From user's keyword list**: User pastes their own keyword list (e.g. from Helium 10 Cerebro, Jungle Scout, or manual research)
4. **Auto-discover**: Use `web_search` to find top keywords for the product category
When competitor ASINs are provided, always fetch and analyze them first. Extract every meaningful keyword from their titles and bullets, then merge with any user-provided keywords. The goal: cover everything competitors cover, plus keywords they missed.
### Step A2: Prioritize Keywords
Organize keywords into tiers:
```
🔴 Primary (must appear in Title):
- [keyword] — [search volume if known]
- [keyword] — [search volume if known]
🟡 Secondary (must appear in Bullets):
- [keyword]
- [keyword]
🟢 Tertiary (should appear in Description or Backend):
- [keyword]
- [keyword]
⚪ Long-tail (use where natural):
- [keyword phrase]
- [keyword phrase]
```
Priority rules:
- Highest search volume → Title (front-loaded)
- Medium volume + high relevance → Bullets (one primary keyword per bullet)
- Lower volume / long-tail → Description
- Remaining → Backend search terms (advise seller to add in Seller Central)
### Step A3: Collect Product Characteristics
Ask or extract from user input:
- **Product name / type**
- **Brand name**
- **Key attributes**: Material, color, size, weight, capacity, quantity
- **Key features**: What makes it different (3-5 features)
- **Target audience**: Who buys this?
- **Use cases**: Top 3 scenarios
- **What's in the box**: Everything included
### Step A4: Select Tone
| Tone | Style | Best for |
|------|-------|----------|
| **Professional** | Authoritative, spec-focused, trust-building | Electronics, tools, B2B |
| **Friendly** | Conversational, benefit-focused, relatable | Kitchen, lifestyle, gifts |
| **Urgent** | Scarcity-driven, action words, problem-solving | Health, safety, seasonal |
| **Luxury** | Premium, sensory language, exclusivity | Beauty, fashion, premium goods |
Default: **Professional** if not specified.
### Step A5: Generate Listing Copy
Generate each component following these rules:
**Title (max 200 characters):**
- Format: `[Brand] + [Primary Keyword] + [Key Attribute 1] + [Key Attribute 2] + [Secondary Keyword] + [Differentiator]`
- Primary keyword as close to the front as possible (after brand)
- No ALL CAPS except brand name
- No promotional claims ("best", "#1", "top rated")
- Include size/color/quantity if relevant to search
**Bullet Points (5 bullets, max 500 chars each):**
- Each bullet: `[BENEFIT HEADER IN CAPS] — [Benefit explanation with keyword naturally embedded]`
- Bullet 1: Primary feature + primary keyword
- Bullet 2: Key use case + secondary keyword
- Bullet 3: Quality/material + trust signal
- Bullet 4: What's included / compatibility
- Bullet 5: Guarantee / differentiator / social proof hint
- Each bullet should contain at least 1 target keyword
**Description (max 2000 characters):**
- Opening: Problem/pain point the product solves
- Middle: Features → benefits (expand on bullets, don't repeat verbatim)
- Close: Call to action + what's in the box
- Embed remaining keywords not used in title/bullets
- Use line breaks for readability
### Step A6: Keyword Coverage Score
After generating, produce a coverage map:
```
## Keyword Coverage Report
| Keyword | Volume | In Title? | In Bullets? | In Description? | Status |
|---------|--------|-----------|-------------|-----------------|--------|
| portable blender | 45,000 | ✅ | ✅ | ✅ | 🟢 Covered |
| smoothie maker | 22,000 | ❌ | ✅ | ✅ | 🟡 Add to title |
| USB rechargeable | 18,000 | ✅ | ✅ | ❌ | 🟢 Covered |
| travel blender | 12,000 | ❌ | ❌ | ✅ | 🟡 Add to bullets |
| mini blender | 8,000 | ❌ | ❌ | ❌ | 🔴 Missing |
Coverage: 18/22 keywords (82%)
Title keywords: 6/8 slots used
Bullet keywords: 12/15 target keywords covered
Uncovered → recommend for Backend Search Terms
```
**Scoring:**
- 🟢 90%+ coverage = Excellent
- 🟡 70-89% = Good, minor gaps
- 🔴 <70% = Needs work, significant keywords missing
---
## Mode B Workflow — Optimize Existing Listing
### Step B1: Fetch Listing Data
Run the bundled script:
```bash
<skill>/scripts/fetch-listing.sh "<ASIN>" [marketplace]
```
**Parameters:**
- `ASIN` (required): e.g. B09V3KXJPB
- `marketplace` (optional): `us` (default), `uk`, `de`, `fr`, `it`, `es`, `jp`, `ca`, `au`, `in`, `mx`, `br`
**Extracts:** Title, brand, price, bullet points, description, image count, A+ content presence, rating, review count, BSR, categories, date first available.
If script returns incomplete data, fall back to `web_fetch` on the product URL.
### Step B2: Discover Target Keywords
If user provides keywords, use those. Otherwise, auto-discover:
1. Extract apparent keywords from current title and bullets
2. Run `web_search` for `site:amazon.com "[product type]"` to find competitors
3. Extract keywords from top 3 competitor titles and bullets
4. (Optional) Chain with `amazon-keyword-research` skill for deeper analysis
5. Compile a combined keyword list with estimated priority
### Step B3: Keyword Gap Analysis
Compare current listing against target keywords:
```
## Keyword Gap Analysis: [ASIN]
### ✅ Keywords Found in Listing
| Keyword | In Title | In Bullets | In Description |
|---------|----------|------------|----------------|
| [kw] | ✅ | ✅ | ❌ |
### ❌ Missing Keywords (Competitors Have, You Don't)
| Keyword | Competitor 1 | Competitor 2 | Competitor 3 | Priority |
|---------|-------------|-------------|-------------|----------|
| [kw] | ✅ Title | ✅ Bullet | ❌ | 🔴 High |
### Coverage: X/Y keywords (Z%)
```
### Step B4: 8-Dimension Audit
Score each on the scale shown, with keyword integration factored in:
| Dimension | Max Score | Key Criteria |
|-----------|-----------|-------------|
| **Title** | /15 | Primary keyword near front? Brand? Attributes? Under 200 chars? Not truncated on mobile? |
| **Bullet Points** | /15 | All 5 used? Benefit-first? Keywords embedded naturally? Under 500 chars each? |
| **Images** | /15 | 7+ images? White bg main? Infographic? Lifestyle? Size ref? Video? |
| **A+ Content** | /10 | Present? Brand story? Comparison chart? Lifestyle imagery? |
| **Description** | /10 | Keywords not in title/bullets? Readable? Problem→solution flow? |
| **Pricing** | /10 | Competitive? Coupon/deal present? |
| **Reviews** | /15 | 4.0+ stars? 100+ reviews? Recent reviews positive? |
| **SEO Coverage** | /10 | Primary kw in title+bullets+desc? Long-tail present? No wasted repeats? **Keyword coverage %** |
### Step B5: Generate Optimized Copy
Rewrite the listing incorporating missing keywords:
- Show **before vs after** for each component
- Highlight which keywords were added and where
- Maintain the brand's existing tone unless a different tone is requested
---
## Output Formats
The primary deliverable is always a **ready-to-use listing** that the seller can copy-paste directly into Seller Central. Diagnostic data (scores, keyword analysis) comes after as supporting evidence.
### Mode A Output — New Listing
```
# ✅ Your Listing — Ready to Use
## Title
[title text — copy this directly into Seller Central]
## Bullet Points
1. [BENEFIT HEADER] — [text with keyword]
2. [BENEFIT HEADER] — [text with keyword]
3. [BENEFIT HEADER] — [text with keyword]
4. [BENEFIT HEADER] — [text with keyword]
5. [BENEFIT HEADER] — [text with keyword]
## Description
[description text — copy this directly into Seller Central]
## Backend Search Terms
[comma-separated keywords to paste into Seller Central → Keywords → Search Terms]
---
# 📊 How We Built This Listing (Diagnostic)
**Marketplace:** Amazon [XX] | **Tone:** [tone] | **Keywords imported:** [count]
**Title characters:** [X]/200 | **Description characters:** [X]/2000
## Keyword Coverage: [X]%
| Keyword | Volume | In Title | In Bullets | In Description | Status |
|---------|--------|----------|------------|----------------|--------|
| [kw] | [vol] | ✅/❌ | ✅/❌ | ✅/❌ | 🟢🟡🔴 |
## Keyword Priority Breakdown
🔴 Primary (Title): [list]
🟡 Secondary (Bullets): [list]
🟢 Tertiary (Description): [list]
⚪ Backend: [list]
```
### Mode B Output — Audit + Optimized Listing
```
# ✅ Optimized Listing — Ready to Use
## Title
[optimized title — copy this directly into Seller Central]
## Bullet Points
1. [BENEFIT HEADER] — [optimized text]
2. [BENEFIT HEADER] — [optimized text]
3. [BENEFIT HEADER] — [optimized text]
4. [BENEFIT HEADER] — [optimized text]
5. [BENEFIT HEADER] — [optimized text]
## Description
[optimized description — copy this directly into Seller Central]
## Backend Search Terms
[comma-separated keywords to paste into Seller Central → Keywords → Search Terms]
---
# 📊 Audit Report: [ASIN]
**Product:** [title] | **Brand:** [brand]
**Price:** [price] | **Rating:** [stars] ([count] reviews)
## Score: [X/100] → [Y/100] (after optimization)
| Dimension | Before | After | Key Change |
|-----------|--------|-------|-----------|
| Title | /15 | /15 | [what changed] |
| Bullet Points | /15 | /15 | [what changed] |
| Images | /15 | — | [recommendation only] |
| A+ Content | /10 | — | [recommendation only] |
| Description | /10 | /10 | [what changed] |
| Pricing | /10 | — | [observation] |
| Reviews | /15 | — | [observation] |
| SEO Coverage | /10 | /10 | [what changed] |
## Keyword Coverage: [X]% → [Y]%
| Keyword | Before | After | Where Added |
|---------|--------|-------|-------------|
| [kw] | ❌ | ✅ | Title + Bullet 2 |
| [kw] | ✅ Title only | ✅ Title + Bullets | Bullet 4 |
## What Changed (Before → After)
**Title:**
> ❌ [original]
> ✅ [optimized]
**Bullets:**
> ❌ 1. [original]
> ✅ 1. [optimized — added: +[kw1], +[kw2]]
## 🔴 Issues Fixed
1. [what was wrong → how we fixed it]
## 🟡 Recommendations (requires seller action)
1. [image improvements, A+ content, pricing — things the skill can't rewrite]
## 🟢 What Was Already Working
1. [positive aspects preserved]
```
### Competitive Comparison (if requested)
```
| Dimension | Your Listing | Competitor 1 | Competitor 2 | Competitor 3 |
|-----------|-------------|-------------|-------------|-------------|
| Title score | /15 | /15 | /15 | /15 |
| Bullets score | /15 | /15 | /15 | /15 |
| Images | [count] | [count] | [count] | [count] |
| A+ Content | Yes/No | Yes/No | Yes/No | Yes/No |
| Keyword coverage | X% | X% | X% | X% |
| Price | — | — | — | — |
| Rating | — | — | — | — |
| **Total** | **/100** | **/100** | **/100** | **/100** |
```
### Key principles
1. The seller's workflow is: **copy the listing → paste into Seller Central → done.** The diagnostic section explains WHY those specific words were chosen, but the listing itself must stand alone as a complete, ready-to-use deliverable. Never output only a report without the actual listing copy.
2. **Output language must match the target marketplace.** Amazon US/UK/AU/CA/IN → English. Amazon DE → German. Amazon FR → French. Amazon JP → Japanese. Amazon ES/MX → Spanish. Amazon IT → Italian. Amazon BR → Portuguese. The entire output (listing copy AND diagnostic section) must be in the marketplace language, regardless of what language the user is speaking in the conversation.
## Integration with amazon-keyword-research
This skill works best when chained with [amazon-keyword-research](https://github.com/nexscope-ai/Amazon-Skills/tree/main/amazon-keyword-research):
```
Step 1: "Research keywords for portable blender on Amazon US"
→ amazon-keyword-research returns keyword list with volumes
Step 2: "Now create a listing using those keywords. Product: 380ml BPA-free blender, USB-C rechargeable. Tone: Friendly."
→ amazon-listing-optimization Mode A uses the keywords to generate optimized copy
```
## Limitations
This skill uses publicly available data from Amazon product pages. It cannot access backend search terms, exact search volumes, or PPC/conversion data. For deeper analytics, stay tuned for **[Nexscope](https://github.com/nexscope-ai)** — coming soon.
---
**Part of the [Nexscope](https://github.com/nexscope-ai) suite — AI-powered Amazon seller tools.**
FILE:_meta.json
{
"name": "amazon-listing-optimization",
"version": "1.0.0",
"ownerId": "nexscope-ai"
}
FILE:scripts/fetch-listing.sh
#!/usr/bin/env bash
# Amazon Listing Fetcher — extracts listing data from an Amazon product page
# Usage: fetch-listing.sh <ASIN> [marketplace]
# Marketplaces: us (default), uk, de, fr, it, es, jp, ca, au, in, mx, br
set -uo pipefail
ASIN="?Usage: fetch-listing.sh <ASIN> [marketplace]"
MP="-us"
declare -A DOMAINS=(
[us]="www.amazon.com" [uk]="www.amazon.co.uk" [de]="www.amazon.de"
[fr]="www.amazon.fr" [it]="www.amazon.it" [es]="www.amazon.es"
[jp]="www.amazon.co.jp" [ca]="www.amazon.ca" [au]="www.amazon.com.au"
[in]="www.amazon.in" [mx]="www.amazon.com.mx" [br]="www.amazon.com.br"
)
DOMAIN="-www.amazon.com"
URL="https://DOMAIN/dp/ASIN"
# Fetch the page
PAGE=$(curl -sL \
-H "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" \
-H "Accept-Language: en-US,en;q=0.9" \
-H "Accept: text/html,application/xhtml+xml" \
--max-time 15 \
"$URL" 2>/dev/null)
if [ -z "$PAGE" ]; then
echo "ERROR: Failed to fetch $URL"
exit 1
fi
echo "=== LISTING DATA FOR $ASIN ($MP) ==="
echo "URL: $URL"
echo ""
# Title
echo "=== TITLE ==="
echo "$PAGE" | grep -o 'productTitle"[^>]*>[^<]*' | sed 's/productTitle"[^>]*>//;s/^[[:space:]]*//;s/[[:space:]]*$//' | head -1
echo ""
# Brand
echo "=== BRAND ==="
echo "$PAGE" | grep -o 'bylineInfo"[^>]*>[^<]*' | sed 's/bylineInfo"[^>]*>//;s/^[[:space:]]*Visit the //;s/ Store$//' | head -1
echo ""
# Price
echo "=== PRICE ==="
echo "$PAGE" | grep -o '<span class="a-offscreen">[^<]*</span>' | head -1 | sed 's/<[^>]*>//g'
echo ""
# Rating
echo "=== RATING ==="
echo "$PAGE" | grep -o '[0-9]\.[0-9] out of 5 stars' | head -1
echo ""
# Review count
echo "=== REVIEW COUNT ==="
echo "$PAGE" | grep -o 'acrCustomerReviewText"[^>]*>[^<]*' | sed 's/acrCustomerReviewText"[^>]*>//' | head -1
echo ""
# Bullet points
echo "=== BULLET POINTS ==="
echo "$PAGE" | grep -o 'a-list-item">[A-Z][^<]\{15,\}' | sed 's/a-list-item">//' | head -10
echo ""
# Description
echo "=== DESCRIPTION ==="
echo "$PAGE" | grep -o 'productDescription"[^>]*>.*</div>' | head -1 | sed 's/<[^>]*>//g;s/^[[:space:]]*//;s/[[:space:]]*$//' | head -5
echo ""
# Image count (main images)
echo "=== IMAGE COUNT ==="
IMG_COUNT=$(echo "$PAGE" | grep -o '"hiRes":"https://[^"]*"' | wc -l)
echo "$IMG_COUNT main images"
echo ""
# A+ Content detection
echo "=== A+ CONTENT ==="
if echo "$PAGE" | grep -q 'aplus-v2\|a-plus-content\|aplusPageWidget'; then
echo "YES — A+ Content detected"
else
echo "NO — No A+ Content found"
fi
echo ""
# BSR
echo "=== BEST SELLERS RANK ==="
echo "$PAGE" | grep -o '#[0-9,]* in [^<]*' | head -3
echo ""
# Category
echo "=== CATEGORY ==="
echo "$PAGE" | grep -o 'a-link-normal a-color-tertiary"[^>]*>[^<]*' | sed 's/.*>//;s/^[[:space:]]*//;s/[[:space:]]*$//' | head -5
echo ""
# Date first available
echo "=== DATE FIRST AVAILABLE ==="
echo "$PAGE" | grep -o 'Date First Available[^<]*' | sed 's/Date First Available//;s/[^A-Za-z0-9, ]//g;s/^[[:space:]]*//;s/[[:space:]]*$//' | head -1
echo ""
echo "=== END ==="
AI-powered web research assistant that leverages BrowserAct API to supplement restricted web access by searching the internet for additional information. Designed for OpenClaw and Claude Code.
---
name: web-research-assistant
description: AI-powered web research assistant that leverages BrowserAct API to supplement restricted web access by searching the internet for additional information. Designed for OpenClaw and Claude Code.
---
# Web Research Assistant
This skill leverages **BrowserAct API** to provide powerful web research capabilities. When primary web access is restricted or blocked, it automatically searches the internet to find and extract relevant information, ensuring your research tasks are completed successfully.
## ✨ OpenClaw & Claude Code Optimized
**🚀 Works Seamlessly with OpenClaw and Claude Code**
| Platform | Status | Installation |
|----------|--------|--------------|
| **OpenClaw** | ✅ **Highly Recommended** | Copy to `~/.openclaw/skills/` |
| **Claude Code** | ✅ **Highly Recommended** | Native skill support |
| **OpenCode** | ✅ Fully Supported | Copy to `~/.opencode/skills/` |
| **Cursor** | ✅ Fully Supported | Copy to `~/.cursor/skills/` |
**Why This Skill?**
- 🎯 **Purpose-built for OpenClaw and Claude Code**
- 🔄 **Auto-recovery** when web access is restricted
- 🌐 **Global access** - no IP or geoblocking issues
- 💰 **Cost-effective** - saves token usage
- ⚡ **Fast execution** - BrowserAct powered
## 🎯 When to Use
**Web Access Restricted? No Problem!**
Use this skill when:
- 🔒 Target websites block AI assistant access
- 🌍 Geographic restrictions limit content access
- 🔐 Paywalls prevent data extraction
- ⏱️ Need quick supplemental information
- 📊 Research requires multiple data sources
- 🔍 Need current information beyond cached data
## 🔑 API Key Guidance
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, request the API key from the user:
**Required Message**:
> "Please provide your BrowserAct API Key from [BrowserAct Console](https://www.browseract.com/reception/integrations) to enable web research capabilities."
## 🛠️ Input Parameters
Configure research based on your needs:
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `query` | string | - | Research topic or question |
| `engine` | string | google | Search engine (google, bing, duckduckgo) |
| `max_results` | number | 10 | Results to retrieve (1-50) |
| `content_type` | string | all | Content filter (all, news, articles, data) |
| `time_range` | string | past_month | Time filter (anytime, past_day/week/month/year) |
## 💻 Quick Start
```bash
# Basic research
python web-research-assistant/scripts/research.py "AI technology trends"
# Deep research with more results
python web-research-assistant/scripts/research.py "competitor analysis" --max-results 20
# Current news research
python web-research-assistant/scripts/research.py "market trends" --content-type news
# Save to file
python web-research-assistant/scripts/research.py "industry data" -o research_report.md
```
## 📊 Output
**Structured Research Data:**
- Titles, URLs, snippets, and relevance scores
- Key facts and statistics extraction
- Source citations and references
- Comprehensive research report
## 🎪 What This Skill Does
1. **🔄 Auto-Supplement** - When direct access fails, automatically searches the web
2. **🌐 Global Search** - Bypasses geographic restrictions via BrowserAct
3. **📈 Multi-Source** - Aggregates data from multiple search results
4. **✅ Validation** - Cross-references information for accuracy
5. **📋 Report Generation** - Creates comprehensive research reports
---
## 能力特性 (Features)
1.**没有幻觉,确保稳定精准提取数据**:预设工作流,规避AI 生成式幻觉。
2.**没有人机验证问题**:内置绕过机制,无需处理 reCAPTCHA 或其他验证挑战。
3.**没有 IP 访问限制和电子围栏**:突破地域 IP 限制,确保全球范围内稳定访问。
4.**执行速度更敏捷**:相比纯 AI 驱动的浏览器自动化方案,任务执行更快速。
5.**极高的成本效益**:相比大量消耗 Token 的 AI 方案,能显著降低数据获取成本。
---
## 🔧 BrowserAct API Integration
```
Research Request → BrowserAct Search → Data Extraction → Validation → Final Report
```
**Powered by BrowserAct MCP** for reliable, unrestricted web access.
---
## ⚠️ Error Handling
- **Invalid API Key**: Report to user, do not retry
- **Search Failed**: Automatic retry with fallback engine
- **No Results**: Return partial data with notification
- **Timeout**: Extended timeout for large research tasks
---
## 📖 Best Practices
1. Use **specific queries** for targeted results
2. Apply **time filters** for current information
3. **Cross-reference** key findings
4. Choose **appropriate content types** for research goals
5. **Validate** statistics with multiple sources
---
## 🔗 Related Skills
- `amazon-competitor-analyzer` - Amazon competitive intelligence
- `google-maps-search-api-skill` - Business data extraction
- `google-news-api-skill` - News monitoring
---
**Version**: 1.0.0
**Updated**: 2026-02-08
**API**: BrowserAct MCP
**Template ID**: `TEMPLATE_ID_HERE`
FILE:scripts/research.py
#!/usr/bin/env python3
"""
Web Research Assistant - BrowserAct Skill
This script performs web research and searches the internet for information
when primary web access is restricted or blocked.
Template ID: TEMPLATE_ID_HERE
"""
import os
import json
import argparse
import requests
from typing import Optional, Dict, List
BROWSERACT_API_KEY = os.environ.get("BROWSERACT_API_KEY")
BROWSERACT_MCP_TOKEN = os.environ.get("BROWSERACT_MCP_TOKEN")
MCP_SERVER_URL = "https://mcp.browseract.com/"
def execute_web_search(query: str, search_engine: str = "google", max_results: int = 10,
content_type: str = "all", time_range: str = "past_month") -> Dict:
"""
Execute a web search using BrowserAct MCP.
Args:
query: Search query string
search_engine: Search engine to use (google, bing, duckduckgo)
max_results: Maximum number of results
content_type: Type of content (all, news, articles, reports, data)
time_range: Time filter (anytime, past_day, past_week, past_month, past_year)
Returns:
Dictionary containing search results
"""
payload = {
"action": "search",
"query": query,
"engine": search_engine,
"max_results": max_results,
"content_type": content_type,
"time_range": time_range,
"options": {
"extract_data": True,
"include_snippets": True,
"follow_redirects": True
}
}
response = requests.post(
MCP_SERVER_URL,
headers={
"Authorization": f"Bearer {BROWSERACT_MCP_TOKEN}",
"Content-Type": "application/json"
},
json=payload,
timeout=60000
)
if response.status_code == 200:
return response.json()
else:
raise Exception(f"Search failed: {response.status_code} - {response.text}")
def extract_key_information(results: Dict) -> Dict:
"""
Extract key information from search results.
Args:
results: Search results dictionary
Returns:
Dictionary with extracted key information
"""
extracted = {
"total_results": 0,
"key_facts": [],
"statistics": [],
"sources": [],
"summary": ""
}
if "results" in results:
extracted["total_results"] = len(results["results"])
for result in results["results"][:10]:
if "title" in result:
extracted["sources"].append({
"title": result["title"],
"url": result.get("url", ""),
"snippet": result.get("snippet", "")
})
# Extract potential statistics (numbers with context)
if "snippet" in result:
snippet = result["snippet"]
# Simple heuristic for extracting statistics
if any(char.isdigit() for char in snippet):
extracted["statistics"].append(snippet[:200])
# Generate summary
if extracted["sources"]:
extracted["summary"] = f"Found {extracted['total_results']} relevant sources"
return extracted
def format_research_report(results: Dict, extracted: Dict, query: str) -> str:
"""
Format research report as markdown.
Args:
results: Raw search results
extracted: Extracted key information
query: Original search query
Returns:
Formatted markdown report
"""
report = f"# Web Research Report\n\n"
report += f"**Query**: {query}\n\n"
report += f"**Date**: {__import__('datetime').datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
report += "## Executive Summary\n\n"
report += f"{extracted['summary']}\n\n"
report += "## Key Findings\n\n"
for i, fact in enumerate(extracted["key_facts"][:5], 1):
report += f"{i}. {fact}\n"
if not extracted["key_facts"]:
report += "_No specific key facts extracted from search results._\n"
report += "\n## Statistics & Data\n\n"
for stat in extracted["statistics"][:5]:
report += f"- {stat}\n"
if not extracted["statistics"]:
report += "_No statistics found in search results._\n"
report += "\n## Data Sources\n\n"
for i, source in enumerate(extracted["sources"][:10], 1):
report += f"### {i}. {source['title']}\n"
report += f"**URL**: {source['url']}\n"
report += f"**Snippet**: {source['snippet'][:300]}...\n\n"
report += "\n## Recommendations\n\n"
report += "- Verify key findings with additional sources\n"
report += "- Cross-reference statistics with official data\n"
report += "- Check publication dates for currency\n"
report += "- Consider multiple perspectives on the topic\n"
return report
def main():
"""Main CLI entry point."""
parser = argparse.ArgumentParser(
description="Web Research Assistant - Supplement restricted web access with internet search"
)
parser.add_argument("query", help="Research topic or question to search for")
parser.add_argument("--engine", "-e", default="google",
choices=["google", "bing", "duckduckgo"],
help="Search engine to use")
parser.add_argument("--max-results", "-m", type=int, default=10,
help="Maximum number of results (1-50)")
parser.add_argument("--content-type", "-c", default="all",
choices=["all", "news", "articles", "reports", "data"],
help="Type of content to search for")
parser.add_argument("--time-range", "-t", default="past_month",
choices=["anytime", "past_day", "past_week", "past_month", "past_year"],
help="Time filter for results")
parser.add_argument("--output", "-o", help="Output file path for report")
parser.add_argument("--format", "-f", default="markdown",
choices=["markdown", "json"],
help="Output format")
parser.add_argument("--verbose", "-v", action="store_true", help="Verbose output")
args = parser.parse_args()
if not BROWSERACT_MCP_TOKEN:
print("Error: BROWSERACT_MCP_TOKEN environment variable not set")
print("Get your token from: https://www.browseract.com/reception/integrations")
return 1
try:
if args.verbose:
print(f"Researching: {args.query}")
print(f"Using engine: {args.engine}")
print(f"Content type: {args.content_type}")
print(f"Time range: {args.time_range}")
# Execute search
results = execute_web_search(
args.query,
args.engine,
args.max_results,
args.content_type,
args.time_range
)
# Extract key information
extracted = extract_key_information(results)
# Generate report
if args.format == "markdown":
report = format_research_report(results, extracted, args.query)
else:
report = json.dumps({
"query": args.query,
"results": results,
"extracted": extracted
}, indent=2, ensure_ascii=False)
# Output
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(report)
if args.verbose:
print(f"Report saved to: {args.output}")
else:
print(report)
if args.verbose:
print(f"\nTotal sources found: {extracted['total_results']}")
print(f"Sources used in report: {len(extracted['sources'])}")
return 0
except Exception as e:
print(f"Error: {e}")
return 1
if __name__ == "__main__":
exit(main())
This skill helps users automatically extract structured news data from Google News via BrowserAct API. Agent should proactively apply this skill when users e...
---
name: google-news-api-skill
description: "This skill helps users automatically extract structured news data from Google News via BrowserAct API. Agent should proactively apply this skill when users express needs like searching for news about a specific topic, tracking industry trends, monitoring public relations or sentiment, collecting competitor updates, getting latest reports on specific keywords, monitoring brand exposure in media, researching market hot topics, summarizing daily industry news, tracking media activities of specific individuals, retrieving hot events from the past 24 hours, extracting structured data for market research, monitoring global breaking news."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Google News Automation Skill
## 📖 Introduction
This skill provides a one-stop news collection service using BrowserAct's Google News API template. It directly extracts structured news results from Google News, including headlines, sources, publication times, and article links. Simply input search keywords and time filters to get clean, usable news data.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
Agent should flexibly configure the following parameters based on user needs:
1. **Search_Keywords (Search Keywords)**
- **Type**: `string`
- **Description**: The content to search on Google News. Can be company names, industry terms, competitor names, etc.
- **Example**: `AI Startup`, `Tesla`, `SpaceX`
2. **Publish_date (Time Range)**
- **Type**: `string`
- **Description**: Filter news by publication time.
- **Options**:
- `any time`: No restriction
- `past hours`: Past few hours (breaking news)
- `past 24 hours`: Past 24 hours (daily monitoring)
- `past week`: Past week (short-term trends)
- `past year`: Past year (long-term research)
- **Default**: `past week`
3. **Datelimit (Max Items)**
- **Type**: `number`
- **Description**: Maximum number of news items to extract per task.
- **Default**: `30`
- **Suggestion**: Use 10-30 for real-time monitoring; use larger values for deep research.
## 🚀 Usage
Agent should use the following independent script to achieve "one-line command result":
```bash
# Example
python -u ./scripts/google_news_api.py "Search Keywords" "Publish Date" Quantity
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
After successful execution, the script parses and prints results directly from the API response. Results include:
- `headline`: News title
- `source`: Publisher/Source
- `news_link`: Article URL
- `published_time`: Publication time
- `author`: Author (if available)
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Industry Trend Tracking**: Find the latest developments in fields like "Low-altitude economy" or "Generative AI".
2. **PR Monitoring**: Monitor media exposure of a specific brand or company over the past 24 hours.
3. **Competitor Intelligence**: Collect information on new products or marketing activities from competitors over the past week.
4. **Market Research**: Get popular reports on specific keywords across different time dimensions.
5. **Figure Tracking**: Retrieve the latest news reports on industry leaders or public figures.
6. **Daily News Summary**: Automatically extract and summarize daily news in specific domains.
7. **Global Breaking News**: Get real-time updates on major global events.
8. **Structured Data Extraction**: Extract structured information like headlines, sources, and links for analysis.
9. **Media Exposure Analysis**: Evaluate the propagation heat of a project or event in mainstream news media.
10. **Long-term Research**: Retrieve all in-depth reports on a specific technical topic from the past year.
FILE:scripts/google_news_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams to ensure compatibility with Windows PowerShell
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
# TEMPLATE_ID extracted from official BrowserAct Google News API documentation
TEMPLATE_ID = "77638424152140851"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_news_task(api_key, keywords, date_range="past week", limit=30):
"""
Executes a Google News scraping task via BrowserAct API.
Args:
api_key (str): BrowserAct API Key
keywords (str): Search keywords
date_range (str): Time range filter (any time, past hours, past 24 hours, past week, past year)
limit (int): Maximum number of items to extract
"""
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "Search_Keywords", "value": keywords},
{"name": "Publish_date", "value": date_range},
{"name": "Datelimit", "value": str(limit)}
]
}
# 1. Start Task
print(f"Starting task via BrowserAct API...", flush=True)
try:
response = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers)
res = response.json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if response.status_code == 401 or (isinstance(res, dict) and "Invalid authorization" in str(res)):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
return None
if "id" not in res:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started successfully. Task ID: {task_id}", flush=True)
# 2. Poll for Completion
print(f"Waiting for task completion...", flush=True)
while True:
try:
status_response = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers)
status_res = status_response.json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying in 10s...", flush=True)
time.sleep(10)
# 3. Get Results
print(f"Retrieving results...", flush=True)
try:
task_info_response = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers)
task_info = task_info_response.json()
# Extract structured data from API response
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Get API Key from environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_news_api.py <keywords> [date_range] [limit]", flush=True)
print("Example: python google_news_api.py \"AI technology\" \"past 24 hours\" 10", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Set it as an environment variable (BROWSERACT_API_KEY) or provide it in the chat.", flush=True)
sys.exit(1)
keywords = sys.argv[1]
date_range = sys.argv[2] if len(sys.argv) > 2 else "past week"
limit = sys.argv[3] if len(sys.argv) > 3 else 30
result = run_google_news_task(api_key, keywords, date_range, limit)
if result:
# Final output for the Agent to process
print(result, flush=True)
This skill is designed to help users automatically extract business data from Google Maps search results. The Agent should proactively apply this skill when...
---
name: google-maps-search-api-skill
description: "This skill is designed to help users automatically extract business data from Google Maps search results. The Agent should proactively apply this skill when the user makes the following requests searching for coffee shops in a specific city, finding dentists or medical clinics nearby, tracking competitors' locations in a certain area, extracting business leads from Google Maps lists, gathering restaurant data for market research, finding hotels or accommodation options in a region, locating specific services like coworking spaces or gyms, monitoring new business openings in a neighborhood, collecting contact information and addresses for sales prospecting, analyzing price ranges and cuisines of local eateries, getting ratings and review counts for a list of businesses, exporting local business data into a CRM or database."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Google Maps Search Automation Skill
## 📖 Introduction
This skill utilizes the BrowserAct Google Maps Search API template to provide a one-stop business data collection service. It extracts structured business results directly from Google Maps search lists. Simply provide search keywords, language, and country filters to get clean, usable business data.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
When calling the script, the Agent should flexibly configure the following parameters based on user needs:
1. **KeyWords**
- **Type**: `string`
- **Description**: The content you want to search on Google Maps. Can be business names, categories, or specific keywords.
- **Example**: `coffee shop`, `dental clinic`, `coworking space`
2. **language**
- **Type**: `string`
- **Description**: Sets the UI language and the language of returned text fields.
- **Common Values**: `en`, `de`, `fr`, `it`, `es`, `ja`, `zh-CN`, `zh-TW`
- **Default**: `en`
3. **country**
- **Type**: `string`
- **Description**: Sets the country or region bias for search results.
- **Example**: `us`, `gb`, `ca`, `au`, `de`, `fr`, `jp`
- **Default**: `us`
4. **max_dates**
- **Type**: `number`
- **Description**: The maximum number of places to extract from the search results list.
- **Default**: `100`
## 🚀 Usage
The Agent should execute the following independent script to achieve "one-line command result":
```bash
# Example call
python -u ./scripts/google_maps_search_api.py "search keywords" "language" "country" count
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
After successful execution, the script parses and prints results directly from the API response. Fields include:
- `name`: Business name
- `full address`: Full address
- `rating`: Star rating
- `review count`: Number of reviews
- `price range`: Price level
- `cuisine type`: Business category
- `amenity tags`: Features like Wi-Fi
- `review snippet`: Short review text
- `service options`: Service indicators (e.g., "Order online")
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Local Business Discovery**: Find all "Italian restaurants" in Manhattan.
2. **Sales Lead Generation**: Extract a list of "real estate agencies" in London for prospecting.
3. **Competitor Mapping**: Locate all "Starbucks" branches in a specific city to map competition.
4. **Market Research**: Analyze "boutique hotels" in Paris, including their ratings and price ranges.
5. **Contact Collection**: Gather addresses and names of "dental clinics" in Sydney.
6. **Service Search**: Find "24-hour pharmacies" or "emergency plumbers" in a certain area.
7. **Neighborhood Monitoring**: Track new "gyms" or "yoga studios" opening in a community.
8. **Structured Data Export**: Export structured data of "car dealerships" for CRM integration.
9. **Sentiment Analysis Prep**: Get review snippets and ratings for "popular tourist attractions".
10. **Global Search Localization**: Use different language and country settings to research "tech hubs" globally.
FILE:scripts/google_maps_search_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
TEMPLATE_ID = "77805072070738748"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_maps_search_task(api_key, keywords, language="en", country="us", max_dates=100):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "KeyWords", "value": keywords},
{"name": "language", "value": language},
{"name": "country", "value": country},
{"name": "max_dates", "value": str(max_dates)}
]
}
# 1. Start Task
print(f"Start Task", flush=True)
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Prioritize command line API key, then environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_maps_search_api.py <keywords> [language] [country] [max_dates]", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).", flush=True)
sys.exit(1)
keywords = sys.argv[1]
language = sys.argv[2] if len(sys.argv) > 2 else "en"
country = sys.argv[3] if len(sys.argv) > 3 else "us"
max_dates = sys.argv[4] if len(sys.argv) > 4 else 100
result = run_google_maps_search_task(api_key, keywords, language, country, max_dates)
if result:
print(result, flush=True)
This skill is designed to help users automatically extract reviews from Google Maps via the Google Maps Reviews API. Agent should proactively apply this skil...
---
name: google-maps-reviews-api-skill
description: "This skill is designed to help users automatically extract reviews from Google Maps via the Google Maps Reviews API. Agent should proactively apply this skill when users request to find reviews for local businesses (e.g., coffee shops, clinics), monitor customer feedback for a specific brand or location, analyze sentiment of reviews for competitors, extract reviews for a chain of stores or services, track reputation of a local restaurant, gather user testimonials for a specific venue, conduct market research on service quality of local businesses, monitor reviews for a new retail location, collect feedback on public attractions or parks, identify common complaints for a specific service provider, research the best-rated places in a city, analyze recurring themes in reviews for a specific industry."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Google Maps Reviews Automation Skill
## 📖 Introduction
This skill provides a one-stop review collection service using BrowserAct's Google Maps Reviews API template. It can extract structured review data directly from Google Maps search results. Simply provide the search keywords, language, and country to get clean, usable review data.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
The Agent should flexibly configure the following parameters when calling the script:
1. **KeyWords (Search Keywords)**
- **Type**: `string`
- **Description**: The query used to find places on Google Maps (e.g., business names, categories).
- **Example**: `coffee shop`, `dental clinic`, `Tesla showroom`
2. **language (Language)**
- **Type**: `string`
- **Description**: Sets the UI language and the language of the returned text.
- **Supported values**: `en`, `zh-CN`, `es`, `fr`, etc.
- **Default**: `en`
3. **country (Country)**
- **Type**: `string`
- **Description**: Country or region bias for search results.
- **Supported values**: `us`, `gb`, `ca`, `au`, `jp`, etc.
- **Default**: `us`
## 🚀 Usage
Agent should use the following independent script to achieve "one-line command result":
```bash
# Example call
python -u ./scripts/google_maps_reviews_api.py "Keywords" "Language" "Country"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
After successful execution, the script parses and prints results from the API response:
- `author_name`: Display name of the reviewer
- `author_profile_url`: Profile URL of the reviewer
- `rating`: Star rating
- `text`: Review text content
- `comment_date`: Human-readable date
- `likes_count`: Number of likes
- `author_image_url`: Reviewer's avatar URL
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Local Business Analysis**: Find reviews for cafes or clinics in a specific area.
2. **Reputation Monitoring**: Track feedback for a specific brand location.
3. **Competitive Benchmarking**: Analyze reviews of competitor stores.
4. **Sentiment Analysis**: Gather review text for emotion and topic modeling.
5. **Market Research**: Evaluate service quality across different regions.
6. **Lead Qualification**: Use review data to identify high-quality service providers.
7. **Customer Insight**: Understand recurring complaints or praises.
8. **Venue Research**: Collect testimonials for parks, museums, or attractions.
9. **Retail Monitoring**: Gather feedback for newly opened stores.
10. **Service Quality Audit**: Analyze ratings and comments for a specific service chain.
FILE:scripts/google_maps_reviews_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
TEMPLATE_ID = "77806855016940604"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_maps_reviews_task(api_key, keywords, language="en", country="us"):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "KeyWords", "value": keywords},
{"name": "language", "value": language},
{"name": "country", "value": country}
]
}
# 1. Start Task
print(f"Start Task", flush=True)
try:
response = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers)
if response.status_code == 401:
print(f"Error: Invalid authorization. Please check your API key.", flush=True)
return None
res = response.json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your API key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Prioritize environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_maps_reviews_api.py <keywords> [language] [country]", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).", flush=True)
sys.exit(1)
keywords = sys.argv[1]
language = sys.argv[2] if len(sys.argv) > 2 else "en"
country = sys.argv[3] if len(sys.argv) > 3 else "us"
result = run_google_maps_reviews_task(api_key, keywords, language, country)
if result:
print(result, flush=True)
This skill helps users automatically scrape business data from Google Maps using the BrowserAct Google Maps API. Agent should proactively trigger this skill...
---
name: google-maps-api-skill
description: "This skill helps users automatically scrape business data from Google Maps using the BrowserAct Google Maps API. Agent should proactively trigger this skill for needs like finding restaurants in a specific city, extracting contact info of dental clinics, researching local competitors, collecting addresses of coffee shops, generating lead lists for specific industries, monitoring business ratings and reviews, getting opening hours of local services, finding specialized stores (e.g., Turkish-style restaurants), analyzing business categories in a region, extracting website links from local businesses, gathering phone numbers for sales outreach, mapping out service providers in a specific country."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Google Maps Automation Scraper Skill
## 📖 Introduction
This skill leverages BrowserAct's Google Maps API template to provide a one-stop business data collection service. It extracts structured details directly from Google Maps, including business names, categories, contact info, ratings, and more. Simply provide the search keywords and location bias to get clean, actionable data.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
Configure the following parameters based on user requirements:
1. **keywords (Search Keywords)**
- **Type**: `string`
- **Description**: The query you would search for on Google Maps.
- **Example**: `coffee shop`, `dental clinic`, `Turkish-style restaurant`
2. **language (UI Language)**
- **Type**: `string`
- **Description**: Defines the UI language and returned text language (e.g., en, zh-CN).
- **Default**: `en`
3. **country (Country Bias)**
- **Type**: `string`
- **Description**: Specifies the country or region bias (e.g., us, gb, ca).
- **Default**: `us`
## 🚀 Usage
Execute the following script to get results in one command:
```bash
# Example call
python -u ./scripts/google_maps_api.py "keywords" "language" "country"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
Upon success, the script parses and prints the following fields from the API:
- `Title Name`: Official business name
- `Category_primary`: Main business category
- `Address`: Full street address
- `Phone number`: Contact phone number
- `Website link`: Official URL
- `Rating`: Average star rating
- `reviews_count`: Total number of reviews
- `business_status`: Operational status (e.g., operational)
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Lead Generation**: Find "SaaS companies" in "us" for sales outreach.
2. **Competitor Research**: Extract data on "coffee shops" in a specific neighborhood.
3. **Market Analysis**: Identify the density of "dental clinics" in a region.
4. **Contact Info Retrieval**: Get phone numbers and websites for "real estate agencies".
5. **Local Service Discovery**: Find "Turkish-style restaurants" with high ratings.
6. **Business Status Monitoring**: Check if specific stores are "operational".
7. **Directory Building**: Gather addresses and categories for a local business directory.
8. **Rating Benchmarking**: Compare ratings of various "luxury hotels".
9. **Global Scouting**: Research "tech startups" in different countries like "gb" or "au".
10. **Automated Data Sync**: Periodically pull local business data into a CRM.
FILE:scripts/google_maps_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
TEMPLATE_ID = "77577579210625331"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_maps_task(api_key, keywords, language="en", country="us"):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "keywords", "value": keywords},
{"name": "language", "value": language},
{"name": "country", "value": country}
]
}
# 1. Start Task
print(f"Start Task", flush=True)
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your API key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# The result is usually in output['string'] or within the raw JSON response
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Get API key from environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_maps_api.py <keywords> [language] [country]", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).", flush=True)
sys.exit(1)
keywords = sys.argv[1]
language = sys.argv[2] if len(sys.argv) > 2 else "en"
country = sys.argv[3] if len(sys.argv) > 3 else "us"
result = run_google_maps_task(api_key, keywords, language, country)
if result:
print(result, flush=True)
This skill helps users automatically extract Amazon product reviews via the Amazon Reviews API. Agent should proactively apply this skill when users express...
---
name: amazon-reviews-api-skill
description: "This skill helps users automatically extract Amazon product reviews via the Amazon Reviews API. Agent should proactively apply this skill when users express needs like getting reviews for Amazon product with ASIN B07TS6R1SF, analyzing customer feedback for a specific Amazon item, getting ratings and comments for a competitive product, tracking sentiment of recent Amazon reviews, extracting verified purchase reviews for quality assessment, summarizing user experiences from Amazon product pages, monitoring product performance through customer reviews, collecting reviewer profiles and links for market research, gathering review titles and descriptions for content analysis, scraping Amazon reviews without requiring a login."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Amazon Reviews Automation Extraction Skill
## 📖 Introduction
This skill provides a one-stop Amazon review collection service through BrowserAct's Amazon Reviews API template. It can directly extract structured review results from Amazon product pages. By simply providing an ASIN, you can get clean, usable review data without building crawler scripts or requiring an Amazon account login.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
When calling the script, the Agent should flexibly configure parameters based on user needs:
1. **ASIN (Amazon Standard Identification Number)**
- **Type**: `string`
- **Description**: The unique identifier for the product on Amazon.
- **Example**: `B07TS6R1SF`, `B08N5WRWJ6`
## 🚀 Usage
The Agent should execute the following independent script to achieve "one-line command result":
```bash
# Example call
python -u ./scripts/amazon_reviews_api.py "ASIN_HERE"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
After successful execution, the script will parse and print results directly from the API response. Each review item includes:
- `Commentator`: Reviewer's name
- `Commenter profile link`: Link to the reviewer's profile
- `Rating`: Star rating
- `reviewTitle`: Headline of the review
- `review Description`: Full text of the review
- `Published at`: Date the review was published
- `Country`: Reviewer's country
- `Variant`: Product variant info (if available)
- `Is Verified`: Whether it's a verified purchase
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Competitor Analysis**: Extract reviews for competitors' products to understand their strengths and weaknesses.
2. **Product Feedback**: Summarize feedback for your own products to identify areas for improvement.
3. **Market Research**: Collect data on customer preferences and common complaints in a specific category.
4. **Sentiment Monitoring**: Monitor recent reviews to detect shifts in customer sentiment.
5. **QA Insights**: Use customer reviews to identify potential quality issues or bugs.
6. **Sentiment Analysis Prep**: Gather review text and ratings for detailed emotion modeling.
7. **Verified Purchase Analysis**: Compare feedback from verified vs. unverified buyers.
8. **Geographic Insights**: Analyze product performance across different reviewer countries.
9. **Variant Comparison**: Understand which product variants (size/color) receive the best feedback.
10. **Historical Trend Tracking**: Retrieve and analyze review publication dates to track product lifecycle sentiment.
FILE:scripts/amazon_reviews_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
TEMPLATE_ID = "77817507798321724"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_amazon_reviews_task(api_key, asin):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "ASIN", "value": asin}
]
}
# 1. Start Task
print(f"Start Task", flush=True)
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Prioritize environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python amazon_reviews_api.py <asin>", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).", flush=True)
sys.exit(1)
asin = sys.argv[1]
result = run_amazon_reviews_task(api_key, asin)
if result:
print(result, flush=True)
This skill is designed to help users automatically extract product data from Amazon search results. The Agent should proactively apply this skill when users...
---
name: amazon-product-search-api-skill
description: "This skill is designed to help users automatically extract product data from Amazon search results. The Agent should proactively apply this skill when users request searching for products related to keywords, finding best-selling items from specific brands, monitoring product prices and availability on Amazon, extracting product listings for market research, collecting product ratings and review counts for competitive analysis, finding specific products with a maximum count, searching Amazon in different languages for localized results, tracking monthly sales estimates for brand products, gathering product URLs and titles for a product catalog, scanning Amazon for Best Seller tags in a specific category, monitoring shipping and delivery information for brand items, building a structured dataset of Amazon search results."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Amazon Product Search Automation Skill
## 📖 Introduction
This skill provides a one-stop product data collection service through BrowserAct's Amazon Product Search API template. It directly extracts structured product results from Amazon search lists. Simply input search keywords, brand filters, and quantity limits to get clean, usable product data.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
When calling the script, the Agent should flexibly configure the following parameters based on user needs:
1. **KeyWords (Search Keywords)**
- **Type**: `string`
- **Description**: The keywords the user wants to search for on Amazon.
- **Example**: `phone`, `wireless earbuds`, `laptop stand`
2. **Brand (Brand Filter)**
- **Type**: `string`
- **Description**: Filter products by brand name shown in the listing.
- **Example**: `Apple`, `Samsung`, `Sony`
3. **Maximum_date (Maximum Products)**
- **Type**: `number`
- **Description**: The maximum number of products to extract across paginated search results.
- **Default**: `50`
4. **language (UI Language)**
- **Type**: `string`
- **Description**: UI language for the Amazon browsing session.
- **Options**: `en`, `de`, `fr`, `it`, `es`, `ja`, `zh-CN`, `zh-TW`
- **Default**: `en`
## 🚀 Usage
The Agent should execute the following independent script to achieve "one-line command result":
```bash
# Example Call
python -u ./scripts/amazon_product_search_api.py "Keywords" "Brand" Quantity "language"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
After successful execution, the script will parse and print results directly from the API response. Results include:
- `product_title`: Product name
- `product_url`: Detail page URL
- `rating_score`: Average star rating
- `review_count`: Total number of reviews
- `monthly_sales`: Estimated monthly sales (if available)
- `current_price`: Current selling price
- `list_price`: Original list price (if available)
- `delivery_info`: Delivery or fulfillment information
- `shipping_location`: Shipping origin or location
- `is_best_seller`: Whether marked as Best Seller
- `is_available`: Whether available for purchase
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Market Research**: Search for "wireless earbuds" from "Sony" to analyze the current market.
2. **Competitive Monitoring**: Track "Samsung" phone prices and availability on Amazon.
3. **Catalog Discovery**: Gather product titles and URLs for a new product catalog in the "laptop stand" category.
4. **Localized Analysis**: Search Amazon in "ja" (Japanese) to understand products available in the Japan region.
5. **Best Seller Tracking**: Identify products marked as "Best Seller" for a specific brand.
6. **Pricing Intelligence**: Compare `current_price` and `list_price` to monitor discounts.
7. **Sales Trend Estimation**: Use `monthly_sales` data to estimate market demand for certain items.
8. **Shipping Efficiency Study**: Analyze `delivery_info` and `shipping_location` for various brands.
9. **Large-scale Data Extraction**: Collect up to 100 products for a comprehensive dataset.
10. **Product Availability Check**: Verify if specific brand products are currently `is_available` for purchase.
FILE:scripts/amazon_product_search_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
TEMPLATE_ID = "77809217106347580"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_amazon_product_search_task(api_key, keywords, brand="Apple", limit=50, language="en"):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "KeyWords", "value": keywords},
{"name": "Brand", "value": brand},
{"name": "Maximum_date", "value": str(limit)},
{"name": "language", "value": language}
]
}
# 1. Start Task
print(f"Start Task", flush=True)
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# Extract data from output["string"] as requested
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Prioritize command line API key, then environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python amazon_product_search_api.py <keywords> [brand] [limit] [language]", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).", flush=True)
sys.exit(1)
keywords = sys.argv[1]
brand = sys.argv[2] if len(sys.argv) > 2 else "Apple"
limit = sys.argv[3] if len(sys.argv) > 3 else 50
language = sys.argv[4] if len(sys.argv) > 4 else "en"
result = run_amazon_product_search_task(api_key, keywords, brand, limit, language)
if result:
print(result, flush=True)
This skill helps users extract structured product listings from Amazon, including titles, ASINs, prices, ratings, and specifications. Use this skill when use...
---
name: amazon-product-api-skill
description: "This skill helps users extract structured product listings from Amazon, including titles, ASINs, prices, ratings, and specifications. Use this skill when users want to search for products on Amazon, find the best selling brand products, track price changes for items, get a list of categories with high ratings, compare different brand products on Amazon, extract Amazon product data for market research, look for products in a specific language or marketplace, analyze competitor pricing for keywords, find featured products for search terms, get technical specifications like material or color for product lists."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Amazon Product Search Skill
## 📖 Introduction
This skill utilizes BrowserAct's Amazon Product API template to extract structured product listings from Amazon search results. It provides detailed information including titles, ASINs, prices, ratings, and product specifications, enabling efficient market research and product monitoring without manual data collection.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
The agent should configure the following parameters based on user requirements:
1. **KeyWords**
- **Type**: `string`
- **Description**: Search keywords used to find products on Amazon.
- **Required**: Yes
- **Example**: `laptop`, `wireless earbuds`
2. **Brand**
- **Type**: `string`
- **Description**: Filter products by brand name.
- **Default**: `Apple`
- **Example**: `Dell`, `Samsung`
3. **Maximum_number_of_page_turns**
- **Type**: `number`
- **Description**: Number of search result pages to paginate through.
- **Default**: `1`
4. **language**
- **Type**: `string`
- **Description**: UI language for the Amazon browsing session.
- **Default**: `en`
- **Example**: `zh-CN`, `de`
## 🚀 Usage
Agent should use the following independent script to achieve "one-line command result":
```bash
# Example Usage
python -u ./scripts/amazon_product_api.py "keywords" "brand" pages "language"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
Upon success, the script parses and prints the structured product data from the API response, which includes:
- `product_title`: Full title of the product.
- `asin`: Amazon Standard Identification Number.
- `product_url`: URL of the Amazon product page.
- `brand`: Brand name.
- `price_current_amount`: Current price.
- `price_original_amount`: Original price (if applicable).
- `rating_average`: Average star rating.
- `rating_count`: Total number of ratings.
- `featured`: Badges like "Best Seller" or "Amazon's Choice".
- `color`, `material`, `style`: Product attributes (if available).
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Market Research**: Search for a specific product category to analyze top brands and pricing.
2. **Competitor Monitoring**: Track product listings and price changes for specific competitor brands.
3. **Product Catalog Enrichment**: Extract structured details like ASINs and specifications to build or update a product database.
4. **Rating Analysis**: Find high-rated products for specific keywords to identify market leaders.
5. **Localized Research**: Search Amazon in different languages to analyze international markets.
6. **Price Tracking**: Monitor current and original prices to identify discount trends.
7. **Brand Performance**: Evaluate the presence of a specific brand in search results across multiple pages.
8. **Attribute Extraction**: Gather technical specifications like material or color for a list of products.
9. **Lead Generation**: Identify popular products and their manufacturers for business outreach.
10. **Automated Data Feed**: Periodically pull Amazon search results into external BI tools or dashboards.
FILE:scripts/amazon_product_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams to handle multi-language content
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
# Amazon Product API Template ID
TEMPLATE_ID = "77670107419143475"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_amazon_product_task(api_key, keywords, brand="Apple", pages=1, language="en"):
"""
Executes an Amazon Product search task via BrowserAct API.
"""
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "KeyWords", "value": keywords},
{"name": "Brand", "value": brand},
{"name": "Maximum_number_of_page_turns", "value": str(pages)},
{"name": "language", "value": language}
]
}
# 1. Start Task
print(f"Starting Amazon Product search task for keywords: {keywords}", flush=True)
try:
response = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers)
res = response.json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# Extract data from output["string"] or the whole result
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Get API key from environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python amazon_product_api.py <keywords> [brand] [pages] [language]", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Set it as an environment variable (BROWSERACT_API_KEY) or provide it in the chat.", flush=True)
sys.exit(1)
keywords = sys.argv[1]
brand = sys.argv[2] if len(sys.argv) > 2 else "Apple"
pages = sys.argv[3] if len(sys.argv) > 3 else 1
language = sys.argv[4] if len(sys.argv) > 4 else "en"
result = run_amazon_product_task(api_key, keywords, brand, pages, language)
if result:
print(result, flush=True)
This skill helps users extract structured product details from Amazon using a specific ASIN (Amazon Standard Identification Number). Use this skill when the...
---
name: amazon-asin-lookup-api-skill
description: "This skill helps users extract structured product details from Amazon using a specific ASIN (Amazon Standard Identification Number). Use this skill when the user asks to get Amazon product details by ASIN, lookup Amazon product title and price using ASIN, extract Amazon product ratings and reviews count for a specific ASIN, check Amazon product availability and current price, get Amazon product description and features via ASIN, enrich product catalog with Amazon data using ASIN, monitor Amazon product price changes for specific ASINs, retrieve Amazon product brand and material information, fetch Amazon product images and specifications by ASIN, validate Amazon ASIN and get product metadata."
metadata: {"clawdbot":{"emoji":"🌐","requires":{"bins":["python"],"env":["BROWSERACT_API_KEY"]}}}
---
# Amazon ASIN Lookup Skill
## 📖 Introduction
This skill utilizes BrowserAct's Amazon ASIN Lookup API template to provide a seamless way to retrieve comprehensive product information from Amazon. By simply providing an ASIN, you can extract structured data including title, price, ratings, brand, and detailed descriptions directly into your application without manual scraping.
## ✨ Features
1. **No Hallucinations**: Pre-set workflows avoid AI generative hallucinations, ensuring stable and precise data extraction.
2. **No Captcha Issues**: No need to handle reCAPTCHA or other verification challenges.
3. **No IP Restrictions**: No need to handle regional IP restrictions or geofencing.
4. **Faster Execution**: Tasks execute faster compared to pure AI-driven browser automation solutions.
5. **Cost-Effective**: Significantly lowers data acquisition costs compared to high-token-consuming AI solutions.
## 🔑 API Key Setup
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not take other measures; ask and wait for the user to provide it.
**Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please visit the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key."
## 🛠️ Input Parameters
The agent should configure the following parameters based on user requirements:
1. **ASIN (Amazon Standard Identification Number)**
- **Type**: `string`
- **Description**: The unique identifier for the Amazon product.
- **Required**: Yes
- **Example**: `B07TS6R1SF`
## 🚀 Usage
The agent should execute the following script to get results in one command:
```bash
# Example Usage
python -u ./scripts/amazon_asin_lookup_api.py "ASIN_VALUE"
```
### ⏳ Execution Monitoring
Since this task involves automated browser operations, it may take some time (several minutes). The script will **continuously output status logs with timestamps** (e.g., `[14:30:05] Task Status: running`).
**Agent Instructions**:
- While waiting for the script result, keep monitoring the terminal output.
- As long as the terminal is outputting new status logs, the task is running normally; do not mistake it for a deadlock or unresponsiveness.
- Only if the status remains unchanged for a long time or the script stops outputting without returning a result should you consider triggering the retry mechanism.
## 📊 Data Output
Upon success, the script parses and prints the structured product data from the API response, which includes:
- `product_title`: Full title of the product.
- `ASIN`: The provided ASIN.
- `product_url`: URL of the Amazon product page.
- `brand`: Brand name.
- `price_current_amount`: Current price.
- `price_original_amount`: Original price (if applicable).
- `price_discount_amount`: Discount amount (if applicable).
- `rating_average`: Average star rating.
- `rating_count`: Total number of ratings.
- `featured`: Badges like "Amazon's Choice".
- `color`: Color variant (if applicable).
- `compatible_devices`: List of compatible devices (if applicable).
- `product_description`: Full product description.
- `special_features`: Highlighted features.
- `style`: Style attribute (if applicable).
- `material`: Material used (if applicable).
## ⚠️ Error Handling & Retry
If an error occurs during script execution (e.g., network fluctuations or task failure), the Agent should follow this logic:
1. **Check Output Content**:
- If the output **contains** `"Invalid authorization"`, it means the API Key is invalid or expired. **Do not retry**; guide the user to re-check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task failed (e.g., output starts with `Error:` or returns empty results), the Agent should **automatically try to re-execute the script once**.
2. **Retry Limit**:
- Automatic retry is limited to **one time**. If the second attempt fails, stop retrying and report the specific error information to the user.
## 🌟 Typical Use Cases
1. **Product Data Enrichment**: Retrieve full details for a list of ASINs to update an e-commerce database.
2. **Price Comparison**: Lookup current Amazon prices for specific ASINs to compare with other retailers.
3. **Review Monitoring**: Track changes in rating averages and review counts for key products.
4. **Availability Checks**: Automatically verify if a specific product is currently in stock on Amazon.
5. **Brand Analysis**: Identify the brand and manufacturer of products identified by ASIN.
6. **Detailed Specifications**: Fetch material, style, and color information for catalog management.
7. **Feature Highlighting**: Extract "special features" and detailed descriptions for marketing copy.
8. **Compatibility Verification**: Check "compatible devices" for electronics or accessories.
9. **Market Research**: Analyze featured badges like "Amazon's Choice" for specific product IDs.
10. **URL Resolution**: Convert a list of ASINs into full Amazon product page URLs.
FILE:scripts/amazon_asin_lookup_api.py
import os
import time
import requests
import json
import sys
import datetime
import io
# Force UTF-8 encoding for standard output and error streams to handle multi-language content
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# API Configuration
# Amazon ASIN Lookup API Template ID
TEMPLATE_ID = "77814333389670716"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_amazon_asin_lookup(api_key, asin):
"""
Starts an Amazon ASIN Lookup task and polls for completion.
"""
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "ASIN", "value": asin}
]
}
# 1. Start Task
print(f"Starting Amazon ASIN Lookup task for ASIN: {asin}", flush=True)
try:
response = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers)
res = response.json()
except Exception as e:
print(f"Error: Connection to API failed - {e}", flush=True)
return None
if "id" not in res:
# Check for authorization error
if "Invalid authorization" in str(res):
print(f"Error: Invalid authorization. Please check your BrowserAct API Key.", flush=True)
else:
print(f"Error: Could not start task. Response: {res}", flush=True)
return None
task_id = res["id"]
print(f"Task started. ID: {task_id}", flush=True)
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Task Status: {status}", flush=True)
if status == "finished":
print(f"[{timestamp}] Task finished successfully.", flush=True)
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.", flush=True)
return None
except Exception as e:
timestamp = datetime.datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] Polling error: {e}. Retrying...", flush=True)
time.sleep(10)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# Extract data from output["string"] or the whole result
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
# Fallback to returning the JSON representation of data
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}", flush=True)
return None
if __name__ == "__main__":
# Get API key from environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python amazon_asin_lookup_api.py <asin>", flush=True)
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.", flush=True)
print("Please follow these steps:", flush=True)
print("1. Go to: https://www.browseract.com/reception/integrations", flush=True)
print("2. Copy your API Key.", flush=True)
print("3. Set it as an environment variable (BROWSERACT_API_KEY) or provide it in the chat.", flush=True)
sys.exit(1)
asin = sys.argv[1]
result = run_amazon_asin_lookup(api_key, asin)
if result:
print(result, flush=True)
Scrape structured news data from Google News automatically. Use when the user asks for news on a topic, industry trends, or PR monitoring. Triggers on keywords like "find news about", "track trends", or "monitor PR".
---
name: google-news-api
description: Scrape structured news data from Google News automatically. Use when the user asks for news on a topic, industry trends, or PR monitoring. Triggers on keywords like "find news about", "track trends", or "monitor PR".
---
# Google News Automation Scraper Skill
## ✨ Platform Compatibility
**✅ Works Powerfully & Reliably On All Major AI Assistants**
| Platform | Status | How to Install |
|----------|--------|----------------|
| **OpenCode** | ✅ Fully Supported | Copy skill folder to `~/.opencode/skills/` |
| **Claude Code** | ✅ Fully Supported | Native skill support |
| **Cursor** | ✅ Fully Supported | Copy to `~/.cursor/skills/` |
| **OpenClaw** | ✅ Fully Supported | Compatible |
**Why Choose BrowserAct Skills?**
- 🚀 Stable & crash-free execution
- ⚡ Fast response times
- 🔧 No configuration headaches
- 📦 Plug & play installation
- 💬 Professional support
## 📖 Introduction
This skill provides a one-stop news collection service using BrowserAct's Google News API template. It allows the agent to retrieve structured news data with a single command.
## 🔑 API Key Guidance
Before running, check the `BROWSERACT_API_KEY` environment variable. If not set, do not proceed with script execution; instead, request the API key from the user.
**Required Message to User**:
> "Since you haven't configured the BrowserAct API Key, please go to the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key and provide it to me in this chat."
## 🛠️ Input Parameters
Flexibly configure these parameters based on user requirements:
1. **Search_Keywords**
- **Type**: `string`
- **Description**: Keywords to search on Google News (e.g., company names, industry terms).
- **Example**: `AI Startup`, `Tesla`, `SpaceX`
2. **Publish_date**
- **Type**: `string`
- **Description**: Time range filter for articles.
- **Options**:
- `any time`: No restriction
- `past hours`: Breaking news
- `past 24 hours`: Daily monitoring (Recommended)
- `past week`: Short-term trends
- `past year`: Long-term research
- **Default**: `past week`
3. **Datelimit**
- **Type**: `number`
- **Description**: Maximum news items to extract.
- **Default**: `30`
- **Suggestion**: Use 10-30 for monitoring, higher for research.
## 🚀 Execution (Recommended)
Execute the following script to get results:
```bash
# Call Example
python .cursor/skills/google-news-api/scripts/google_news_api.py "Keywords" "TimeRange" Count
```
## 📊 Data Output
Successful execution returns structured data:
- `headline`: News title
- `source`: Publisher
- `news_link`: URL
- `published_time`: Timestamp
- `author`: Author name (if available)
## ⚠️ Error Handling & Retry Mechanism
1. **Check Output**:
- If output contains `"Invalid authorization"`, the API Key is invalid. **Do not retry**. Guide the user to provide a correct key.
- For other failures (e.g., `Error:` or empty results), **automatically retry once**.
2. **Retry Limit**:
- Maximum **one** automatic retry. If it still fails, stop and report the error to the user.
FILE:scripts/google_news_api.py
import os
import time
import requests
import json
import sys
# API Configuration
TEMPLATE_ID = "77638424152140851"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_news_task(api_key, keywords, date_range="past week", limit=30):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "Search_Keywords", "value": keywords},
{"name": "Publish_date", "value": date_range},
{"name": "Datelimit", "value": str(limit)}
]
}
# 1. Start Task
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}")
return None
if "id" not in res:
print(f"Error: Could not start task. Response: {res}")
return None
task_id = res["id"]
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
if status == "finished":
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.")
return None
except Exception as e:
# Silent retry on minor connection issues
pass
time.sleep(3)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# Extract data from output["string"]
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}")
return None
if __name__ == "__main__":
# Prioritize command line API key, then environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_news_api.py <keywords> [date_range] [limit]")
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.")
print("Please follow these steps:")
print("1. Go to: https://www.browseract.com/reception/integrations")
print("2. Copy your API Key.")
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).")
sys.exit(1)
keywords = sys.argv[1]
date_range = sys.argv[2] if len(sys.argv) > 2 else "past week"
limit = sys.argv[3] if len(sys.argv) > 3 else 30
result = run_google_news_task(api_key, keywords, date_range, limit)
if result:
print(result)
This skill is designed to help users automatically extract business data from Google Maps search results. When a user asks to "find coffee shops in New York," "search for dental clinics," or "extract business leads from Google Maps," the agent should proactively apply this skill.
---
name: google-maps-search-api
description: This skill is designed to help users automatically extract business data from Google Maps search results. When a user asks to "find coffee shops in New York," "search for dental clinics," or "extract business leads from Google Maps," the agent should proactively apply this skill.
---
# Google Maps Search Automation Skill
## ✨ Platform Compatibility
**✅ Works Powerfully & Reliably On All Major AI Assistants**
| Platform | Status | How to Install |
|----------|--------|----------------|
| **OpenCode** | ✅ Fully Supported | Copy skill folder to `~/.opencode/skills/` |
| **Claude Code** | ✅ Fully Supported | Native skill support |
| **Cursor** | ✅ Fully Supported | Copy to `~/.cursor/skills/` |
| **OpenClaw** | ✅ Fully Supported | Compatible |
**Why Choose BrowserAct Skills?**
- 🚀 Stable & crash-free execution
- ⚡ Fast response times
- 🔧 No configuration headaches
- 📦 Plug & play installation
- 💬 Professional support
## 📖 Introduction
This skill provides a one-stop business data collection service through the BrowserAct Google Maps Search API template. Obtain structured business data with just one command.
## 🔑 API Key Guidance
Before running, check the `BROWSERACT_API_KEY` environment variable. If it is not set, do not take further action; instead, request and wait for the user to provide it.
**The Agent must inform the user**:
> "Since you haven't configured the BrowserAct API Key, please go to the [BrowserAct Console](https://www.browseract.com/reception/integrations) to get your Key and provide it to me in this chat."
## 🛠️ Input Parameters Details
The Agent should flexibly configure the following parameters when calling the script based on user needs:
1. **KeyWords (Search Keywords)**
- **Type**: `string`
- **Description**: The keywords the user wants to search for on Google Maps.
- **Example**: `coffee`, `bakery`, `coworking space`
2. **language (UI Language)**
- **Type**: `string`
- **Description**: Sets the UI language and the language of the returned text.
- **Optional Values**: `en`, `de`, `fr`, `it`, `es`, `ja`, `zh-CN`, `zh-TW`
- **Default**: `en`
3. **country (Country/Region Bias)**
- **Type**: `string`
- **Description**: Sets the country or region bias for search results.
- **Example**: `us`, `gb`, `ca`, `au`, `de`, `fr`, `es`, `it`, `jp`
- **Default**: `us`
4. **max_dates (Maximum extraction limit)**
- **Type**: `number`
- **Description**: The maximum number of places to extract from search results.
- **Default**: `100`
## 🚀 Execution Method (Recommended)
The Agent should implement "one command for results" by executing the following independent script:
```bash
# Call example
python ./scripts/google_maps_search_api.py "KeyWords" "language" "country" max_dates
```
## 📊 Data Output Description
After successful execution, the script will directly parse and print the results from the API response. Results include:
- `name`: Business name
- `full address`: Business address
- `rating`: Average star rating
- `review count`: Number of reviews
- `price range`: Price level
- `cuisine type`: Business category
- `amenity tags`: Features like Wi-Fi, outdoor seating
- `review snippet`: Highlighted short review
- `service options`: Such as "Order online", "Dine-in"
## ⚠️ Error Handling & Retry
During script execution, if an error occurs (such as network fluctuations or task failure), the Agent should follow this logic:
1. **Check output content**:
- If the output **contains** `"Invalid authorization"`, the API Key is invalid or expired. **Do not retry**; instead, guide the user to check and provide the correct API Key.
- If the output **does not contain** `"Invalid authorization"` but the task execution fails (e.g., output starts with `Error:` or returns an empty result), the Agent should **automatically attempt to re-execute** the script once.
2. **Retry Limit**:
- Automatic retry is limited to **once**. If the second attempt still fails, stop retrying and report the specific error message to the user.
FILE:scripts/google_maps_search_api.py
import os
import time
import requests
import json
import sys
# API Configuration
TEMPLATE_ID = "77805072070738748"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
def run_google_maps_task(api_key, keywords, language="en", country="us", max_dates=100):
headers = {"Authorization": f"Bearer {api_key}"}
payload = {
"workflow_template_id": TEMPLATE_ID,
"input_parameters": [
{"name": "KeyWords", "value": keywords},
{"name": "language", "value": language},
{"name": "country", "value": country},
{"name": "TargetURL", "value": "https://www.google.com/maps"},
{"name": "max_dates", "value": str(max_dates)}
]
}
# 1. Start Task
try:
res = requests.post(f"{API_BASE_URL}/run-task-by-template", json=payload, headers=headers).json()
except Exception as e:
print(f"Error: Connection to API failed - {e}")
return None
if "id" not in res:
print(f"Error: Could not start task. Response: {res}")
return None
task_id = res["id"]
# 2. Poll for Completion
while True:
try:
status_res = requests.get(f"{API_BASE_URL}/get-task-status?task_id={task_id}", headers=headers).json()
status = status_res.get("status")
if status == "finished":
break
elif status in ["failed", "canceled"]:
print(f"Error: Task {status}. Please check your BrowserAct dashboard.")
return None
except Exception as e:
# Silent retry on minor connection issues
pass
time.sleep(3)
# 3. Get Results
try:
task_info = requests.get(f"{API_BASE_URL}/get-task?task_id={task_id}", headers=headers).json()
# Extract data from output["string"] as requested
output = task_info.get("output", {})
result_string = output.get("string")
if result_string:
return result_string
else:
return json.dumps(task_info, ensure_ascii=False)
except Exception as e:
print(f"Error: Failed to retrieve results - {e}")
return None
if __name__ == "__main__":
# Prioritize command line API key, then environment variable
api_key = os.getenv("BROWSERACT_API_KEY")
if len(sys.argv) < 2:
print("Usage: python google_maps_search_api.py <keywords> [language] [country] [max_dates]")
sys.exit(1)
if not api_key:
print("\n[!] ERROR: BrowserAct API Key is missing.")
print("Please follow these steps:")
print("1. Go to: https://www.browseract.com/reception/integrations")
print("2. Copy your API Key.")
print("3. Provide it to me or set it as an environment variable (BROWSERACT_API_KEY).")
sys.exit(1)
keywords = sys.argv[1]
language = sys.argv[2] if len(sys.argv) > 2 else "en"
country = sys.argv[3] if len(sys.argv) > 3 else "us"
max_dates = sys.argv[4] if len(sys.argv) > 4 else 100
result = run_google_maps_task(api_key, keywords, language, country, max_dates)
if result:
print(result)
Scrapes Amazon product data from ASINs using browseract.com automation API and performs surgical competitive analysis. Compares specifications, pricing, revi...
---
name: amazon-competitor-analyzer
description: Scrapes Amazon product data from ASINs using browseract.com automation API and performs surgical competitive analysis. Compares specifications, pricing, review quality, and visual strategies to identify competitor moats and vulnerabilities.
env:
- BROWSERACT_API_KEY
---
# Amazon Competitor Analyzer
This skill scrapes Amazon product data from user-provided ASINs using browseract.com's browser automation API and performs deep competitive analysis.
## When to Use This Skill
- Competitive research: Input multiple ASINs to understand market landscape
- Pricing strategy analysis: Compare price bands across similar products
- Specification benchmarking: Deep dive into technical specs and feature differences
- Review insights: Analyze review quality, quantity, and sentiment patterns
- Market opportunity discovery: Identify gaps and potential threats
## What This Skill Does
1. **ASIN Data Collection**: Extract product title, price, rating, review count, images
2. **Specification Extraction**: Deep extraction of technical specs, features, and materials
3. **Review Quality Analysis**: Analyze review patterns, keywords, and sentiment
4. **Multi-Dimensional Comparison**: Side-by-side comparison of key metrics
5. **Moat Identification**: Identify core competitive advantages and barriers
6. **Vulnerability Discovery**: Find competitor weaknesses and market opportunities
## Features
1. **Stable and accurate data extraction**: Pre-set workflows ensure consistent results.
2. **Browser automation**: Uses BrowserAct's automated browser instances for reliable data collection.
3. **Global accessibility**: BrowserAct provides servers in multiple regions.
4. **Fast execution**: Optimized workflow templates complete tasks quickly.
5. **Cost efficient**: Reduces manual research time and associated costs.
## Prerequisites
### BrowserAct.com Account Setup
You need a BrowserAct.com account and API key:
1. Visit [browseract.com](https://browseract.com)
2. Sign up for an account
3. Navigate to [API Settings](https://www.browseract.com/reception/integrations)
4. Generate an API key
### Environment Configuration
Copy the `.env.example` file to `.env` and add your API key:
```bash
cp .env.example .env
# Edit .env and replace YOUR_API_KEY_HERE with your actual API key
```
Or set as environment variable:
```bash
export BROWSERACT_API_KEY="your-api-key-here"
```
## Usage
### Basic Analysis
```bash
python amazon-competitor-analyzer/amazon_competitor_analyzer.py B09G9GB4MG
```
### Multiple Products
```bash
python amazon-competitor-analyzer/amazon_competitor_analyzer.py B09G9GB4MG B07ABC11111 B08N5WRWNW
```
### With Output Directory
```bash
python amazon-competitor-analyzer/amazon_competitor_analyzer.py B09G9GB4MG -o ./output
```
### Output Formats
- **CSV**: Structured data table
- **Markdown**: Comprehensive report
- **JSON**: Raw data with analysis
## Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| asins | string | - | One or more Amazon ASINs to analyze |
| --output, -o | string | ./output | Output directory |
| --format | string | all | Output format (csv/markdown/json/all) |
| --api-key | string | env | BrowserAct API key |
## Dependencies
This skill requires the following Python packages:
```bash
pip install requests
```
Optional (for automatic .env loading):
```bash
pip install python-dotenv
```
## Environment Variables
| Variable | Required | Description |
|----------|----------|-------------|
| BROWSERACT_API_KEY | Yes | Your BrowserAct API key. Get it from [BrowserAct Console](https://www.browseract.com/reception/integrations) |
## Error Handling
- **Invalid API Key**: Check BROWSERACT_API_KEY environment variable
- **Network Error**: Verify internet connection
- **Rate Limit**: Wait and retry with exponential backoff
- **Invalid ASIN**: Verify ASIN format (10 alphanumeric characters)
---
**Version**: 1.0.0
**Updated**: 2026-02-09
**Template ID**: `77814333389670716`
FILE:amazon_competitor_analyzer.py
"""
Amazon Competitor Analyzer Skill
===============================
Scrapes Amazon product data from ASINs using BrowserAct API
and performs surgical competitive analysis.
Author: OpenCode
Version: 1.0.0
"""
import os
import sys
import json
import time
import csv
import requests
from datetime import datetime
from typing import Dict, List, Optional, Any
from pathlib import Path
# Try to load .env file if python-dotenv is available
try:
from dotenv import load_dotenv
# Load .env from same directory as script
script_dir = Path(__file__).parent
env_file = script_dir / ".env"
if env_file.exists():
load_dotenv(env_file)
except ImportError:
# If python-dotenv not available, check .env manually
script_dir = Path(__file__).parent
env_file = script_dir / ".env"
if env_file.exists():
with open(env_file) as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
os.environ.setdefault(key, value.strip())
# Configuration
BROWSERACT_API_KEY = os.getenv("BROWSERACT_API_KEY", "")
WORKFLOW_TEMPLATE_ID = "77814333389670716"
API_BASE_URL = "https://api.browseract.com/v2/workflow"
class AmazonCompetitorAnalyzer:
"""Main class for Amazon competitive analysis"""
def __init__(self, api_key: str = None, workflow_template_id: str = None):
"""Initialize the analyzer with API credentials"""
self.api_key = api_key or BROWSERACT_API_KEY
self.workflow_template_id = workflow_template_id or WORKFLOW_TEMPLATE_ID
self.headers = {
"Authorization": f"Bearer {self.api_key}"
}
def validate_asin(self, asin: str) -> bool:
"""Validate ASIN format"""
return len(asin) == 10 and asin.isalnum()
def extract_asins_from_text(self, text: str) -> List[str]:
"""Extract ASINs from user input text"""
import re
# Match 10-character alphanumeric strings starting with B0 or similar
asin_pattern = r'\b[B0][A-Z0-9]{9}\b'
asins = re.findall(asin_pattern, text.upper())
return list(set(asins)) # Remove duplicates
def submit_task(self, asin: str) -> Optional[str]:
"""Submit scraping task for a single ASIN"""
if not self.validate_asin(asin):
print(f"Invalid ASIN: {asin}")
return None
data = {
"workflow_template_id": self.workflow_template_id,
"input_parameters": [{"name": "ASIN", "value": asin}]
}
try:
response = requests.post(
f"{API_BASE_URL}/run-task-by-template",
json=data,
headers=self.headers,
timeout=30
)
if response.status_code == 200:
result = response.json()
task_id = result.get("id")
return task_id
else:
print(f"Failed to submit task for {asin}: {response.json().get('msg', 'Unknown error')}")
return None
except Exception as e:
print(f"Error submitting task for {asin}: {e}")
return None
def wait_for_task(self, task_id: str, timeout: int = 300) -> bool:
"""Wait for task completion"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
response = requests.get(
f"{API_BASE_URL}/get-task-status?task_id={task_id}",
headers=self.headers,
timeout=10
)
if response.status_code == 200:
status = response.json().get("status")
if status == "finished":
return True
elif status in ["failed", "canceled"]:
return False
time.sleep(3)
except Exception:
time.sleep(5)
return False
def get_results(self, task_id: str) -> Optional[Dict]:
"""Get task results"""
try:
response = requests.get(
f"{API_BASE_URL}/get-task?task_id={task_id}",
headers=self.headers,
timeout=30
)
if response.status_code == 200:
return response.json()
except Exception as e:
print(f"Error getting results: {e}")
return None
def scrape_product(self, asin: str, wait_timeout: int = 300) -> Optional[Dict]:
"""Scrape a single product"""
# Submit task
task_id = self.submit_task(asin)
if not task_id:
return None
# Wait for completion
if not self.wait_for_task(task_id, wait_timeout):
return None
# Get results
results = self.get_results(task_id)
return results
def scrape_multiple_products(self, asins: List[str], delay: int = 5) -> Dict[str, Any]:
"""Scrape multiple products"""
results = {}
for asin in asins:
print(f"Processing: {asin}")
data = self.scrape_product(asin)
results[asin] = data
if delay > 0 and asin != asins[-1]:
time.sleep(delay)
return results
def analyze_competitive_position(self, products: Dict[str, Any]) -> Dict[str, Any]:
"""Analyze competitive positioning"""
analysis = {
"price_analysis": {},
"rating_analysis": {},
"market_leaders": {},
"opportunities": []
}
prices = []
ratings = []
for asin, data in products.items():
if data:
try:
product = data.get('results', {}).get('products', [{}])[0]
price = product.get('pricing', {}).get('current_price', 0)
rating = product.get('reviews', {}).get('average_rating', 0)
reviews = product.get('reviews', {}).get('total_count', 0)
brand = product.get('product_info', {}).get('brand', asin)
prices.append((asin, price, brand))
ratings.append((asin, rating, reviews, brand))
except Exception:
pass
# Sort by price
prices.sort(key=lambda x: x[1])
if prices:
analysis["price_analysis"]["lowest"] = prices[0]
analysis["price_analysis"]["highest"] = prices[-1]
analysis["price_analysis"]["range"] = prices[-1][1] - prices[0][1]
# Sort by rating
ratings.sort(key=lambda x: x[1], reverse=True)
if ratings:
analysis["rating_analysis"]["top_rated"] = ratings[0]
analysis["rating_analysis"]["by_volume"] = sorted(ratings, key=lambda x: x[2], reverse=True)
return analysis
def generate_csv_report(self, products: Dict[str, Any], output_path: str):
"""Generate CSV report"""
with open(output_path, 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow([
'ASIN', 'Product Title', 'Brand', 'Price ($)', 'Original Price ($)',
'Discount (%)', 'Rating', 'Reviews Count', 'Weight', 'Features'
])
for asin, data in products.items():
if data:
try:
product = data.get('results', {}).get('products', [{}])[0]
writer.writerow([
asin,
product.get('product_info', {}).get('title', 'N/A')[:100],
product.get('product_info', {}).get('brand', 'N/A'),
product.get('pricing', {}).get('current_price', 'N/A'),
product.get('pricing', {}).get('original_price', 'N/A'),
product.get('pricing', {}).get('discount_percent', 'N/A'),
product.get('reviews', {}).get('average_rating', 'N/A'),
product.get('reviews', {}).get('total_count', 'N/A'),
product.get('specifications', {}).get('weight', 'N/A'),
', '.join(product.get('specifications', {}).get('features', [])[:5])
])
except:
writer.writerow([asin, 'Error', '', '', '', '', '', '', '', ''])
else:
writer.writerow([asin, 'Failed', '', '', '', '', '', '', '', ''])
print(f"CSV report saved: {output_path}")
def generate_markdown_report(self, products: Dict[str, Any], output_path: str):
"""Generate comprehensive markdown report"""
with open(output_path, 'w', encoding='utf-8') as f:
f.write("# Amazon Competitive Analysis Report\n\n")
f.write(f"**Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write(f"**Products Analyzed:** {len(products)}\n\n")
# Summary table
f.write("## Data Summary\n\n")
f.write("| ASIN | Brand | Price | Rating | Reviews |\n")
f.write("|------|-------|-------|--------|---------|\n")
for asin, data in products.items():
if data:
try:
product = data.get('results', {}).get('products', [{}])[0]
info = product.get('product_info', {})
pricing = product.get('pricing', {})
reviews = product.get('reviews', {})
f.write(f"| {asin} | {info.get('brand', 'N/A')} | "
f"pricing.get('current_price', 'N/A') | "
f"{reviews.get('average_rating', 'N/A')}/5 | "
f"{reviews.get('total_count', 'N/A'):,} |\n")
except:
f.write(f"| {asin} | Error | - | - | - |\n")
else:
f.write(f"| {asin} | Failed | - | - | - |\n")
# Detailed analysis
f.write("\n## Detailed Analysis\n\n")
competitive_analysis = self.analyze_competitive_position(products)
f.write("### Price Positioning\n")
if competitive_analysis.get("price_analysis"):
pa = competitive_analysis["price_analysis"]
if "lowest" in pa:
f.write(f"- Lowest Price: {pa['lowest'][2]} at pa['lowest'][1]\n")
if "highest" in pa:
f.write(f"- Highest Price: {pa['highest'][2]} at pa['highest'][1]\n")
f.write("\n### Rating Leaders\n")
if competitive_analysis.get("rating_analysis"):
ra = competitive_analysis["rating_analysis"]
if "top_rated" in ra:
f.write(f"- Highest Rated: {ra['top_rated'][3]} at {ra['top_rated'][1]}/5\n")
f.write("\n---\n")
f.write(f"*Generated by Amazon Competitor Analyzer*\n")
print(f"Markdown report saved: {output_path}")
def generate_json_report(self, products: Dict[str, Any], output_path: str):
"""Generate JSON report"""
report_data = {
"generated_at": datetime.now().isoformat(),
"products_analyzed": len(products),
"products": products,
"analysis": self.analyze_competitive_position(products)
}
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(report_data, f, indent=2, ensure_ascii=False)
print(f"JSON report saved: {output_path}")
def analyze_asins(asins: List[str], output_dir: str = None) -> Dict[str, Any]:
"""Main function to analyze multiple ASINs"""
analyzer = AmazonCompetitorAnalyzer()
print(f"Analyzing {len(asins)} ASINs...")
# Scrape products
products = analyzer.scrape_multiple_products(asins)
# Generate reports if output directory specified
if output_dir:
os.makedirs(output_dir, exist_ok=True)
base_path = os.path.join(output_dir, "amazon_analysis")
analyzer.generate_csv_report(products, f"{base_path}.csv")
analyzer.generate_markdown_report(products, f"{base_path}.md")
analyzer.generate_json_report(products, f"{base_path}.json")
return products
def main():
"""CLI entry point"""
import argparse
parser = argparse.ArgumentParser(description="Amazon Competitor Analyzer")
parser.add_argument("asins", nargs="+", help="ASINs to analyze")
parser.add_argument("-o", "--output", default=".", help="Output directory")
parser.add_argument("-k", "--api-key", help="BrowserAct API key")
args = parser.parse_args()
# Initialize with custom API key if provided
if args.api_key:
global BROWSERACT_API_KEY
BROWSERACT_API_KEY = args.api_key
# Run analysis
products = analyze_asins(args.asins, args.output)
print(f"\nAnalysis complete! Analyzed {len(products)} products.")
if __name__ == "__main__":
main()