Home / Blog / Amazon Buy Box Lost Alert in Zulip: Basic Auth, No Webhook URL

Amazon Buy Box Lost Alert in Zulip: Basic Auth, No Webhook URL

Get an Amazon Buy Box lost alert posted straight into a Zulip 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 call Zulip's own REST API with HTTP Basic auth, since Zulip has no generic webhook URL for a custom alert. Covers the form-encoded request, the realm-specific message length cap and the JSON-body retry-after on a 429. Tested Python, costs one credit per ASIN per check.

November 25, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script posted via the Zulip REST API

To get an Amazon Buy Box lost alert posted into Zulip today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST to Zulip's own /api/v1/messages endpoint with HTTP Basic auth. Zulip has no generic incoming-webhook URL for a custom alert the way Slack, Teams or Mattermost do, so the script stores a bot email and API key instead of one opaque secret URL. It sends one message per run, tells a lost Buy Box apart from a suppressed one, 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.
  • Zulip has no generic webhook URL for a custom integration: the script authenticates with HTTP Basic auth (a bot email + API key) against the same REST endpoint every Zulip client uses to send a message.
  • The request body is form-encoded (type/to/topic/content); the response is JSON on both success and every error, with a machine-readable code field, not just a status code.
  • A 429 carries code RATE_LIMIT_HIT and a retry-after field inside the JSON body itself, on top of the usual Retry-After header; the script retries once from the body's value.

How is calling Zulip different from a Slack- or Teams-style webhook?

Every other channel in this alert series (Slack, Teams, Discord, Mattermost, Google Chat, ntfy, Pushover, Webex, Matrix, Rocket.Chat) hands you one secret URL: POST a JSON body to it and the service posts the message for you. Zulip's own incoming-webhook framework (zulip.readthedocs.io, Incoming webhooks overview, checked 2026-11-25) exists, but it is built for pre-registered integrations shipped inside Zulip's own codebase, each already knowing the payload shape of one specific third-party service - it is not a generic endpoint a custom script can POST an arbitrary alert to. The documented way to send a custom message is Zulip's regular REST API: create a bot account, grab its email and API key from its own settings page, and call POST https://your-org.zulipchat.com/api/v1/messages with HTTP Basic auth, exactly like a human client would (zulip.com/api/send-message, checked 2026-11-25).

The four readings and the Zulip message each one can trigger.
ResponseReadingZulip 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 Zulip?

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_zulip() sends every queued line as one channel 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. A long batch is capped at MAX_LINES and truncated to stay under the realm's message length limit (MAX_TEXT_CHARS, 10,000 code points by default) before it is sent, rather than letting the server reject an oversized post outright. A 429 is read for code == "RATE_LIMIT_HIT" and its JSON retry-after value, and retried exactly once.

buybox_zulip_alert.py - offers check, 2-check confirmation, one REST API call per run

import json
import os
import re

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 Zulip 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 = 10000                            # MAX_MESSAGE_LENGTH realm default; read from POST /register in production
MAX_LINES = 20                                    # keep well under the char cap even with long lines
ZULIP_SITE = os.environ["ZULIP_SITE"]             # e.g. https://your-org.zulipchat.com, no trailing slash
ZULIP_BOT_EMAIL = os.environ["ZULIP_BOT_EMAIL"]   # the bot's own Zulip account email, treat as a secret alongside the key
ZULIP_API_KEY = os.environ["ZULIP_API_KEY"]       # the bot's API key from its own account settings
ZULIP_CHANNEL = os.environ.get("ZULIP_CHANNEL", "buy-box-alerts")
ZULIP_TOPIC = "Buy Box"                           # every channel message needs one; keeps all alerts threaded together


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 _send(text: str):
    """One POST to Zulip's own send-message endpoint; returns the parsed JSON body, raises on a transport error."""
    resp = requests.post(
        f"{ZULIP_SITE}/api/v1/messages",
        auth=(ZULIP_BOT_EMAIL, ZULIP_API_KEY),            # HTTP Basic, no webhook-URL secret
        data={"type": "stream", "to": ZULIP_CHANNEL, "topic": ZULIP_TOPIC, "content": text},
        timeout=30,
    )
    try:
        body = resp.json()                                 # Zulip answers JSON on BOTH success and every error
    except ValueError:
        body = {"result": "error", "code": "NON_JSON_RESPONSE", "msg": resp.text[:200]}
    return resp.status_code, body


def post_to_zulip(lines: list[str]) -> bool:
    """Send every confirmed change this run as one Zulip channel message; one retry on a rate limit."""
    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:                     # MAX_MESSAGE_LENGTH is counted in Unicode code points, not bytes
        text = text[: MAX_TEXT_CHARS - 20].rsplit("\n", 1)[0] + "\n- ...(truncated)"
    status, body = _send(text)
    if status == 429 and body.get("code") == "RATE_LIMIT_HIT":
        # the server duplicates the wait time into the JSON body as "retry-after" (lowercase, hyphenated,
        # fractional seconds) on top of the Retry-After HTTP header, so a client that already parses the
        # body never needs to also read response headers to back off correctly
        wait = float(body.get("retry-after", 1.0))
        print(f"zulip rate limited, retry-after={wait:.1f}s, retrying once")
        import time
        time.sleep(min(wait, 5.0))                     # capped for the test harness; a real deployment waits the full amount
        status, body = _send(text)
    if body.get("result") != "success":
        # the machine-readable field is "code" (e.g. BAD_REQUEST, STREAM_DOES_NOT_EXIST, INVALID_API_KEY);
        # "msg" is translated into the sending account's own language and must never be pattern-matched on
        print(f"zulip post failed: {status} code={body.get('code')} msg={body.get('msg')}")
        return False
    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_zulip([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_zulip(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; [zulip] = the message sent)

--- run 1 (illustrative ASINs and sellers)
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 2, B0EXAMPLE2 lost (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 3, same reading confirmed
[zulip] **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, 1 change line(s)
--- run 4, back to mine (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent, 0 change line(s)
--- run 5, back to mine, confirmed
[zulip] **Amazon Buy Box change, confirmed on 2 checks:**
- B0EXAMPLE2: BACK, you hold the Buy Box again
3 checked, 1 alert(s) sent, 1 change line(s)

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

curl -s -X POST https://your-org.zulipchat.com/api/v1/messages \
  -u buybox-bot@example.com:test-zulip-key \
  --data-urlencode type=stream \
  --data-urlencode to=buy-box-alerts \
  --data-urlencode topic="Buy Box" \
  --data-urlencode 'content=**Amazon Buy Box change, confirmed on 2 checks:**
- 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
# {"result": "success", "msg": "", "id": 42}
Blueprint flow: offers check per ASIN, two-check confirmation, then one Zulip REST API call
A reading has to repeat before it reaches Zulip; failed calls change nothing.

How do I set up the Zulip bot?

  1. Create a generic botIn the Zulip web app, go to Personal settings > Bots > Add a new bot, pick Generic bot, name it and create it.
  2. Get the bot's email and API keyOpen the new bot's own settings; its email address and API key are both there. Store both as secrets, since either one alone is useless without the other.
  3. Subscribe the bot to the channelAdd the bot as a subscriber of the channel it should post into (Channel settings > Subscribers), or the send call fails with an authorization error even with a valid key.
  4. Send a test messagecurl -X POST https://your-org.zulipchat.com/api/v1/messages -u bot-email:api-key --data-urlencode type=stream --data-urlencode to=general --data-urlencode topic=test --data-urlencode content=test from a terminal; a {"result": "success"} 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 bot email + API key together let anyone post as this bot)
export SELLERMAGNET_API_KEY="your-key-here"
export ZULIP_SITE="https://your-org.zulipchat.com"
export ZULIP_BOT_EMAIL="buybox-bot@your-org.zulipchat.com"
export ZULIP_API_KEY="your-bot-api-key-here"
export ZULIP_CHANNEL="buy-box-alerts"
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_zulip_alert.py >> alert.log 2>&1

Zulip's own API documentation (zulip.com/api/send-message and zulip.com/api/rest-error-handling, checked 2026-11-25) describes the contract the script relies on: the request is form-encoded (type, to, topic, content), authenticated with HTTP Basic auth, never a bare webhook URL. The response is always JSON, success or error, with a result field and, on an error, a machine-readable code (for example STREAM_DOES_NOT_EXIST or INVALID_API_KEY) that the script checks instead of the translated msg text. A rate limit (429) carries code: RATE_LIMIT_HIT and a retry-after field in the JSON body itself, duplicating the Retry-After HTTP header, which the script reads before retrying once.

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; Zulip itself charges nothing extra for sending messages through its own API on a plan you already have. 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.

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

Why does this script authenticate with a username and password instead of a webhook URL?

Zulip has no generic incoming-webhook endpoint that accepts an arbitrary custom JSON payload the way Slack, Teams, Discord or Mattermost do. Its own incoming-webhook framework (checked on zulip.readthedocs.io, Incoming webhooks overview) only runs pre-registered integrations shipped in Zulip's own codebase, each with its own expected payload shape. A custom alert instead calls Zulip's REST API directly (POST /api/v1/messages) using HTTP Basic auth with a bot's email and API key, so there are two secrets to store, not one opaque URL.

Is the message sent as JSON, like most webhook integrations?

No. The send-message endpoint takes regular form-encoded POST parameters (type, to, topic, content), matching Zulip's own curl --data-urlencode examples (zulip.com/api/send-message, checked 2026-11-25), not a JSON request body. The response, on the other hand, is always JSON, on both success and every error.

What is the character limit for a Zulip message?

There is no single fixed number: Zulip's own API docs tell clients to read max_message_length from the POST /register response rather than hardcode a figure, because each realm (server/organization) can configure its own. The out-of-the-box default is 10,000 Unicode code points (zproject/default_settings.py MAX_MESSAGE_LENGTH, checked 2026-11-25) - a code-point cap, not a byte cap like ntfy's 4,096 B or Google Chat's 32,000 B.

What happens when the script gets rate limited?

Zulip answers HTTP 429 with a JSON body carrying code RATE_LIMIT_HIT and a retry-after field (lowercase, hyphenated) in fractional seconds, in addition to the usual Retry-After HTTP header (zulip.com/api/rest-error-handling and Zulip's own RateLimitedError source, both checked 2026-11-25). The script reads the value out of the JSON body - a client that only parses response bodies never needs to also read response headers to back off correctly - and retries the post exactly once before giving up.

Why does the post need both a channel ('to') and a 'topic' parameter?

Every Zulip channel message carries a topic; it is how Zulip groups messages into threads inside a channel. None of the other alert channels in this series have an equivalent required field: a Slack or Discord webhook message has no required topic/thread for a first post. Sending every alert with the same fixed topic ("Buy Box") keeps them threaded together instead of scattering across the channel's default view.

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 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 call Zulip's REST API directly with HTTP Basic auth, since there is no webhook URL to POST a custom JSON body to - remembering that a 429's retry time is duplicated into the JSON body, not just the response header. 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.

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