To get an Amazon Buy Box lost alert posted into Mattermost today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST a JSON payload to a Mattermost incoming webhook URL. The script below sends one message per run, tells a lost Buy Box apart from a suppressed one, reads the webhook's plain-text success body correctly, and costs one SellerMagnet credit per ASIN per check.
Key Takeaways
- buyBox is the featured offer: its sellerId is the seller who holds the Buy Box, the literal "Amazon" when Amazon does.
- An empty buyBox means two different things: buyBoxSuppressed true (offers exist, Amazon features none) or no offers at all.
- Alert only when two checks in a row agree: an offer page can come back without parsable offers, and one reading should not page you.
- A successful Mattermost webhook POST answers HTTP 200 with a 2-byte plain-text body, literally "ok" - not JSON, so the script never calls resp.json() on the success path.
- attachments belongs at the TOP LEVEL of the webhook payload; nested under props it is silently stripped by the server, with no error to notice.
- Each check costs 1 SellerMagnet credit per ASIN; 502/503 retries are billed per attempt, a 500 is refunded, and a free 401/403 stops the run with one STOP message.
How is a Mattermost incoming webhook different from Slack or Teams?
Create one from Main Menu > Integrations > Incoming Webhooks on your Mattermost server (docs.mattermost.com/integrations-guide/incoming-webhooks, checked 2026-11-24); it must be enabled for your server first, then you pick a channel and get a URL shaped like https://your-server.com/hooks/xxx-generatedkey-xxx - treat it as a secret, since anyone who has it can post to that channel. The payload format is deliberately Slack-compatible (text, channel, username, icon_url, attachments), but the two differ in two places that matter for a script: the success response body is plain text, not JSON, and attachments sits at the top level of the payload, not nested under props the way the REST API's own post-creation endpoint expects it.
| Response | Reading | Mattermost message |
|---|---|---|
| buyBox.sellerId is your sellerId | mine | BACK, after a confirmed loss |
| buyBox.sellerId is any other seller or "Amazon" | lost | LOST, with holder, price and your offer |
| buyBox is {} and buyBoxSuppressed is true | suppressed | NONE |
| buyBox is {} and offers is [] | no-offers | EMPTY |
How do I build the Amazon Buy Box lost alert for Mattermost?
read_buy_box() turns one offers response into a reading, check() keeps a streak per ASIN in buybox_state.json and queues a line once a new reading has been seen CONFIRM times in a row, and post_to_mattermost() sends every queued line as one webhook POST. get_with_retry comes from retry.py and ApiError and new_session from sellermagnet.py, both from the Python quickstart. Malformed ASINs are skipped before any call, because the offers endpoint bills a typo like any other request. MY_SELLER_ID has no default on purpose: without it every ASIN would read as lost, so the script refuses to start. A long batch is capped at MAX_LINES and truncated to stay under Mattermost's documented 16,383-character message length before it is sent, rather than letting the server reject an oversized post outright.
buybox_mattermost_alert.py - offers check, 2-check confirmation, one webhook POST per run
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 Mattermost hears about it
STATE_FILE = "buybox_state.json"
ASIN_RE = re.compile(r"^[A-Z0-9]{10}$") # offers calls are billed even for a typo, so filter first
MAX_TEXT_CHARS = 16383 # product-limits: "Message length" is a CHARACTER cap, not bytes
MAX_LINES = 20 # keep well under the char cap even with long lines
MATTERMOST_URL = os.environ["MATTERMOST_WEBHOOK_URL"] # https://<server>/hooks/<id>; treat as a secret
def read_buy_box(session, asin: str) -> tuple[str, str]:
"""('mine' | 'lost' | 'suppressed' | 'no-offers', detail for the message)."""
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))]
if mine:
detail += f", your offer {mine[0]:.2f}"
return "lost", detail
def load_state() -> dict:
try:
with open(STATE_FILE) as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return {}
def save_state(state: dict) -> None:
with open(STATE_FILE, "w") as f:
json.dump(state, f)
def check(session, asins: list[str]) -> list[str]:
"""One pass over every ASIN; returns the queued lines (confirmed changes only)."""
state = load_state()
lines = []
for asin in asins:
if not ASIN_RE.match(asin):
print(f"skip malformed ASIN: {asin!r}")
continue
try:
reading, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
raise
print(f"{asin}: call failed ({err.status}), streak kept")
continue
entry = state.get(asin)
if entry is None:
# a new ASIN seeds its state to whatever it first reads, no false alert for staying that way
state[asin] = {"reading": reading, "streak": 1, "alerted": reading}
continue
if entry["reading"] == reading:
entry["streak"] = entry.get("streak", 1) + 1
else:
entry["reading"], entry["streak"] = reading, 1
if entry["streak"] >= CONFIRM and entry.get("alerted") != reading:
if reading == "mine":
lines.append(f"{asin}: BACK, you hold the Buy Box again")
elif reading == "lost":
lines.append(f"{asin}: LOST, held by {detail}")
elif reading == "suppressed":
lines.append(f"{asin}: Buy Box SUPPRESSED, no featured offer shown")
else:
lines.append(f"{asin}: no offers found at all")
entry["alerted"] = reading
save_state(state)
return lines
def post_to_mattermost(lines: list[str]) -> bool:
"""POST one Mattermost incoming-webhook message for every confirmed change this run."""
if not lines:
return False
text = "**Amazon Buy Box change, confirmed on 2 checks:**\n" + "\n".join(f"- {l}" for l in lines[:MAX_LINES])
if len(lines) > MAX_LINES:
text += f"\n- ...and {len(lines) - MAX_LINES} more"
if len(text) > MAX_TEXT_CHARS: # the 16,383-char cap is counted in characters, not bytes
text = text[: MAX_TEXT_CHARS - 20].rsplit("\n", 1)[0] + "\n- ...(truncated)"
color = "#d9534f" if any(": LOST" in l for l in lines) else "#5cb85c"
# attachments MUST be a top-level field, not nested inside props (silently stripped there, no error)
payload = {"text": text, "attachments": [{"color": color, "fallback": lines[0]}]}
resp = requests.post(MATTERMOST_URL, json=payload, timeout=30)
if resp.status_code != 200:
print(f"mattermost post failed: {resp.status_code} {resp.text[:200]}")
return False
# a successful post answers "ok" as a 2-byte PLAIN-TEXT body, never JSON: resp.json() would raise ValueError
if resp.text.strip() != "ok":
print(f"mattermost post: unexpected 200 body {resp.text[:200]!r}")
return True
def main() -> None:
session = new_session()
state = load_state()
try:
lines = check(session, ASINS)
except ApiError as err:
if not state.get("_stop_sent"):
post_to_mattermost([f"STOP: SellerMagnet credits/key problem ({err.status}), run stopped early"])
state["_stop_sent"] = True
save_state(state)
else:
print(f"stop already sent, not repeating ({err.status})")
print(f"stopped: {err}")
return
if state.get("_stop_sent"): # a clean run clears the STOP flag so the next one can re-fire
state["_stop_sent"] = False
save_state(state)
sent = post_to_mattermost(lines)
print(f"{len(ASINS)} checked, {1 if sent else 0} alert(s) sent, {len(lines)} change line(s)")
if __name__ == "__main__":
main()
Five runs of the script (illustrative ASINs and sellers; [mattermost] = the message sent)
--- run 1 (illustrative ASINs and sellers)
3 checked, 0 alert(s) sent
--- run 2, B0EXAMPLE2 lost (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 3, same reading confirmed
[mattermost] **Amazon Buy Box change, confirmed on 2 checks:**
- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99
3 checked, 1 alert(s) sent
--- run 4, back to mine (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 5, back to mine, confirmed
[mattermost] **Amazon Buy Box change, confirmed on 2 checks:**
- B0EXAMPLE2: BACK, you hold the Buy Box again
3 checked, 1 alert(s) sent
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST https://your-server.com/hooks/xxx-generatedkey-xxx \
-H "Content-Type: application/json" \
-d '{"text": "**Amazon Buy Box change, confirmed on 2 checks:**\n- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99", "attachments": [{"color": "#d9534f", "fallback": "B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99"}]}'
# HTTP/1.1 200 OK
# Content-Type: text/plain
# ok

How do I set up the Mattermost incoming webhook?
- Enable incoming webhooksA System Admin enables them once for the server under System Console > Integrations > Integration Management, if they are not already on.
- Add the webhookGo to Main Menu > Integrations > Incoming Webhooks > Add Incoming Webhook, name it, and pick the channel it should post into.
- Copy the URL and treat it as a secretYou get a URL like
https://your-server.com/hooks/xxx-generatedkey-xxx; anyone who has it can post to that channel, so store it the same way you would an API key. - Send a test message
curl -X POST -H 'Content-Type: application/json' -d '{"text": "test"}' <your-webhook-url>from a terminal; a 200 response with bodyokmeans it worked.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the webhook URL alone lets anyone post into this channel)
export SELLERMAGNET_API_KEY="your-key-here"
export MATTERMOST_WEBHOOK_URL="https://your-server.com/hooks/xxx-generatedkey-xxx"
export MY_SELLER_ID="A1MYSELLER0001" # your sellerId as it appears in offers[]
# crontab -e: every 15 minutes, 3 ASINs = 288 credits a day; flock -n skips a run while the last one still runs
*/15 * * * * cd /opt/buybox && . ./.env && flock -n .lock .venv/bin/python buybox_mattermost_alert.py >> alert.log 2>&1
Mattermost's own documentation (docs.mattermost.com/integrations-guide/incoming-webhooks and the developer integration guide, checked 2026-11-24) describes the contract the script relies on: a successful POST answers HTTP 200 with Content-Type: text/plain and a 2-byte body, literally ok - there is no JSON to parse on success, unlike ntfy's id/time/event body or Google Chat's name/thread.name echo. The payload accepts attachments only as a top-level field; putting it inside props (the way the REST API's post-creation endpoint nests it) is one of several keys the server strips from client-supplied props without an error either way. A 400 means the JSON body itself was malformed ("Unable to parse incoming data"), and a 404 means the webhook id is unknown or was deleted - neither is documented as retry-safe, so the script logs them and leaves the stored streak untouched for the next scheduled run.
What should you check when a LOST alert fires?
The alert tells you who holds the Buy Box and at what total price, not why Amazon featured that offer. Amazon's US help page Becoming the Featured Offer (Seller Central, checked 2026-10-23) lists what it weighs: the total price including shipping, a fast and specific delivery promise, free shipping, free returns and seller performance, and an out-of-stock offer cannot be featured. Its Featured Offer guide on sell.amazon.com adds that fulfilling orders yourself can be just as effective as FBA. Start with the gap between the holder's price and your offer in the message, then your delivery date and stock. The Buy Box price gap guide shows why the lowest price alone does not decide it.
How many credits does a Buy Box alert cost?
One offers call per ASIN per check, so the SellerMagnet cost is the number of ASINs times the number of checks; Mattermost itself charges nothing extra for an incoming webhook on a self-hosted or Cloud server you already run. With a 2-check confirmation the worst-case delay before the channel hears about a loss is about two intervals. Errors add to the SellerMagnet bill in different ways: a 404 is billed once and not retried, a 502 or 503 is billed on every attempt, a 500 is refunded, and the free gate errors (400 for a missing parameter, 401, 403, 429) cost nothing. The Buy Box monitoring interval guide compares intervals in more detail, and Pricing lists the plans.
| Check interval | Credits per day | Credits per 30 days | Worst-case alert delay |
|---|---|---|---|
| Every 15 minutes | 96 | 2,880 | about 30 minutes |
| Every hour | 24 | 720 | about 2 hours |
| Every 4 hours | 6 | 180 | about 8 hours |
| Once a day | 1 | 30 | about 2 days |

Frequently Asked Questions
Does a successful Mattermost webhook post return JSON like most APIs?
No. Mattermost's own incoming webhook docs (checked 2026-11-24) show a successful POST answering HTTP 200 with Content-Type text/plain and a literal 2-byte body: ok. Calling response.json() on that body raises ValueError, so this script checks the status code and reads resp.text, never resp.json(), on the success path.
Why does the color-coded attachment need to sit at the top level of the JSON payload?
Mattermost's webhook payload and its REST API payload differ here: the REST API nests attachments under props.attachments, but an incoming webhook expects attachments as a top-level key. Put it under props instead (as a Teams- or Slack-style integration might guess) and Mattermost silently strips it: props.attachments is one of several keys the server reserves and removes from client-supplied props, with no error either way.
How long can the alert text be before Mattermost rejects it?
Mattermost documents a 16,383-character message length limit (Product limits, checked 2026-11-24). That is a CHARACTER cap, not a byte cap like ntfy's 4,096 bytes or Google Chat's 32,000 bytes, so an alert full of multi-byte emoji or non-ASCII seller names has more headroom here than a byte-counted channel would give it for the same character count.
Why does the script wait for a second check before posting?
An offer page can come back without parsable offers, which looks like a stock-out. Waiting for the same reading on two checks in a row filters one-off readings at the cost of one interval.
What happens if the webhook URL is wrong or the integration was deleted?
Mattermost answers a 400 with a message like "Unable to parse incoming data" for a malformed payload, or a 404 for a webhook id that does not exist or was removed. Either way the script logs the status and body and does not retry; nothing in the stored streak changes, so the next scheduled run tries again from the same state.
What happens when my SellerMagnet credits run out?
The API answers 401 (or 403 during a burst), which is not billed. The script stops instead of calling the remaining ASINs, posts one STOP message and does not repeat it until a run gets through without a 401 or 403.
Bottom line: compare buyBox.sellerId with your own seller ID, keep a streak per ASIN, and post one Mattermost webhook message per run - remembering that the success body is plain text, not JSON, and that attachments belongs at the top level of the payload. To see who held the Buy Box and for how long after the fact, use the Buy Box history API; a free account includes 150 credits to try the alert.