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 opens an incident, then POST a critical event to Zenduty's Events API at https://events.zenduty.com/api/events/<integration-key>/. The same ASIN always gets the same entity_id, and Zenduty's own documentation states that alerts are bound into incidents by their entity ID - so when you win the Buy Box back, a resolved event with that same entity_id closes the exact incident it opened, never a second one.
Key Takeaways
- The integration key lives in the URL path (events.zenduty.com/api/events/<key>/), not in a request header - it belongs to one service's Events API integration, not your Zenduty login.
- entity_id is what makes this idempotent: Zenduty's docs state alerts are bound into incidents by their entity ID, so the SAME id on the critical and resolved calls keeps both events on one incident instead of opening a new one each time.
- alert_type is a required field with six documented values (critical, acknowledged, resolved, error, warning, info) - this script only ever sends critical and resolved.
- A successful call returns HTTP 201, not 202 or 200 - Zenduty's own API reference lists 201 as the Create Event response, alongside 400 (bad request), 403 (forbidden) and 404.
- payload is optional and free-form; message and summary are the two required text fields Zenduty actually shows as the incident title and description.
Why Zenduty 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). Zenduty is built around the same idea: an incident has a state, an on-call owner, and an escalation policy that pushes harder 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 Zenduty incident does not have.
What does the Events API actually require?
| Field | Required | Type | Notes |
|---|---|---|---|
| message | Yes | string | the incident title Zenduty shows |
| summary | Yes per the integration setup guide | string | a longer one-line description |
| alert_type | Yes | string, default info | critical | acknowledged | resolved | error | warning | info |
| entity_id | No | string | if omitted Zenduty makes one; alerts sharing one bind into the same incident |
| payload | No | object | free-form extra detail, shown on the incident |
check() only returns an action once a reading repeats for CONFIRM = 2 consecutive polls, the same confirm-before-alert pattern used in the Slack, SMS and PagerDuty versions. The difference here is what happens afterwards: the script remembers it already alerted (alerted = True) so a Buy Box that keeps flapping between two rival sellers never sends a second critical event on every poll - it only sends resolved once you are confirmed back, then can alert again cleanly on the next confirmed loss.
buybox_zenduty_alert.py - confirm twice, then critical or resolved by entity_id
"""Open a Zenduty 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.
Zenduty Events API calls go straight through requests.post - there is no official Zenduty 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 alerting
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
ZENDUTY_INTEGRATION_KEY = os.environ["ZENDUTY_INTEGRATION_KEY"] # the Events API integration key for one service
ZENDUTY_EVENTS_URL = f"https://events.zenduty.com/api/events/{ZENDUTY_INTEGRATION_KEY}/"
ZD_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', '?')})"
price = box.get("totalPrice")
if isinstance(price, (int, float)):
detail += f" at {round(price, 2)} {currency}" # buyBox.totalPrice is NOT pre-rounded
return "lost", detail
def entity_id(asin: str) -> str:
return f"buybox:{MY_SELLER_ID}:{asin}" # Zenduty binds alerts into one incident by entity_id
def send_event(alert_type: str, asin: str, message: str, summary: str, payload: dict | None = None) -> dict:
body = {"alert_type": alert_type, "message": message, "summary": summary, "entity_id": entity_id(asin)}
if payload is not None:
body["payload"] = payload
for attempt in range(1, 4):
resp = requests.post(ZENDUTY_EVENTS_URL, json=body, headers={"Content-Type": "application/json"},
timeout=15)
if resp.status_code == 201:
return resp.json()
if resp.status_code not in ZD_RETRYABLE or attempt == 3:
# 400 = malformed body (missing message/summary/alert_type), 403 = bad/revoked integration key,
# 404 = wrong integration key in the URL path - none of those are fixed by retrying
raise RuntimeError(f"zenduty {resp.status_code}: {resp.text}")
time.sleep(min(2 ** attempt, 10))
raise RuntimeError("unreachable")
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, status: str, detail: str) -> str | None:
"""Return 'trigger' / 'resolve' only once a reading repeats CONFIRM times; else None."""
row = state.setdefault(asin, {"status": None, "streak": 0, "alerted": False})
if status == row["status"]:
row["streak"] += 1
else:
row["status"], row["streak"] = status, 1
confirmed = row["streak"] >= CONFIRM
if confirmed and status == "lost" and not row["alerted"]:
row["alerted"] = True
row["detail"] = detail
return "trigger"
if confirmed and status == "mine" and row["alerted"]:
row["alerted"] = False
return "resolve"
return None
def run() -> int:
session, state, sent = new_session(), load_state(), 0
for asin in ASINS:
if not ASIN_RE.match(asin):
print(f"skip {asin}: not a 10-char ASIN, would be a billed call for nothing")
continue
try:
status, detail = read_buy_box(session, asin)
except ApiError as err:
print(f"{asin}: API error {err.status} - {err}")
continue
except (requests.ConnectionError, requests.Timeout) as err:
print(f"{asin}: connection error - {err}; skipping this poll, not the whole batch")
continue
action = check(state, asin, status, detail)
if action == "trigger":
send_event("critical", asin, f"Buy Box lost on {asin}", f"Buy Box lost on {asin}: {detail}",
payload={"asin": asin, "holder": detail})
print(f"[zenduty] critical {asin}: entity_id={entity_id(asin)}")
sent += 1
elif action == "resolve":
send_event("resolved", asin, f"Buy Box recovered on {asin}", f"Buy Box recovered on {asin}")
print(f"[zenduty] resolved {asin}: entity_id={entity_id(asin)}")
sent += 1
save_state(state)
print(f"{len(ASINS)} checked, {sent} Zenduty event(s) sent")
return sent
if __name__ == "__main__":
run()
What this script POSTs to events.zenduty.com/api/events/<key>/ on a confirmed loss
{
"alert_type": "critical",
"message": "Buy Box lost on B0EXAMPLE2",
"summary": "Buy Box lost on B0EXAMPLE2: Rival Co (RIVAL1, FBA) at 19.99 USD",
"entity_id": "buybox:A1MYSELLERID:B0EXAMPLE2",
"payload": {"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 Zenduty event(s) sent
--- run 2: B0EXAMPLE2 loses the Buy Box (1st sighting, not confirmed yet) ---
3 checked, 0 Zenduty event(s) sent
--- run 3: same reading confirmed, Zenduty incident triggered ---
[zenduty] critical B0EXAMPLE2: entity_id=buybox:A1MYSELLERID:B0EXAMPLE2
3 checked, 1 Zenduty event(s) sent
--- run 4: B0EXAMPLE2 is back (1st sighting, not confirmed yet) ---
3 checked, 0 Zenduty event(s) sent
--- run 5: back-in-stock confirmed, Zenduty incident resolved ---
[zenduty] resolved B0EXAMPLE2: entity_id=buybox:A1MYSELLERID:B0EXAMPLE2
3 checked, 1 Zenduty event(s) sent


| alert_type | Sent by this script when | What Zenduty does |
|---|---|---|
| critical | a confirmed Buy Box loss (2 consecutive polls) | creates a NEW alert, or binds into the existing incident sharing that entity_id |
| resolved | a confirmed Buy Box recovery (2 consecutive polls) | closes the incident Zenduty already grouped under that entity_id |
| acknowledged | not sent by this script | a human acting on the incident in the Zenduty app, or a separate on-call tool |
A 400 or 403 is a config problem, not a transient one
Zenduty's own API reference lists exactly four response codes for Create Event: 201, 400, 403 and 404. A 400 means the body is missing a required field (message, summary or alert_type) - retrying resends the same bad payload. A 403 means the integration key is wrong, disabled or belongs to a different team - retrying never fixes a bad key. This script only retries 429/500/502/503, the same billed-vs-free split used for the SellerMagnet side (see the error-handling guide), and raises immediately on 400/403/404 so a misconfigured key fails loudly on the first poll instead of silently retrying forever. Zenduty's own OpenAPI reference marks this /api/events/<integration-key>/ path as a deprecated Create Event operation in favor of a newer generic-events path with a different response shape - it is still accepted and is the one the in-app integration setup card hands you today, so this guide covers that one, not the newer replacement.
What does this mean for a seller running this unattended?
An incident that nobody 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 Zenduty service's escalation policy 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 a 201 response confirm the incident is visible in the Zenduty app?
A 201 means the Event object was created by the API, which is the documented success response for this endpoint. It is a direct create, not an async queue acknowledgement like some other incident tools use.
What happens if I send a resolved event for an entity_id that was never triggered?
Not tested here: Zenduty's docs describe binding alerts into incidents by entity_id for the normal trigger-then-resolve flow, but don't document the behaviour for a resolve with no matching open alert, so treat it as unverified rather than assuming a no-op.
Can I reuse the same entity_id for two different ASINs?
Don't - Zenduty groups alerts sharing an entity_id into one incident, so two ASINs sharing an id would resolve or re-open each other's incident. This script keys it as buybox:{seller_id}:{asin} specifically to keep every ASIN's lifecycle independent.
Is the integration key the same as a Zenduty API token?
No. The integration key in the URL path belongs to one service's Events API integration, created in that service's Integrations tab; it has no access to the account's REST API and cannot read or change anything else.
Why does the payload block appear on the critical call but not on resolved in the example?
payload is documented as an optional free-form object for extra detail; the resolved call only needs to repeat the required fields (message, summary, alert_type, entity_id) to close the matching incident, so this script leaves it off there.
Bottom line: confirm twice, send critical with a payload, resolve with just the required fields plus the same entity_id, and let Zenduty'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.