前言
本文实现一套完整的亚马逊竞品价格监控与告警系统,具备以下能力:
- 10分钟级采集频率,接近实时感知竞品价格变化
- AI Agent 分析层(OpenClaw),自动生成价格变化背景分析
- 飞书 + Slack 双渠道推送,告警直达工作群
- 完整可运行代码,5分钟内配置完成
适合读者:亚马逊卖家/运营团队中有一定Python基础的成员,或需要构建价格监控基础设施的开发者。

技术栈
| 组件 | 用途 |
|---|---|
| Python 3.9+ | 主逻辑语言 |
| Pangolinfo Scrape API | 亚马逊ASIN数据采集 |
| OpenClaw | AI Agent框架,价格分析与建议生成 |
| APScheduler | 定时任务调度(10分钟轮询) |
| 飞书 Webhook | 告警消息推送 |
| Slack Webhook | 告警消息推送(可选) |
| python-dotenv | 环境变量管理 |
系统架构
[亚马逊商品页面]
↓ 每10分钟
[Pangolinfo Scrape API] ← 结构化JSON,含Buybox/Offer数据
↓
[价格差分比对模块] ← 与上次快照对比,计算变化幅度
↓ 超过阈值
[OpenClaw AI Agent] ← 生成竞争态势分析 + 应对建议
↓
[飞书 Bot Webhook] → 告警卡片发送至运营群
[Slack Webhook] → 同步发送至Slack频道(可选)
第一步:环境安装与配置
pip install openclaw requests apscheduler python-dotenv
创建 .env 文件:
PANGOLINFO_API_KEY=your_pangolinfo_api_key
MY_SELLER_ID=your_amazon_seller_account_id
FEISHU_WEBHOOK_URL=https://open.feishu.cn/open-apis/bot/v2/hook/YOUR_TOKEN
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/SLACK/PATH
获取 Pangolinfo API Key:登录 Pangolinfo API 控制台→ API管理 → 创建Key 或者使用 API 请求 Key。
第二步:数据采集模块
# price_collector.py
import requests
from datetime import datetime
from typing import Optional, List
PANGOLINFO_API_URL = "https://api.pangolinfo.com/v1/amazon/product"
def fetch_asin_data(asin: str, api_key: str, marketplace: str = "US") -> Optional[dict]:
"""
调用 Pangolinfo Scrape API 获取 ASIN 完整商品数据
返回字段包含:
- buybox_price: 当前 Buybox 价格
- buybox_seller: Buybox 卖家名称/ID
- all_offers: 所有卖家报价列表(含FBA/FBM标识)
- in_stock: 库存状态
"""
resp = requests.post(
PANGOLINFO_API_URL,
headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
json={
"asin": asin,
"marketplace": marketplace,
"parse": True,
"include_offers": True,
"include_buybox": True
},
timeout=30
)
resp.raise_for_status()
raw = resp.json()
return {
"asin": asin,
"collected_at": datetime.utcnow().isoformat() + "Z",
"buybox_price": raw.get("buybox", {}).get("price"),
"buybox_seller_name": raw.get("buybox", {}).get("seller_name"),
"buybox_seller_id": raw.get("buybox", {}).get("seller_id"),
"buybox_is_fba": raw.get("buybox", {}).get("is_fba"),
"all_offers": raw.get("offers", []),
"product_title": raw.get("title", ""),
"in_stock": raw.get("availability") == "In Stock"
}
def batch_fetch(asin_list: List[str], api_key: str) -> List[dict]:
"""批量采集,包含异常处理"""
results = []
for asin in asin_list:
try:
data = fetch_asin_data(asin, api_key)
results.append(data)
print(f"[OK] {asin}: ${data['buybox_price']} | {data['buybox_seller_name']}")
except Exception as e:
print(f"[FAIL] {asin}: {e}")
return results
关键说明:
parse=True:让API返回结构化JSON而非原始HTML,节省解析工作include_offers=True:获取所有卖家报价,而非仅Buybox价格- 超时设置30秒,防止单个请求阻塞整个采集周期
第三步:OpenClaw AI Agent 分析模块
# price_analyzer.py
from openclaw import Agent, Task
from typing import Optional, List
import json
class CompetitorPriceAnalyzer:
"""
基于 OpenClaw Agent 的竞品价格分析器
功能:
1. 差分比对:识别价格变化
2. 阈值判断:过滤噪声波动
3. AI分析:生成竞争背景摘要
4. 历史追踪:记录每次调价事件
"""
DEFAULT_ALERT_THRESHOLD = 5.0 # 触发告警的最低降幅百分比
def __init__(self,
my_seller_id: str = "",
alert_threshold_pct: float = DEFAULT_ALERT_THRESHOLD):
self.my_seller_id = my_seller_id
self.threshold = alert_threshold_pct
self._price_baseline: dict = {} # {asin: {price, seller, history}}
# 初始化 OpenClaw AI Agent
self.agent = Agent(
name="PriceAnalyst",
role="亚马逊竞争定价分析专家",
goal="快速识别竞品调价威胁,给出精准的竞争态势判断和应对建议",
backstory=(
"你是资深的亚马逊运营专家,有10年以上跨境电商竞品分析经验,"
"擅长识别价格战信号并制定快速响应策略"
)
)
def check(self, snapshot: dict) -> Optional[dict]:
"""
检查当前快照是否需要触发告警
Returns:
告警事件字典(需告警),或 None(无需告警)
"""
asin = snapshot["asin"]
curr_price = snapshot.get("buybox_price")
curr_seller_id = snapshot.get("buybox_seller_id")
# 跳过无效价格
if curr_price is None:
return None
# 初始化基准
if asin not in self._price_baseline:
self._price_baseline[asin] = {
"price": curr_price,
"seller_id": curr_seller_id,
"history": []
}
print(f"[INIT] {asin} 基准价格: ${curr_price}")
return None
baseline = self._price_baseline[asin]
prev_price = baseline["price"]
# 计算变化幅度
if prev_price <= 0:
return None
change_pct = (curr_price - prev_price) / prev_price * 100
# 判断是否为竞品行为(排除自己账号)
is_competitor_action = curr_seller_id != self.my_seller_id
# 触发条件:降价超过阈值 + 竞品行为
if change_pct <= -self.threshold and is_competitor_action:
ai_analysis = self._generate_analysis(snapshot, prev_price, change_pct, baseline)
# 记录历史
baseline["history"].append({
"from": prev_price,
"to": curr_price,
"pct": change_pct,
"ts": snapshot["collected_at"]
})
alert_event = {
"priority": "HIGH" if abs(change_pct) >= 10 else "MEDIUM",
"asin": asin,
"title": snapshot.get("product_title", "")[:60],
"competitor_seller": snapshot.get("buybox_seller_name"),
"price_from": prev_price,
"price_to": curr_price,
"change_pct": change_pct,
"historical_changes": len(baseline["history"]),
"ai_analysis": ai_analysis,
"detected_at": snapshot["collected_at"]
}
# 更新基准
baseline["price"] = curr_price
baseline["seller_id"] = curr_seller_id
return alert_event
# 无需告警,更新基准
baseline["price"] = curr_price
return None
def _generate_analysis(self, snapshot: dict, prev_price: float,
change_pct: float, baseline: dict) -> str:
"""调用 OpenClaw Agent 生成竞争态势分析"""
task = Task(
description=f"""
分析以下亚马逊竞品调价事件,输出简洁的中文竞争态势分析(不超过80字):
ASIN: {snapshot['asin']}
当前竞品卖家: {snapshot.get('buybox_seller_name')}
FBA卖家: {snapshot.get('buybox_is_fba')}
降价幅度: {abs(change_pct):.1f}%(${prev_price:.2f} → ${snapshot['buybox_price']:.2f})
历史调价次数: {len(baseline.get('history', []))}
市场库存状态: {snapshot.get('in_stock')}
""",
expected_output="80字以内的竞争分析,包含威胁等级和推荐第一步应对动作"
)
return self.agent.execute_task(task)
技术亮点:
- 通过
my_seller_id过滤掉自己账号的价格变化,只关注真实竞品动作 - OpenClaw Agent 接收历史调价次数作为上下文,使分析更有参考价值
change_pct <= -threshold只在降价时告警,涨价不触发(可按需修改)
第四步:告警推送模块
# notifier.py
import requests
from typing import Optional
class MultiChannelNotifier:
"""支持飞书 + Slack 双渠道推送"""
def __init__(self, feishu_webhook: str = "", slack_webhook: str = ""):
self.feishu = feishu_webhook
self.slack = slack_webhook
def notify(self, event: dict):
"""向所有配置渠道发送告警"""
results = {}
if self.feishu:
results["feishu"] = self._send_feishu(event)
if self.slack:
results["slack"] = self._send_slack(event)
status = " | ".join(f"{k}: {'✅' if v else '❌'}" for k, v in results.items())
print(f"[ALERT] {event['asin']} 降价{abs(event['change_pct']):.1f}% → {status}")
def _send_feishu(self, event: dict) -> bool:
color = "red" if event["priority"] == "HIGH" else "orange"
payload = {
"msg_type": "interactive",
"card": {
"header": {
"title": {"content": f"🚨 竞品降价 | ASIN: {event['asin']}", "tag": "plain_text"},
"template": color
},
"elements": [{
"tag": "div",
"text": {
"tag": "larkmd",
"content": (
f"**商品**: {event['title']}\n"
f"**竞品卖家**: {event['competitor_seller']}\n"
f"**价格变化**: ${event['price_from']:.2f} → **${event['price_to']:.2f}**\n"
f"**降幅**: {abs(event['change_pct']):.1f}% | "
f"历史调价: {event['historical_changes']}次\n"
f"**分析**: {event['ai_analysis']}"
)
}
}, {
"tag": "action",
"actions": [{
"tag": "button",
"text": {"content": "查看价格走势", "tag": "plain_text"},
"type": "primary",
"url": f"https://tool.pangolinfo.com/tracking/{event['asin']}"
}]
}]
}
}
resp = requests.post(self.feishu, json=payload, timeout=10)
return resp.status_code == 200
def _send_slack(self, event: dict) -> bool:
emoji = "🔴" if event["priority"] == "HIGH" else "🟡"
payload = {
"blocks": [
{"type": "header", "text": {"type": "plain_text",
"text": f"{emoji} Competitor Price Drop | {event['asin']}"}},
{"type": "section", "fields": [
{"type": "mrkdwn", "text": f"*Competitor:*\n{event['competitor_seller']}"},
{"type": "mrkdwn",
"text": f"*Price:*\n${event['price_from']:.2f} → ${event['price_to']:.2f} ({abs(event['change_pct']):.1f}%)"}
]},
{"type": "section",
"text": {"type": "mrkdwn", "text": f"*Analysis:* {event['ai_analysis']}"}},
]
}
resp = requests.post(self.slack, json=payload, timeout=10)
return resp.status_code == 200
第五步:主程序入口
# main.py
import os
from dotenv import load_dotenv
from apscheduler.schedulers.blocking import BlockingScheduler
from price_collector import batch_fetch
from price_analyzer import CompetitorPriceAnalyzer
from notifier import MultiChannelNotifier
load_dotenv()
# 配置
API_KEY = os.getenv("PANGOLINFO_API_KEY")
MY_SELLER_ID = os.getenv("MY_SELLER_ID", "")
FEISHU_WEBHOOK = os.getenv("FEISHU_WEBHOOK_URL", "")
SLACK_WEBHOOK = os.getenv("SLACK_WEBHOOK_URL", "")
MONITOR_ASINS = [ # 在这里添加你要监控的竞品ASIN
"B0D6BFMNN5",
"B08K2S9X7Q",
]
POLL_INTERVAL = 10 # 采集间隔(分钟)
ALERT_THRESHOLD = 5.0 # 告警阈值(降幅百分比)
# 初始化模块
analyzer = CompetitorPriceAnalyzer(my_seller_id=MY_SELLER_ID, alert_threshold_pct=ALERT_THRESHOLD)
notifier = MultiChannelNotifier(feishu_webhook=FEISHU_WEBHOOK, slack_webhook=SLACK_WEBHOOK)
def monitoring_cycle():
print(f"\n{'─'*40}")
snapshots = batch_fetch(MONITOR_ASINS, API_KEY)
for snapshot in snapshots:
alert = analyzer.check(snapshot)
if alert:
notifier.notify(alert)
print(f"[DONE] {len(snapshots)} ASINs checked")
if __name__ == "__main__":
print(f"🚀 监控启动 | {len(MONITOR_ASINS)} ASINs | 每{POLL_INTERVAL}分钟")
monitoring_cycle() # 立即执行一次初始化
scheduler = BlockingScheduler()
scheduler.add_job(monitoring_cycle, 'interval', minutes=POLL_INTERVAL)
scheduler.start()
常见问题
Q: API被限速了怎么办?
A: Pangolinfo API 有并发限制,批量采集时建议在请求之间加 time.sleep(1),或者使用异步并发但控制最大并发数为5-10。
Q: OpenClaw连接失败?
A: 检查 OpenClaw 的 LLM 配置文件(~/.openclaw/config.yaml),确保已正确配置模型API Key。
Q: 告警太多(噪声)?
A: 提高阈值(改 ALERT_THRESHOLD),或者在 _price_baseline 里增加告警冷却逻辑(同一ASIN两次告警间隔最少2小时)。
Q: 想要更简单的方案?
A: 直接用 AMZ Data Tracker 的可视化界面配置,不需要写任何代码。
总结
核心要点:
- Pangolinfo Scrape API 提供稳定的结构化ASIN数据,屏蔽爬虫复杂性
- OpenClaw Agent 在价格告警的基础上增加了AI分析层,提升告警的决策价值
- 飞书+Slack双渠道确保告警必达工作群
- APScheduler 10分钟轮询是数据时效与API成本的最优平衡点
780

被折叠的 条评论
为什么被折叠?



