To get an Amazon Buy Box lost alert posted into Rocket.Chat 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 Rocket.Chat 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 JSON 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 Rocket.Chat incoming webhook URL carries TWO secrets in its path, an integrationId and a token (https://server/hooks/<id>/<token>) - not one opaque id like Mattermost or two query parameters like Google Chat.
- A successful POST answers HTTP 200 with a JSON body, at minimum {"success": true} - never plain text - and a bad id/token answers 404 with a JSON error, never a silent drop.
- 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 Rocket.Chat incoming webhook different from Mattermost or Slack?
Create one from Administration > Workspace > Integrations > New > Incoming on your Rocket.Chat workspace (docs.rocket.chat/docs/integrations, checked 2026-11-24); pick the channel or user it posts to, save it, and Rocket.Chat shows a webhook URL shaped like https://your-server/hooks/{integrationId}/{token} - both the integration id and the token sit in the URL path, so the whole URL is the secret, not a single opaque segment the way Mattermost's hook id is. The payload is Slack-compatible (text, emoji, attachments), but the incoming webhook actually calls the same Post Message endpoint the REST API uses, so a successful call answers with real JSON ({"success": true, ...}), never Mattermost's 2-byte plain-text ok body.
| Response | Reading | Rocket.Chat 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 Rocket.Chat?
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_rocketchat() 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. Writing the two-check confirmation logic surfaced a real bug while testing: carrying the "already alerted a loss" flag across a reading change by building a fresh dict (instead of copying it forward) silently dropped that flag, so a BACK message could never fire after the first LOST - fixed by copying alerted_lost into the new entry on every reading change, covered by a dedicated LOST-then-BACK test. A long batch is capped at MAX_LINES and truncated to stay under the 5,000-character default message cap before it is sent, rather than letting the server reject or mangle an oversized post.
buybox_rocketchat_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 Rocket.Chat 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 = 5000 # Message_MaxAllowedSize default (workspace-configurable, not a protocol constant)
MAX_LINES = 20 # keep well under the char cap even with long lines
# Incoming webhook URL carries TWO secrets in its PATH, not one opaque id or query params:
# https://<server>/hooks/<integrationId>/<token> - both are required, treat the whole URL as a secret.
ROCKETCHAT_WEBHOOK_URL = os.environ["ROCKETCHAT_WEBHOOK_URL"]
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 {min(mine):.2f}"
return "lost", detail
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(session, state: dict) -> list[str]:
lines = []
for asin in ASINS:
if not ASIN_RE.match(asin):
continue # a typo is billed like any other request, skip before calling
try:
reading, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
if not state.get("stopped"):
lines.append(f"**STOP: SellerMagnet returned {err.status}, pausing checks until it clears**")
state["stopped"] = True
return lines
continue # 404/502/503-after-retries: leave the streak untouched
state["stopped"] = False
entry = state.get(asin, {"reading": None, "streak": 0})
if reading == entry["reading"]:
entry["streak"] += 1
else:
# a reading change must NOT drop alerted_lost: that flag is what lets a later
# confirmed "mine" reading fire the BACK message, and it must survive even if the
# streak bounces through other readings (suppressed/no-offers) on the way back.
entry = {"reading": reading, "streak": 1, "alerted_lost": entry.get("alerted_lost", False)}
state[asin] = entry
if entry["streak"] == CONFIRM:
if reading == "mine" and entry.get("alerted_lost"):
lines.append(f"- {asin}: BACK, you hold the Buy Box again")
entry["alerted_lost"] = False
elif reading == "lost":
lines.append(f"- {asin}: LOST, held by {detail}")
entry["alerted_lost"] = True
state[asin] = entry
return lines
def post_to_rocketchat(lines: list[str]) -> None:
if not lines:
return
shown = lines[:MAX_LINES]
text = "**Amazon Buy Box change, confirmed on 2 checks:**\n" + "\n".join(shown)
if len(lines) > MAX_LINES:
text += f"\n...and {len(lines) - MAX_LINES} more"
if len(text) > MAX_TEXT_CHARS:
text = text[:MAX_TEXT_CHARS - 20] + "\n...(truncated)"
payload = {
"text": text,
"attachments": [{"color": "#d9534f" if "LOST" in text else "#5cb85c", "text": text}],
}
resp = requests.post(ROCKETCHAT_WEBHOOK_URL, json=payload, timeout=10)
# Success is JSON, never Mattermost's 2-byte plain-text "ok": {"success": true, ...the posted message...}.
# A disabled/wrong integration id or token answers 404 with {"success": false, "error": "..."} -
# the status code alone already tells you which branch you are in, no need to parse the body on the
# failure path, but the success path's body is never plain text so resp.text is never read here.
try:
body = resp.json()
except ValueError:
body = {}
if resp.status_code == 200 and body.get("success"):
print(f"[rocketchat] {text}")
else:
print(f"[rocketchat] POST failed: {resp.status_code} {body}")
def main() -> None:
session = new_session()
state = _load_state()
lines = check(session, state)
post_to_rocketchat(lines)
_save_state(state)
print(f"{len(ASINS)} checked, {1 if lines else 0} alert(s) sent")
if __name__ == "__main__":
main()
Five runs of the script (illustrative ASINs and sellers; [rocketchat] = 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
[rocketchat] **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
[rocketchat] **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/hooks/AAA111/BBB222 \
-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", "text": "..."}]}'
# HTTP/1.1 200 OK
# Content-Type: application/json
# {"success":true,"channel":"#alerts","ts":"2026-11-24T13:00:00.000Z"}

How do I set up the Rocket.Chat incoming webhook?
- Create the incoming integrationGo to Administration > Workspace > Integrations > New and choose the Incoming tab.
- Set the destination and enable itPick Post to Channel (a
#channelor@username), choose the user it posts as, and turn the Enabled toggle on, then Save. - Copy the full URL and treat it as a secretYou get a URL like
https://your-server/hooks/{integrationId}/{token}; both parts are required and anyone who has the full URL can post to that destination, 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 a JSON body containing\"success\":truemeans 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 destination)
export SELLERMAGNET_API_KEY="your-key-here"
export ROCKETCHAT_WEBHOOK_URL="https://your-server/hooks/AAA111/BBB222"
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_rocketchat_alert.py >> alert.log 2>&1
Rocket.Chat's own documentation (docs.rocket.chat/docs/integrations, checked 2026-11-24) describes the contract the script relies on: the incoming webhook runs the same Post Message endpoint the REST API uses, so a successful POST answers HTTP 200 with a JSON body, at minimum {"success": true}, and the posted message's own fields when no custom script intercepts it - never plain text the way Mattermost's ok body is, and never the id/time/event shape of ntfy. An unknown or wrong integrationId/token pair answers 404 with {"success": false, "error": "Invalid integration id or token provided."} - neither is documented as retry-safe, so the script logs it 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; Rocket.Chat itself charges nothing extra for an incoming webhook on a self-hosted or Cloud workspace 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 Rocket.Chat webhook post return JSON like Pushover or ntfy, or plain text like Mattermost?
JSON. Rocket.Chat's own documentation (docs.rocket.chat/docs/integrations, checked 2026-11-24) shows the webhook running the same Post Message endpoint as the REST API, so a successful call answers HTTP 200 with a JSON body carrying at least "success": true, never Mattermost's 2-byte plain-text "ok". A script-level error on the integration still answers 200 with a bare {"success": true} and posts the raw payload unscripted, so this script checks the success key rather than assuming a richer body is always there.
Why does the webhook URL need two parts, an integration id AND a token?
Rocket.Chat generates a URL shaped https://your-server/hooks/{integrationId}/{token} (docs.rocket.chat/docs/integrations) - both segments live in the PATH, unlike Google Chat's two secrets as QUERY parameters or Mattermost's single opaque hook id. A wrong id or token either way answers HTTP 404 with {"success": false, "error": "Invalid integration id or token provided."}, confirmed against a real deployment's error log, not a guess.
How long can the alert text be before Rocket.Chat rejects or mangles it?
The workspace-wide Message_MaxAllowedSize setting defaults to 5,000 characters (docs.rocket.chat/docs/deployment-environment-variables, checked 2026-11-24) - smaller than Mattermost's fixed 16,383-character protocol cap, and unlike every other channel in this series, it is an admin setting an operator can raise or lower, not a constant baked into the service. The script treats 5,000 as a conservative default and truncates before sending rather than trusting the server to reject or silently convert an oversized message to a .txt attachment.
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?
Rocket.Chat answers HTTP 404 with a JSON body {"success": false, "error": "Invalid integration id or token provided."} for an unknown id/token pair. 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 Rocket.Chat webhook message per run - remembering that the webhook URL carries two secrets, the success body is JSON, and the default message cap is 5,000 characters. 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.