Home / Blog / Amazon Buy Box Lost Alert in Matrix: PUT /send, Idempotent txnId Retries

Amazon Buy Box Lost Alert in Matrix: PUT /send, Idempotent txnId Retries

Get an Amazon Buy Box lost alert posted straight into a Matrix room: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and PUT one m.room.message event per confirmed change. Covers the Bearer token, the JSON event_id success body, why a retry must reuse the same txnId, percent-encoding the room ID and the 65,536-byte whole-event cap. Tested Python, costs one credit per ASIN per check.

November 24, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script sent via the Matrix Client-Server API

To get an Amazon Buy Box lost alert posted into Matrix today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and PUT a JSON message event to /_matrix/client/v3/rooms/{roomId}/send/m.room.message/{txnId}. The script below sends one event per confirmed change, tells a lost Buy Box apart from a suppressed one, and reuses the SAME transaction ID on every retry of one message so a dropped response cannot turn into a duplicate event.

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, and only on a CHANGE: a brand-new ASIN seeds its starting reading without alerting, so deploying the script never fires a backstory alert.
  • A successful send answers HTTP 200 with JSON {"event_id": "..."} - unlike a webhook chat channel's plain-text ack, this one must be parsed as JSON on the success path.
  • The txnId in the URL path must be the SAME string on every retry of one message: the Matrix spec calls this out explicitly as how the server keeps a retry idempotent.
  • The room ID's leading "!" and its ":" before the server name must be percent-encoded into the URL path, or a strict server/proxy can reject or mis-route the request.
  • 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 do I send a message into a Matrix room from a script?

Get a room ID (starts with !, e.g. !AbCdEfGhIjKlMnOpQr:example.org) and a long-lived access token for an account that has already joined that room - either your own account's token from Settings > Help & About > Advanced in Element, or a dedicated bot account's token, created the same way. Every request authenticates with Authorization: Bearer <access_token> (spec.matrix.org/latest/client-server-api/, checked 2026-11-24); the older access_token query-string parameter still works on most homeservers but the spec documents it being phased out, so a new script should not rely on it. Sending itself is one PUT to /_matrix/client/v3/rooms/{roomId}/send/{eventType}/{txnId} with the event's content as the JSON body - m.room.message with {"msgtype": "m.text", "body": "..."} for a plain-text alert.

The four readings and the Matrix message each one can trigger.
ResponseReadingMatrix message
buyBox.sellerId is your sellerIdmineBACK, after a confirmed loss
buyBox.sellerId is any other seller or "Amazon"lostLOST, with holder, price and your offer
buyBox is {} and buyBoxSuppressed is truesuppressedSUPPRESSED, no featured offer shown
buyBox is {} and offers is []no-offersno offers found at all

How do I build the Amazon Buy Box lost alert for Matrix?

read_buy_box() turns one offers response into a reading, check() keeps a per-ASIN streak plus the reading it last actually alerted on in buybox_state.json, and post_to_matrix() PUTs every queued line as one m.room.message event. get_with_retry comes from retry.py and ApiError/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. The txnId is derived from the message text itself, not from a counter or a timestamp per attempt, specifically so every retry of ONE confirmed payload keeps sending the identical transaction ID.

buybox_matrix_alert.py - offers check, 2-check confirmation, one idempotent PUT per confirmed change

import json
import os
import re
import time
import urllib.parse

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 Matrix 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

MATRIX_HOMESERVER = os.environ["MATRIX_HOMESERVER"]        # e.g. https://matrix.example.org, no trailing slash
MATRIX_ACCESS_TOKEN = os.environ["MATRIX_ACCESS_TOKEN"]    # treat as a secret; never commit it
MATRIX_ROOM_ID = os.environ["MATRIX_ROOM_ID"]               # "!roomid:example.org" - note the leading "!"
MAX_BODY_CHARS = 60000                            # content.body chars; whole-event cap is 65536 BYTES (spec v1.15+)
MAX_LINES = 20
TXN_ATTEMPTS = 4


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}")           # a typo is billed like any other request
            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")   # e.g. billed 404: not on this marketplace
            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 _txn_id(payload_key: str) -> str:
    # One id per CONFIRMED PAYLOAD, not per HTTP attempt: the Matrix spec says to reuse the same
    # txnId when retrying a request, so the homeserver can dedupe a retry after a dropped response
    # instead of creating a second event for a message that actually went through the first time.
    return f"bbm-{abs(hash(payload_key)) % 10 ** 12}"


def post_to_matrix(lines: list[str]) -> bool:
    """PUT one m.room.message event 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_BODY_CHARS:
        text = text[:MAX_BODY_CHARS - 3] + "..."
    content = {"msgtype": "m.text", "body": text}
    txn_id = _txn_id(text)                                     # same id across every retry below
    room_path = urllib.parse.quote(MATRIX_ROOM_ID, safe="")    # "!roomid:example.org" has "!" and ":"
    url = f"{MATRIX_HOMESERVER}/_matrix/client/v3/rooms/{room_path}/send/m.room.message/{txn_id}"
    headers = {"Authorization": f"Bearer {MATRIX_ACCESS_TOKEN}"}
    for attempt in range(1, TXN_ATTEMPTS + 1):
        try:
            resp = requests.put(url, headers=headers, json=content, timeout=30)
        except (requests.ConnectionError, requests.Timeout):
            if attempt == TXN_ATTEMPTS:
                print("matrix PUT failed: connection error, giving up (same txnId retries next run)")
                return False
            continue                                            # same txn_id: a dropped send is not a new message
        if resp.status_code == 200:
            # a successful send answers JSON {"event_id": "..."}, unlike Mattermost's plain-text "ok" body
            print(f"matrix post ok: {resp.json()['event_id']}")
            return True
        try:
            err_body = resp.json()
        except ValueError:
            err_body = {}
        if resp.status_code == 429 and err_body.get("errcode") == "M_LIMIT_EXCEEDED" and attempt < TXN_ATTEMPTS:
            retry_after = resp.headers.get("Retry-After")       # seconds; current spec header
            wait = float(retry_after) if retry_after is not None else err_body.get("retry_after_ms", 2000) / 1000
            time.sleep(wait)
            continue                                            # same txn_id again
        print(f"matrix post failed: {resp.status_code} {err_body.get('errcode', '?')} {err_body.get('error', '')}")
        return False
    return False


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_matrix([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_matrix(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; only B0EXAMPLE2 ever changes)

--- run 1 (illustrative ASINs and sellers) ---
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 2 (illustrative ASINs and sellers) ---
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 3 (illustrative ASINs and sellers) ---
matrix post ok: $a3bcd1234:example.org
3 checked, 1 alert(s) sent, 1 change line(s)
--- run 4 (illustrative ASINs and sellers) ---
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 5 (illustrative ASINs and sellers) ---
matrix post ok: $a5bcd1234:example.org
3 checked, 1 alert(s) sent, 1 change line(s)

What the script actually PUTs (curl equivalent, illustrative values)

curl -s -X PUT \
  "https://matrix.example.org/_matrix/client/v3/rooms/%21roomid%3Aexample.org/send/m.room.message/bbm-583920471028" \
  -H "Authorization: Bearer syt_abcdef..." \
  -H "Content-Type: application/json" \
  -d '{"msgtype": "m.text", "body": "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"}'
# HTTP/1.1 200 OK
# Content-Type: application/json
# {"event_id": "$a1b2c3d4e5f6g7h8i9j0:example.org"}
Blueprint flow: offers check per ASIN, two-check confirmation, then one idempotent Matrix PUT
A reading has to repeat and actually CHANGE before it reaches Matrix; retries reuse the txnId.

How do I get a Matrix room ID and access token?

  1. Create or pick a roomIn Element (or any Matrix client), create a room for the alerts, or reuse an existing one. Open Room Settings > Advanced to read its internal room ID, shaped like !AbCdEfGhIjKlMnOpQr:example.org.
  2. Get an access tokenIn Element, go to Settings > Help & About > Advanced > Access Token, or register a dedicated bot account and log it in via the /login API to get a token scoped to that account only.
  3. Join the room with that accountThe account the token belongs to must already be a member of the room; an un-joined account's token gets M_FORBIDDEN on every send, not a more specific "not joined" error.
  4. Send a test eventcurl -X PUT -H 'Authorization: Bearer <token>' -d '{"msgtype": "m.text", "body": "test"}' '<homeserver>/_matrix/client/v3/rooms/<url-encoded-room-id>/send/m.room.message/test1' - a 200 with an event_id in the body means 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 access token alone can post into every room the account has joined)
export SELLERMAGNET_API_KEY="your-key-here"
export MATRIX_HOMESERVER="https://matrix.example.org"       # no trailing slash
export MATRIX_ACCESS_TOKEN="syt_abcdef..."
export MATRIX_ROOM_ID="!roomid:example.org"                 # keep the leading ! and the :server part
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_matrix_alert.py >> alert.log 2>&1

The Matrix Client-Server API (spec.matrix.org/latest/client-server-api/, checked 2026-11-24) describes the contract the script relies on: a successful PUT answers HTTP 200 with a JSON body containing event_id - there is no plain-text ack the way Mattermost's webhook has. A 429 carries errcode: M_LIMIT_EXCEEDED; the current spec says to wait for the Retry-After HTTP header before retrying and separately marks the older retry_after_ms body field as deprecated, so the script checks the header first and only falls back to the body field when the header is missing. On every retry - whether triggered by a 429 or by a connection error - the script reuses the exact same txnId, because the spec states that a client-chosen transaction ID is how the server "ensures idempotency of requests": generating a fresh ID for what is really a retry can create a duplicate event if the first attempt actually went through before the response was lost.

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; a self-hosted or Matrix.org-hosted room costs nothing extra to post into. With a 2-check confirmation the worst-case delay before the room 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.

Credits per tracked ASIN by check interval (1 credit per offers call).
Check intervalCredits per dayCredits per 30 daysWorst-case alert delay
Every 15 minutes962,880about 30 minutes
Every hour24720about 2 hours
Every 4 hours6180about 8 hours
Once a day130about 2 days
Blueprint table of credits per tracked ASIN for four check intervals and the alert delay
Shorter intervals cost more credits and cut the delay; the confirmation doubles it.

Frequently Asked Questions

Does Matrix give a message a confirmed delivery receipt the way SMS does?

No, and it is better than that for a script: a successful PUT answers HTTP 200 with JSON {"event_id": "$..."} - the homeserver accepted and persisted the event under that ID. What it does NOT tell you is whether every room member's client has synced it yet; that is a separate, eventually-consistent federation concern this alert does not need to track.

Why does a retry reuse the same txnId instead of generating a new one?

The Matrix spec's own wording: clients should generate an ID unique across requests with the same access token, and the server uses it to ensure idempotency. Reusing the txnId on a retry after a timeout or a dropped response lets the homeserver recognise it as the SAME send attempt; generating a fresh one for what is actually a retry risks a duplicate event if the first PUT had already gone through.

Why does the room ID need percent-encoding in the URL?

A real room ID looks like !AbCdEfGhIjKlMnOpQr:example.org: a literal "!" followed by a ":" before the server name. Both are percent-encoded (%21 and %3A) when built into the request path; some homeservers tolerate the raw characters, but a strict server or an intermediate proxy can reject or mis-route an un-encoded path.

Is the 65,536-byte Matrix event cap the same kind of limit as Mattermost's 16,383 characters?

No. Mattermost's limit is documented as a CHARACTER cap on the message text alone. Matrix's 65,536-byte cap applies to the COMPLETE event (envelope fields like sender and origin_server_ts included, Canonical-JSON-encoded), not just content.body, and it is bytes, not characters, so multi-byte text eats the budget faster than its character count suggests.

What happens if the access token is wrong or was revoked?

The homeserver answers M_UNKNOWN_TOKEN, normally with HTTP 401. That is not retry-safe: the script logs it and leaves the stored streak untouched, the same way it treats a SellerMagnet 401/403, rather than looping on a token that will not start working again on its own.

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 to the Matrix room 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 PUT one Matrix m.room.message event per confirmed change - remembering that the success body is JSON with an event_id, that the room ID needs percent-encoding, and that any retry of that same message must reuse the same txnId. 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.

Related Articles

Continue exploring topics related to this article.

Terminal window showing the Amazon Buy Box lost alert a Python script posted into Webex with a bot token
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Webex: Bot Token, No Webhook URL

Get an Amazon Buy Box lost alert posted straight into Webex: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one message per run with a bot's Bearer token, no webhook URL at all. Covers the roomId body field, the full echoed message response and the 22,740-byte content cap. Tested Python, costs one credit per ASIN per check.

Nov 24, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted via a Rocket.Chat incoming webhook
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Rocket.Chat: Incoming Webhook, Two-Part URL

Get an Amazon Buy Box lost alert posted straight into Rocket.Chat: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one incoming-webhook message per run. Covers the two-part integrationId/token webhook URL, the JSON success body and the 5,000-character default message cap. Tested Python, costs one credit per ASIN per check.

Nov 24, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted via a Mattermost incoming webhook
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Mattermost: Incoming Webhook, Top-Level Attachments

Get an Amazon Buy Box lost alert posted straight into a Mattermost channel: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one incoming-webhook message per run. Covers the plain-text "ok" success body, the top-level attachments field and the 16,383-character cap. Tested Python, costs one credit per ASIN per check.

Nov 24, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime