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

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.

November 24, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script posted into Webex with a bot token

To get an Amazon Buy Box lost alert posted into Webex today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST a JSON payload to https://webexapis.com/v1/messages with a bot's access token in the Authorization header. The script below sends one message per run, tells a lost Buy Box apart from a suppressed one, reads the echoed JSON response 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.
  • Webex has no webhook URL with an embedded secret: a bot's Bearer token goes in a header, and the destination room is a roomId field in the JSON body, both posted to the same fixed endpoint.
  • A successful post echoes the full created message object as JSON, not a bare success flag or plain text; the combined text/markdown/attachments content is capped at 22,740 bytes.
  • 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 posting to Webex different from a Slack-style incoming webhook?

Create a bot at developer.webex.com > My Webex Apps > Create a Bot and copy its access token (docs.webex.com/messaging/docs/bots, checked 2026-11-24); that token authenticates every request the bot makes, for as long as it exists - unlike a personal access token, which the same docs note expires after 12 hours. Add the bot to a space (or let someone message it directly) to get a roomId, then POST to https://webexapis.com/v1/messages with Authorization: Bearer <token> and a JSON body containing roomId and either text or markdown. There is no per-destination secret URL to create, copy or rotate; the room id by itself is not a secret, because only the bot's own token can post as the bot.

The four readings and the Webex message each one can trigger.
ResponseReadingWebex 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 truesuppressedNONE
buyBox is {} and offers is []no-offersEMPTY

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

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_webex() sends every queued line as one message. 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. Carrying the two-check confirmation logic over from an earlier channel in this series surfaced a real bug while testing: building a fresh state dict on every reading change (instead of copying the old one forward) silently dropped the "already alerted a loss" 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 22,740-byte content cap before it is sent, and a 429 from Webex is retried exactly once, honoring the Retry-After header, rather than giving up immediately or looping indefinitely.

buybox_webex_alert.py - offers check, 2-check confirmation, one bot-token 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 Webex 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_MARKDOWN_BYTES = 22740                        # documented cap on text+markdown+attachments combined
MAX_LINES = 20                                    # keep well under the byte cap even with long lines
# Webex has NO webhook URL with an embedded secret: a bot's access token goes in the
# Authorization header, and the destination is a roomId in the JSON body, not the URL.
WEBEX_BOT_TOKEN = os.environ["WEBEX_BOT_TOKEN"]
WEBEX_ROOM_ID = os.environ["WEBEX_ROOM_ID"]
WEBEX_URL = "https://webexapis.com/v1/messages"


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_webex(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.encode()) > MAX_MARKDOWN_BYTES:
        text = text.encode()[:MAX_MARKDOWN_BYTES - 40].decode(errors="ignore") + "\n...(truncated)"
    payload = {"roomId": WEBEX_ROOM_ID, "markdown": text}
    headers = {"Authorization": f"Bearer {WEBEX_BOT_TOKEN}"}
    for attempt in range(2):                      # 1 retry: only a 429 is worth a second attempt here
        resp = requests.post(WEBEX_URL, json=payload, headers=headers, timeout=10)
        if resp.status_code == 429 and attempt == 0:
            time.sleep(min(float(resp.headers.get("Retry-After", 5)), 30))
            continue
        break
    # Success echoes the FULL created message object (id, roomId, markdown, personEmail, created),
    # never a bare {"success": true} the way Rocket.Chat's script-error fallback can, and never
    # Mattermost's plain-text "ok". A bad/expired bot token answers 401; a roomId the bot is not a
    # member of answers 404 - both carry a JSON "message" field, not Rocket.Chat's "error" key.
    try:
        body = resp.json()
    except ValueError:
        body = {}
    if resp.status_code == 200 and body.get("id"):
        print(f"[webex] {text}")
    else:
        print(f"[webex] POST failed: {resp.status_code} {body}")


def main() -> None:
    session = new_session()
    state = _load_state()
    lines = check(session, state)
    post_to_webex(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; [webex] = 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
[webex] **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
[webex] **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://webexapis.com/v1/messages \
  -H "Authorization: Bearer YOUR_BOT_ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"roomId": "Y2lzY2ZAKEROOM", "markdown": "**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
# {"id":"Y2lzY2ZAKEMSG","roomId":"Y2lzY2ZAKEROOM","personEmail":"bot@example.com","created":"2026-11-24T13:00:00.000Z"}
Blueprint flow: offers check per ASIN, two-check confirmation, then one Webex bot-token POST
A reading has to repeat before it reaches Webex; failed calls change nothing.

How do I set up the Webex bot?

  1. Create the botGo to developer.webex.com > My Webex Apps > Create a New App > Create a Bot, name it and copy the access token shown once - it does not expire the way a personal access token does.
  2. Add the bot to a spaceAdd the bot's email address to the Webex space (or message it directly) you want the alert to land in.
  3. Find the roomIdCall GET https://webexapis.com/v1/rooms with the bot's token to list the spaces it is in and copy the id of the one you want.
  4. Send a test messagecurl -X POST -H 'Authorization: Bearer TOKEN' -H 'Content-Type: application/json' -d '{\"roomId\": \"ROOM_ID\", \"text\": \"test\"}' https://webexapis.com/v1/messages; a 200 response with an id field 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 bot token alone lets anyone post as this bot)
export SELLERMAGNET_API_KEY="your-key-here"
export WEBEX_BOT_TOKEN="your-bot-access-token"
export WEBEX_ROOM_ID="Y2lzY2ZAKEROOM"
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_webex_alert.py >> alert.log 2>&1

Webex's own REST API basics (developer.webex.com/messaging/docs/basics and /docs/rest-api-basics, checked 2026-11-24) describe the contract the script relies on: a successful POST /v1/messages answers HTTP 200 with the full created message as JSON, a missing or expired token answers 401, and a roomId the bot cannot see (wrong id, or the bot was never added) answers 404 - neither is documented as retry-safe, so the script logs it and leaves the stored streak untouched for the next scheduled run. A 429 is the one failure worth retrying: it always carries a Retry-After header telling the script exactly how long to wait.

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; Webex itself charges nothing extra for a bot posting into a space you already use. With a 2-check confirmation the worst-case delay before the space 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 Webex use a webhook URL with an embedded secret like Slack or Mattermost?

No. Every other channel in this series posts to a URL that itself carries the secret (a hook id, a token, or both). Webex has no such thing for sending messages: a bot's access token goes in an Authorization: Bearer header, and the destination is a roomId field in the JSON body, both sent to the same fixed endpoint, https://webexapis.com/v1/messages (developer.webex.com/messaging/docs/basics, checked 2026-11-24). Leaking the room id alone does not let anyone post; the bot token is the only secret.

What does a successful post actually return?

The full created message object - id, roomId, the markdown you sent, personEmail, and created - as JSON with HTTP 200 (developer.webex.com/docs/api/v1/messages, checked 2026-11-24). That is richer than Rocket.Chat's bare {"success": true} fallback and nothing like Mattermost's 2-byte plain-text ok; this script only checks for the id key rather than parsing the rest of the echoed message.

How long can the alert be before Webex rejects or trims it?

Webex's own Buttons and Cards documentation (checked 2026-11-24) states the combined content of text, markdown and attachments cannot exceed 22,740 bytes in one message - a single cap across every content field, unlike Rocket.Chat's plain character count on text alone or Mattermost's 16,383-character limit. The script measures the encoded markdown string and truncates before sending rather than trusting the API to reject an oversized post.

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 on a 429 from the Webex API?

Webex's REST API basics (checked 2026-11-24) document a 429 Too Many Requests response with a Retry-After header giving the exact number of seconds to wait; the /messages endpoint gets a higher, dynamically adjusted quota than the roughly 300 requests/minute default on most other endpoints. The script sleeps for that header's value (capped at 30 seconds for a check this infrequent) and retries exactly once before giving up and logging the failure.

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 Webex message per run with a bot's Bearer token - remembering there is no webhook URL to create, the response echoes the full message, and the content cap is 22,740 bytes across text, markdown and attachments combined. 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 sent via the Matrix Client-Server API
Amazon API Buy Box Alerts

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.

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