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.
| Response | Reading | Gotify 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 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"}

How do I create the Gotify app and get a token?
- 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. - 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.
- Note the server's own URLWhatever address the server answers on (for example
https://push.example.com); this isGOTIFY_URL, not a vendor domain. - Send a test message
curl -H "X-Gotify-Key: <apptoken>" -F "title=test" -F "message=hello" -F "priority=5" https://push.example.com/message; the response should echo back anid.
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.
| 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
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.