Home / Blog / Amazon Buy Box Lost Alert in Gotify: Self-Hosted Push, No ok Field

Amazon Buy Box Lost Alert in Gotify: Self-Hosted Push, No ok Field

Get an Amazon Buy Box lost alert pushed to your own Gotify server: 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 POST /message once per run. No fixed vendor domain, no webhook secret in a URL, just your server's own address and an app token. Costs one credit per ASIN per check.

November 26, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script pushed via Gotify

To get an Amazon Buy Box lost alert pushed to Gotify today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and call your own Gotify server's POST /message once per run: https://<your-server>/message with title, message and priority, authenticated by an app token in the X-Gotify-Key header. No fixed vendor domain and no secret baked into a webhook URL like Mattermost or Rocket.Chat; the server address itself is yours. The script below tells a lost Buy Box apart from a suppressed one, sends an explicit priority on every call, and costs one SellerMagnet credit per ASIN per check.

Key Takeaways

  • The message endpoint is not a fixed vendor domain: it is the URL of your own self-hosted Gotify server, the only channel in this series where that is true.
  • A successful POST /message always answers HTTP 200 with the full created message echoed back as JSON (id, appid, message, title, priority, date) - never a boolean ok/success field like Telegram's ok or Rocket.Chat's {"success": true}.
  • An omitted priority does not default to 0 server-side; it falls back to the sending application's own configured DefaultPriority (server/api/message.go), so this script sends a fixed priority on every call instead of leaving it out.
  • buyBox is the featured offer: its sellerId is the seller who holds the Buy Box, the literal "Amazon" when Amazon does.
  • 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.
  • 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 Gotify's POST /message different from Telegram, Webex or Rocket.Chat?

Every other channel in this series posts to a fixed address the vendor controls (api.telegram.org, webexapis.com, a company's own Rocket.Chat instance reached by a shared webhook path). Gotify is self-hosted: the base URL is whatever address the user's own server answers on, so this script takes it as a required setting, not a constant. Authentication is an app token (gotify.net/api-docs, checked 2026-11-26), sent as the X-Gotify-Key header (a token query parameter also works per the docs, but a header keeps it out of access logs). A successful call answers 200 with the full message object the server just created and assigned an id to; there is no separate ok/success field to check at all, unlike every sibling channel.

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

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_gotify() sends every queued line as one POST /message call. 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. A new ASIN seeds its state to whatever it first reads, so a listing that starts out suppressed never fires a false alert just for staying that way. priority is always sent explicitly, and lines are capped and summarized well before any practical message-size ceiling.

buybox_gotify_alert.py - offers check, 2-check confirmation, one POST /message 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 Gotify 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_MESSAGE_CHARS = 32768                         # gotify.net has no documented hard cap (sqlite/postgres TEXT);
                                                   # 32768 is the practical ceiling Apprise's Gotify notifier uses
MAX_LINES = 200                                   # keep well under the char cap even with long lines
GOTIFY_PRIORITY = 5                               # explicit: an omitted priority falls back to the APP's own
                                                   # configured DefaultPriority server-side, not 0 (server/api/
                                                   # message.go CreateMessage, checked 2026-11-26)


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))]
    detail += f", your offer {min(mine):.2f}" if mine else ", your offer: not on the first offer page"
    return "lost", detail                      # any other holder is the same reading: a rotation still confirms


def line_for(asin: str, key: str, detail: str) -> str:
    text = {"mine": "BACK, you hold the Buy Box again",
            "suppressed": "NONE, offers exist but Amazon features none",
            "no-offers": "EMPTY, no offers on the listing"}.get(key, f"LOST, held by {detail}")
    return f"{asin}: {text}"


def build_message(lines: list[str]) -> str:
    # No documented hard cap; summarize anyway so one push notification stays readable on a phone.
    if len(lines) > MAX_LINES:
        lines = lines[:MAX_LINES] + [f"+{len(lines) - MAX_LINES} more, see the dashboard"]
    header = "Amazon Buy Box change, confirmed on 2 checks:\n"
    body = header + "\n".join(lines)
    while len(body) > MAX_MESSAGE_CHARS and lines:
        lines = lines[:-1] + ["+1 more, see the dashboard"]
        body = header + "\n".join(lines)
    return body


def post_to_gotify(base_url: str, token: str, lines: list[str]) -> bool:
    """One message per run. Unlike every sibling channel in this series, the endpoint itself is not a fixed
    vendor domain: it is the URL of the user's OWN self-hosted Gotify server (gotify.net/api-docs, checked
    2026-11-26), so a wrong or unreachable base_url is a real possibility this script has to report, not just
    a wrong token. The app token goes in the `X-Gotify-Key` header (a query-string `token` param also works per
    the docs, but a header keeps the token out of access logs). A successful POST always answers HTTP 200 with
    the full created message echoed back as JSON - id, appid, message, title, priority, date - never a boolean
    `ok`/`success` flag like every other channel in this family. `priority` is sent explicitly on every call:
    the server falls back to the sending application's own configured DefaultPriority when it is omitted
    (server/api/message.go CreateMessage: `if message.Priority == nil { message.Priority = &app.DefaultPriority }`),
    not to 0, so an omitted priority is not a safe default to assume. A 401 (bad or revoked app token) or a 400
    (empty message) are real input problems and are never retried; the API has no documented retryable 4xx."""
    if not lines:
        return True
    payload = {"title": "Amazon Buy Box Alert", "message": build_message(lines), "priority": GOTIFY_PRIORITY}
    url = f"{base_url.rstrip('/')}/message"
    try:
        resp = requests.post(url, json=payload, headers={"X-Gotify-Key": token}, timeout=10)
    except requests.RequestException as err:
        print(f"gotify unreachable: {type(err).__name__}")
        return False
    try:
        body = resp.json()
    except ValueError:
        body = {}
    if resp.status_code == 200 and body.get("id") is not None:
        return True
    print(f"gotify rejected the message: {resp.status_code} {body.get('error') or body}")   # input problem
    return False


def load_state() -> dict:
    try:
        with open(STATE_FILE, encoding="utf-8") as fh:
            return json.load(fh)
    except FileNotFoundError:
        return {}


def save_state(state: dict) -> None:
    tmp = STATE_FILE + ".tmp"
    with open(tmp, "w", encoding="utf-8") as fh:
        json.dump(state, fh, indent=1, sort_keys=True)
    os.replace(tmp, STATE_FILE)                     # a crash mid-write keeps the last good state


def check(asins: list[str], base_url: str, token: str) -> None:
    session, state = new_session(), load_state()
    alerts, problems, checked, stopped = [], [], 0, ""
    for asin in dict.fromkeys(a.strip().upper() for a in asins):            # dedupe, keep order
        if not ASIN_RE.match(asin):
            problems.append(f"{asin}: not an ASIN, skipped")
            continue
        try:
            key, detail = read_buy_box(session, asin)
        except ApiError as err:
            if err.status in (401, 403):
                stopped = str(err)                       # bad key or no credits: every further call fails too
                problems.append(f"stopped: {stopped}")
                break
            problems.append(f"{asin}: {err}")            # 404 = listing gone (billed); state stays as it was
            continue
        except requests.RequestException as err:
            problems.append(f"{asin}: {type(err).__name__} after retries, state kept")
            continue
        checked += 1
        s = state.get(asin)
        if s is None:
            # first-ever sighting of this ASIN: seed state to it so a steady reading never alerts as a change
            s = state[asin] = {"last": key, "streak": 1, "reported": key}
            continue
        s["streak"] = s["streak"] + 1 if key == s["last"] else 1
        s["last"] = key
        if s["streak"] >= CONFIRM and key != s["reported"]:
            alerts.append((asin, key, line_for(asin, key, detail)))
    lines = [line for _, _, line in alerts]
    if stopped and state.get("_stopped") != stopped:
        lines.append(f"STOP: checks stopped: {stopped}")       # said once, not every run
    sent = post_to_gotify(base_url, token, lines)
    if sent:
        for asin, key, _ in alerts:
            state[asin]["reported"] = key               # only after Gotify echoed the created message, else re-sent
        if stopped:
            state["_stopped"] = stopped
    if not stopped:
        state.pop("_stopped", None)
    save_state(state)
    for line in problems:
        print(line)
    print(f"{checked} checked, {len(alerts)} alert(s) {'sent' if sent else 'NOT sent, retried next run'}")


if __name__ == "__main__":
    check(ASINS, os.environ["GOTIFY_URL"], os.environ["GOTIFY_APP_TOKEN"])

Five runs of the script (illustrative ASIN and seller; [gotify] = the message sent)

--- run 1 (illustrative ASIN and seller)
1 checked, 0 alert(s) sent
--- run 2, B0EXAMPLE2 lost (1st sighting, not yet confirmed)
1 checked, 0 alert(s) sent
--- run 3, same reading confirmed
1 checked, 1 alert(s) sent
[gotify] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99
--- run 4, back to mine (1st sighting, not yet confirmed)
1 checked, 0 alert(s) sent
--- run 5, back to mine, confirmed
1 checked, 1 alert(s) sent
[gotify] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: BACK, you hold the Buy Box again

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

curl -s -X POST https://push.example.com/message \\
  -H "X-Gotify-Key: AgTeStT0k3n12345" \\
  -H "Content-Type: application/json" \\
  -d '{"title": "Amazon Buy Box Alert", "priority": 5, "message":
"Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"}'
# {"id": 42, "appid": 7, "message": "...", "title": "Amazon Buy Box Alert", "priority": 5,
#  "date": "2026-11-26T07:00:00.000Z"}
Blueprint flow: offers check per ASIN, two-check confirmation, then one POST /message call
A reading has to repeat before it reaches Gotify; failed calls change nothing.

How do I create the Gotify app and get a token?

  1. Run a Gotify serverSelf-hosted: download the server yourself (gotify/server) and run it, or use a prebuilt binary from gotify.net. There is no shared public server; it is yours to run and address.
  2. Create an applicationLog into the Gotify web UI, open Apps, click Create Application, name it. Gotify hands you its app token once, shown only at creation.
  3. Note the server's own URLWhatever address the server answers on (for example https://push.example.com); this is GOTIFY_URL, not a vendor domain.
  4. Send a test messagecurl -H "X-Gotify-Key: <apptoken>" -F "title=test" -F "message=hello" -F "priority=5" https://push.example.com/message; the response should echo back an id.

Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)

# .env (keep it out of git: the app token lets anyone push through your server as this app)
export SELLERMAGNET_API_KEY="your-key-here"
export GOTIFY_URL="https://push.example.com"        # your own server, not a vendor domain
export GOTIFY_APP_TOKEN="AgTeStT0k3n12345"           # created once in the Gotify web UI, shown only then
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_gotify_alert.py >> alert.log 2>&1

Gotify's own documentation (gotify.net/api-docs and the server's own source at server/api/message.go, both checked 2026-11-26) describe the contract the script relies on: every successful call gets the full created message echoed back with a server-assigned id, there is no ok/success flag anywhere in the response, and an omitted priority is not guaranteed to be 0 (it falls back to the sending application's own configured default). There is no documented message-length cap on the official API; most real deployments store it without a hard limit; a 400 (empty message) or 401 (bad token) are real input problems and must not be retried unchanged, while a 5xx or connection failure is the server's own temporary problem, logged and left for the next run rather than retried.

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; your own Gotify server has whatever cost or free tier you already chose when you set it up, unrelated to SellerMagnet credits. With a 2-check confirmation the worst-case delay before Gotify 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) 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

Do I need to register anywhere before I can send a Gotify push?

You need your own Gotify server (download and run it yourself, gotify.net) and one application created in it, which hands you an app token. Unlike every other channel in this series, the message endpoint itself is not a fixed vendor domain: it is YOUR server's own URL plus /message, so a typo in GOTIFY_URL or a server that is down is a real failure mode this script has to report, separate from a bad token.

Does Gotify's response look like Telegram's ok or Webex's created-message echo?

Closer to Webex than Telegram: a successful POST /message answers HTTP 200 with the full created message echoed back as JSON (id, appid, message, title, priority, date), never a boolean ok/success flag (gotify.net/api-docs, checked 2026-11-26). The script checks that body.get("id") is set, not a status field that does not exist on this API at all.

Why does the script always send priority explicitly instead of leaving it out?

Gotify's server does not default an omitted priority to 0. Reading the server source (server/api/message.go, CreateMessage, checked 2026-11-26): "if message.Priority == nil { message.Priority = &app.DefaultPriority }", so an omitted priority silently falls back to whatever the sending application happens to be configured with, which can be anything. Sending a fixed priority on every call keeps the alert's urgency predictable regardless of app settings.

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 app token is wrong or the Gotify server is unreachable?

A bad or revoked app token answers 401 with {"error": "Unauthorized", ...}; the script logs it and leaves the alert unreported for the next run. A connection error or timeout (server down, wrong GOTIFY_URL) is caught the same way, never retried, since neither is a documented retryable condition in the Gotify API.

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, sends 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 send one Gotify POST /message call per run to your own server - check the echoed id, never a boolean flag that this API does not have. 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 signal-cli-rest-api
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Signal: signal-cli-rest-api /v2/send, No Idempotency

Get an Amazon Buy Box lost alert posted into a Signal chat through your own signal-cli-rest-api container: 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 to /v2/send. Covers the quoted-string timestamp, why a dropped response can duplicate the alert with no idempotency key to stop it, and the 429 rate-limit captcha flow. Tested Python, one credit per ASIN per check.

Nov 26, 2026 Read
Code editor showing a Power Query M function that calls the SellerMagnet API with Web.Contents RelativePath and Query
Ecommerce Amazon API Data Analytics

Amazon Product Data in Power BI with Power Query

Pull Amazon Buy Box prices and bestseller ranks into Power BI with a Power Query M function: one call per ASIN, a stored Web API key so the dataset actually refreshes on a schedule in the Power BI Service, and the one M mistake that silently breaks that schedule.

Nov 25, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted via the Zulip REST API
Amazon API Buy Box Alerts

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.

Nov 25, 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