To page yourself when you lose the Amazon Buy Box, poll /api/amazon-product-offers, confirm the loss on two consecutive checks so a single flaky read never fires an incident, then POST a trigger event to PagerDuty's Events API v2 at https://events.pagerduty.com/v2/enqueue. The same ASIN always gets the same dedup_key, so when you win the Buy Box back, a resolve event with that key closes the exact incident PagerDuty opened for it - never a second one, and never a dangling open incident either.
Key Takeaways
- The Events API v2 integration key goes in the request body as routing_key, not in a header; it belongs to one PagerDuty service's Events API v2 integration, not your PagerDuty user.
- dedup_key is what makes this idempotent: the SAME key on trigger and resolve lets PagerDuty correlate them into one incident lifecycle, documented behaviour of the Events API v2.
- A trigger event needs a payload block (summary, severity, source); a resolve event must NOT include one - PagerDuty's own schema marks payload as only required for a new/updated alert.
- A successful enqueue returns HTTP 202, not 200 - the event is accepted for async processing, not necessarily turned into a visible incident yet.
- The Events API has its own rate limit, separate from and far tighter than the general PagerDuty REST API - a poller checking many ASINs on a short interval can hit it.
Why PagerDuty instead of a Slack or SMS message?
A Slack or SMS alert is fire-and-forget: it tells you something happened, but nothing tracks whether anyone saw it, and nothing clears itself when the problem goes away (see the Slack Buy Box alert and its SMS counterpart for that pattern). PagerDuty is built around an incident LIFECYCLE: an open incident has a state (triggered, acknowledged, resolved), an assigned on-call responder, and a notification policy (push, SMS, phone call) that escalates if nobody acknowledges it. For a Buy Box loss that directly costs sales, that escalation path is the point - a message nobody reads for six hours is a six-hour gap a self-resolving PagerDuty incident does not have.
How does the trigger/resolve lifecycle work?
| event_action | Sent by this script when | What PagerDuty does |
|---|---|---|
| trigger | a confirmed Buy Box loss (2 consecutive polls) | opens a NEW incident, or re-notifies an existing one with the same dedup_key |
| resolve | a confirmed Buy Box recovery (2 consecutive polls) | auto-resolves the incident PagerDuty already grouped under that dedup_key |
| acknowledge | not sent by this script | a human clicking Acknowledge in PagerDuty, or a separate on-call tool |
check() only returns an action once a reading repeats for CONFIRM = 2 consecutive polls, the same confirm-before-alert pattern used in the Slack and SMS alert scripts. The difference here is what happens afterwards: the script remembers it already triggered (alerted = True) so a Buy Box that keeps flapping between two rival sellers never re-opens the incident on every poll - it only sends resolve once you are confirmed back, then can trigger again cleanly on the next confirmed loss.
buybox_pagerduty_alert.py - confirm twice, then trigger or resolve by dedup_key
"""Open a PagerDuty incident when you lose the Buy Box, and resolve it yourself when you get it back.
Uses only the real sellermagnet.py / retry.py helpers (see the Python quickstart) for SellerMagnet calls.
PagerDuty Events API v2 calls go straight through requests.post - there is no official PagerDuty client here.
"""
import json
import os
import re
import time
import requests
from retry import get_with_retry
from sellermagnet import ApiError, new_session
MARKETPLACE_ID = "ATVPDKIKX0DER" # amazon.com
MY_SELLER_ID = os.environ["MY_SELLER_ID"] # your sellerId as it appears in offers[]; no default on purpose
ASINS = ["B0CL61F39H", "B0EXAMPLE2", "B0EXAMPLE3"]
CONFIRM = 2 # same reading on 2 checks in a row before paging
STATE_FILE = "buybox_state.json"
ASIN_RE = re.compile(r"\A[A-Z0-9]{10}\Z") # offers calls are billed even for a typo, so filter first
PD_EVENTS_URL = "https://events.pagerduty.com/v2/enqueue"
PD_ROUTING_KEY = os.environ["PAGERDUTY_ROUTING_KEY"] # the Events API v2 integration key, not an API token
PD_RETRYABLE = {429, 500, 502, 503}
def read_buy_box(session, asin: str) -> tuple[str, str]:
"""('mine' | 'lost' | 'suppressed' | 'no-offers', detail for the event payload)."""
data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=MARKETPLACE_ID)
box = data.get("buyBox") or {}
if not box:
# {} has two causes: offers exist but Amazon features none, or no offer at all (or none parsable)
return ("suppressed", "") if data.get("buyBoxSuppressed") else ("no-offers", "")
holder = box.get("sellerId") or "unknown"
if holder == MY_SELLER_ID:
return "mine", ""
currency = (data.get("currency") or {}).get("code", "")
detail = f"{box.get('sellerName', '?')} ({holder}, {box.get('fulfillmentType', '?')})"
if isinstance(box.get("totalPrice"), (int, float)): # price + shipping as floats, not rounded by the API
detail += f" at {box['totalPrice']:.2f} {currency}"
mine = [o["totalPrice"] for o in data.get("offers") or []
if o.get("sellerId") == MY_SELLER_ID and isinstance(o.get("totalPrice"), (int, float))]
detail += f", yours {min(mine):.2f}" if mine else "" # keep the summary short
return "lost", detail # any other holder is the same reading: a rotation still confirms
def load_state() -> dict:
try:
with open(STATE_FILE) as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_state(state: dict) -> None:
with open(STATE_FILE, "w") as f:
json.dump(state, f)
def check(state: dict, asin: str, key: str, detail: str) -> tuple[str, str] | None:
"""Advance the per-ASIN streak; return (action, detail) only once a reading repeats CONFIRM times.
action is 'trigger' the first confirmed loss, 'resolve' the first confirmed recovery; a streak that
just repeats an already-alerted state returns None, so the same incident is never re-triggered."""
entry = state.get(asin, {"streak_key": None, "streak": 0, "alerted": False})
if key == entry["streak_key"]:
entry["streak"] += 1
else:
entry = {"streak_key": key, "streak": 1, "alerted": entry["alerted"]} # keep 'alerted' across a reset
state[asin] = entry
if entry["streak"] < CONFIRM:
return None
if key == "mine":
if entry["alerted"]:
entry["alerted"] = False
return "resolve", ""
return None
if key == "lost" and not entry["alerted"]:
entry["alerted"] = True
return "trigger", detail
return None # suppressed/no-offers never pages; only a confirmed rival does
def dedup_key(asin: str) -> str:
return f"buybox:{MY_SELLER_ID}:{asin}" # same key for trigger + resolve
def send_event(action: str, asin: str, detail: str, attempts: int = 4) -> dict:
"""POST one alert event to the Events API v2 enqueue endpoint. 429/5xx are safe to retry; a 400 is not -
it means the payload itself is malformed and retrying sends the same bad payload again."""
payload = {
"routing_key": PD_ROUTING_KEY,
"event_action": action,
"dedup_key": dedup_key(asin),
}
if action == "trigger":
payload["payload"] = {
"summary": f"Buy Box lost on {asin}: {detail}" if detail else f"Buy Box lost on {asin}",
"source": asin,
"severity": "warning",
"component": "buybox-monitor",
"group": "amazon-pricing",
"custom_details": {"asin": asin, "holder": detail or "unknown"},
}
last = {"accepted": False, "status": None, "pd_status": None, "message": "no attempt made"}
for attempt in range(1, attempts + 1):
resp = requests.post(PD_EVENTS_URL, json=payload, timeout=15)
try:
body = resp.json()
except ValueError:
body = {}
if resp.status_code == 202:
return {"accepted": True, "status": 202, "pd_status": body.get("status"),
"dedup_key": body.get("dedup_key"), "message": body.get("message")}
last = {"accepted": False, "status": resp.status_code, "pd_status": body.get("status"),
"message": body.get("message", "request failed")}
if resp.status_code not in PD_RETRYABLE or attempt == attempts:
return last
time.sleep(min(2 ** attempt, 60))
return last
def main() -> None:
session = new_session()
state = load_state()
events: list[tuple[str, str, str]] = []
for asin in ASINS:
if not ASIN_RE.match(asin):
print(f"SKIP {asin}: not a well-formed ASIN, not billed")
continue
try:
key, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
print(f"STOP: {err.status} on {asin}, run ended early (free, not billed)")
break
print(f"SKIP {asin}: {err.status} {err}") # 404 billed-not-retried, 502/503 billed-and-capped
continue
result = check(state, asin, key, detail)
if result:
events.append((asin, *result))
save_state(state)
if not events:
print(f"{len(ASINS)} checked, 0 PagerDuty events sent")
return
for asin, action, detail in events:
result = send_event(action, asin, detail)
if result["accepted"]:
print(f"[pagerduty] {action} {asin}: accepted dedup_key={result['dedup_key']} "
f"status={result['pd_status']}")
else:
print(f"[pagerduty] {action} {asin}: NOT accepted HTTP {result['status']} "
f"pd_status={result.get('pd_status')} {result.get('message')}")
print(f"{len(ASINS)} checked, {len(events)} event(s) sent")
if __name__ == "__main__":
main()
What this script POSTs to events.pagerduty.com/v2/enqueue on a confirmed loss
{
"routing_key": "YOUR_EVENTS_API_V2_INTEGRATION_KEY",
"event_action": "trigger",
"dedup_key": "buybox:A1MYSELLERID:B0EXAMPLE2",
"payload": {
"summary": "Buy Box lost on B0EXAMPLE2: Rival Co (RIVAL1, FBA) at 19.99 USD",
"source": "B0EXAMPLE2",
"severity": "warning",
"component": "buybox-monitor",
"group": "amazon-pricing",
"custom_details": {"asin": "B0EXAMPLE2", "holder": "Rival Co (RIVAL1, FBA) at 19.99 USD"}
}
}
Output across five polls (illustrative ASINs and sellers)
--- run 1 (all three hold the Buy Box)
3 checked, 0 PagerDuty events sent
--- run 2: B0EXAMPLE2 loses the Buy Box (1st sighting, not confirmed yet)
3 checked, 0 PagerDuty events sent
--- run 3: same reading confirmed, PagerDuty incident triggered
[pagerduty] trigger B0EXAMPLE2: accepted dedup_key=buybox:A1MYSELLERID:B0EXAMPLE2 status=success
3 checked, 1 event(s) sent
--- run 4: B0EXAMPLE2 is back (1st sighting, not confirmed yet)
3 checked, 0 PagerDuty events sent
--- run 5: back-in-stock confirmed, PagerDuty incident resolved
[pagerduty] resolve B0EXAMPLE2: accepted dedup_key=buybox:A1MYSELLERID:B0EXAMPLE2 status=success
3 checked, 1 event(s) sent


| Field | trigger | resolve |
|---|---|---|
| dedup_key | same string both times: f"buybox:{seller_id}:{asin}" | the only field that links trigger to resolve |
| payload block | required on trigger | omitted entirely on resolve - PagerDuty rejects one present on a resolve |
| severity | set on trigger (warning) | not applicable to resolve |
Don't let a short poll interval outrun the Events API's own rate limit
The Events API v2 enforces its own per-integration-key rate limit, separate from and far tighter than the general PagerDuty REST API limit, and a 429 here means the event may not have been accepted at all. Polling more than a handful of ASINs on a short interval through one routing key can reach it; the fix is the same PD_RETRYABLE backoff already in send_event(), not a shorter retry loop. A malformed payload comes back as 400, not 429 - retrying a 400 just resends the same bad payload, so it is deliberately excluded from the retry set.
What does this mean for a seller running this unattended?
An incident that nobody ever has to remember to close by hand is the actual win here: the same streak-and-alerted-flag state this script already keeps for the Slack and SMS versions is enough to drive a full open/close lifecycle instead of a one-way message. Point the escalation policy on the PagerDuty service at whoever actually repriced the SKU, not a shared inbox - the offer listing API guide covers reading every seller and price on the listing if the incident needs more context than the one-line summary carries.
Frequently Asked Questions
Does PagerDuty confirm the incident was created, or just that the event was accepted?
Just accepted. A 202 with status success means the Events API v2 queued the event for processing, which is asynchronous - it is not a guarantee the incident is visible yet.
What happens if I send a resolve for a dedup_key that was never triggered?
PagerDuty documents dedup_key as required for acknowledge and resolve, used to identify which alert to act on; sending one with no matching open alert is a no-op rather than an error in this script's scope - it is not tested here, so treat an unmatched resolve as unverified behaviour.
Can I reuse the same dedup_key for two different ASINs?
Don't - PagerDuty groups events by dedup_key into one incident, so two ASINs sharing a key would resolve or re-trigger each other's incident. This script keys it as buybox:{seller_id}:{asin} specifically to keep every ASIN's lifecycle independent.
Is the routing_key the same as my PagerDuty API token?
No. routing_key is the integration key for one service's Events API v2 integration, created in that service's Integrations tab; it has no access to the REST API and cannot read or change anything else in the account.
Why does the payload block appear on trigger but not on resolve in the example?
PagerDuty's own schema lists payload as required for an alert event, which a resolve is not creating or updating - sending one anyway is unnecessary and this script never does.
Bottom line: confirm twice, trigger with a payload, resolve with just the dedup_key, and let PagerDuty's own escalation policy do the paging. One /amazon-product-offers poll costs one credit per ASIN; a free account includes 150 credits, enough to watch dozens of ASINs through several confirm cycles before deciding on a polling interval. The error-handling guide covers the SellerMagnet side of the retry policy used here in more depth.