To get an Amazon Buy Box lost alert posted into Signal today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST one JSON message to your own signal-cli-rest-api container's /v2/send. The script below sends one message per confirmed change, tells a lost Buy Box apart from a suppressed one, and - because Signal's send endpoint carries no idempotency key at all - deliberately does not retry a dropped response, trading a theoretical missed retry for never risking a duplicate alert.
The exact text the chat receives (illustrative ASIN and seller)
Amazon Buy Box change, confirmed on 2 checks: - B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, yours 19.99
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 from the last reading actually sent: a brand-new ASIN seeds its starting reading without alerting.
- A successful send answers HTTP 201 with JSON {"timestamp": "..."} - a STRING, even though the value is a millisecond epoch and the Swagger doc types the field as an integer.
- POST /v2/send has no idempotency token: unlike Matrix's txnId or a webhook chat platform's dedup key, retrying a dropped-response send can deliver the same message twice.
- A 429 means Signal itself is rate-limiting the sending number and ships challenge_tokens for a manual CAPTCHA; there is no Retry-After, so the script reports it instead of retrying.
- 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 before anything reaches Signal.
How do I send a message into Signal from a script?
Run your own signal-cli-rest-api (github.com/bbernhard/signal-cli-rest-api) container (checked 2026-11-25) and register or link it to a Signal number - linking as a secondary device via GET /v1/qrcodelink?device_name=... and scanning the QR code from your phone's Settings > Linked devices is the fastest path if you already use Signal on that number. Sending itself is one POST to /v2/send with a JSON body of message (the text), number (your registered/linked sender, E.164 format) and recipients (an array of E.164 numbers and/or group.<base64-id> strings). There is no official Signal bot API and no vendor to authenticate a token against - the container IS the account, so anyone who can reach it can send as that number.
| Response | Reading | Signal message |
|---|---|---|
| buyBox.sellerId is your sellerId | mine | silent (BACK only fires after a confirmed loss first) |
| buyBox.sellerId is any other seller or "Amazon" | lost | LOST, with holder, price and your offer |
| buyBox is {} and buyBoxSuppressed is true | suppressed | SUPPRESSED, no featured offer shown |
| buyBox is {} and offers is [] | no-offers | no offers found at all |
How do I build the Amazon Buy Box lost alert for Signal?
read_buy_box() turns one offers response into a reading, check() keeps a per-ASIN streak plus the reading it last actually sent in buybox_state.json, and post_to_signal() POSTs every queued line as one chat message. 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. A fresh ASIN's FIRST confirmed reading - whatever it is - is seeded into state silently, so deploying the script against an ASIN that is already lost does not immediately fire a backstory alert; only a genuine change from that seeded baseline sends a message.
buybox_signal_alert.py - offers check, 2-check confirmation, one POST per confirmed change
"""Post an Amazon Buy Box lost alert to a Signal chat via a self-hosted signal-cli-rest-api container.
Uses only the real sellermagnet.py / retry.py helpers (see the Python quickstart) for SellerMagnet calls.
The Signal send itself goes straight through requests.post to your own signal-cli-rest-api instance -
there is no official Signal bot API and no hosted vendor to authenticate against.
"""
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 Signal hears about it
STATE_FILE = "buybox_state.json"
ASIN_RE = re.compile(r"\A[A-Z0-9]{10}\Z") # offers calls are billed even for a typo, so filter first
SIGNAL_API_URL = os.environ["SIGNAL_API_URL"].rstrip("/") # e.g. http://127.0.0.1:8080, your own container
SIGNAL_NUMBER = os.environ["SIGNAL_NUMBER"] # the registered/linked sender number, E.164
SIGNAL_RECIPIENTS = json.loads(os.environ["SIGNAL_RECIPIENTS"]) # ["+1...", ...] or ["group.XXXX="]
MAX_LINES = 20
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", yours {min(mine):.2f}" if mine else "" # keep the line short
return "lost", detail # any other holder is the same reading: a rotation still confirms
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(state: dict, asin: str, key: str, detail: str) -> str | None:
"""Advance the per-ASIN streak; return one message line only once a reading repeats CONFIRM times AND it
is a CHANGE from the last reading actually sent - so a brand-new ASIN seeds its first streak silently."""
entry = state.get(asin, {"streak_key": None, "streak": 0, "sent_key": None, "seeded": False})
if key == entry["streak_key"]:
entry["streak"] += 1
else:
entry = {"streak_key": key, "streak": 1, "sent_key": entry["sent_key"], "seeded": entry["seeded"]}
state[asin] = entry
if entry["streak"] < CONFIRM or key == entry["sent_key"]:
return None
if not entry["seeded"]:
entry["seeded"] = True
entry["sent_key"] = key # seed silently: a freshly deployed ASIN never fires a backstory alert
return None
entry["sent_key"] = key
if key == "mine":
return f"- {asin}: BACK, Buy Box recovered"
if key == "lost":
return f"- {asin}: LOST, held by {detail}"
if key == "suppressed":
return f"- {asin}: SUPPRESSED, no featured offer shown"
return f"- {asin}: no offers found at all"
def post_to_signal(lines: list[str]) -> dict:
"""POST one chat message to /v2/send, once, no retry. A 201 carries the send timestamp as a JSON STRING
(observed, not the int64 the swagger doc types it as). A 400 means the payload or the sender account
itself is wrong. A 429 means the Signal server itself is rate-limiting this account and needs a manual
captcha via /v1/accounts/{number}/rate-limit-challenge - unlike a SellerMagnet 429, retrying it blindly
only risks tripping the SAME rate limit again, since Signal gives no Retry-After to wait out."""
text = "Amazon Buy Box change, confirmed on 2 checks:\n" + "\n".join(lines[:MAX_LINES])
payload = {"message": text, "number": SIGNAL_NUMBER, "recipients": SIGNAL_RECIPIENTS}
resp = requests.post(f"{SIGNAL_API_URL}/v2/send", json=payload, timeout=30)
try:
body = resp.json()
except ValueError:
body = {}
if resp.status_code == 201:
return {"accepted": True, "status": 201, "timestamp": body.get("timestamp")}
return {"accepted": False, "status": resp.status_code, "message": body.get("error", "request failed"),
"challenge_tokens": body.get("challenge_tokens")}
def main() -> None:
session = new_session()
state = load_state()
lines: list[str] = []
for asin in ASINS:
if not ASIN_RE.match(asin):
print(f"SKIP {asin}: not a well-formed ASIN, not billed")
continue
try:
key, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
print(f"STOP: {err.status} on {asin}, run ended early (free, not billed)")
break
print(f"SKIP {asin}: {err.status} {err}") # 404 billed-not-retried, 502/503 billed-and-capped
continue
line = check(state, asin, key, detail)
if line:
lines.append(line)
save_state(state)
if not lines:
print(f"{len(ASINS)} checked, 0 Signal message(s) sent, 0 change line(s)")
return
result = post_to_signal(lines)
if result["accepted"]:
print(f"signal post ok: timestamp={result['timestamp']!r} (string)")
else:
extra = f" challenge_tokens={result['challenge_tokens']}" if result.get("challenge_tokens") else ""
print(f"signal post FAILED: HTTP {result['status']} {result['message']}{extra}")
print(f"{len(ASINS)} checked, {1 if result['accepted'] else 0} Signal message(s) sent, {len(lines)} change line(s)")
if __name__ == "__main__":
main()
Eight runs of the script (illustrative ASINs and sellers; only B0EXAMPLE2 ever changes)
--- run 1 (all three hold the Buy Box, 1st sighting)
3 checked, 0 Signal message(s) sent, 0 change line(s)
--- run 2 (all three confirmed, baseline seeded silently, no backstory alert)
3 checked, 0 Signal message(s) sent, 0 change line(s)
--- run 3: B0EXAMPLE2 loses the Buy Box (1st sighting, not confirmed yet)
3 checked, 0 Signal message(s) sent, 0 change line(s)
--- run 4: same reading confirmed, a real CHANGE from the seeded baseline, Signal message sent
signal post ok: timestamp='1764158401234' (string)
3 checked, 1 Signal message(s) sent, 1 change line(s)
--- run 5: B0EXAMPLE2 is back (1st sighting, not confirmed yet)
3 checked, 0 Signal message(s) sent, 0 change line(s)
--- run 6: recovery confirmed, Signal message sent
signal post ok: timestamp='1764158701998' (string)
3 checked, 1 Signal message(s) sent, 1 change line(s)
--- run 7: B0EXAMPLE2 loses it again (1st sighting, not confirmed yet)
3 checked, 0 Signal message(s) sent, 0 change line(s)
--- run 8: confirmed again, but the Signal account itself is rate-limited
signal post FAILED: HTTP 429 Failed to send message due to rate limiting. challenge_tokens=['chl-9f2a0']
3 checked, 0 Signal message(s) sent, 1 change line(s)
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST "http://127.0.0.1:8080/v2/send" \
-H "Content-Type: application/json" \
-d '{"message": "Amazon Buy Box change, confirmed on 2 checks:\n- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, yours 19.99", "number": "+15550001111", "recipients": ["+15550002222"]}'
# HTTP/1.1 201 Created
# Content-Type: application/json
# {"timestamp": "1764158401234"}

How do I get a Signal sender number and recipients?
Run your own signal-cli-rest-api container (your own host, your own volume)
docker run -d -p 8080:8080 \
-v $HOME/.local/share/signal-api:/home/.local/share/signal-cli \
-e 'MODE=native' bbernhard/signal-cli-rest-api
- Run your own containerStart your own signal-cli-rest-api container with the command above; keeping the registration on your own mounted volume lets you recreate your container later without re-linking.
- Link it as a secondary deviceOpen
http://localhost:8080/v1/qrcodelink?device_name=buybox-alertin a browser, then scan the QR code from Signal on your phone under Settings > Linked devices > Link new device. - Note the sender numberThe number that just linked (in E.164, e.g.
+15550001111) is thenumberfield in every/v2/sendcall from this container. - Pick recipientsA direct chat recipient is the other person's E.164 number; a group recipient is the base64 group ID from
GET /v1/groups, prefixedgroup.(e.g.group.abCDEf123...=). - Send a test message
curl -X POST -H 'Content-Type: application/json' -d '{"message": "test", "number": "+15550001111", "recipients": ["+15550002222"]}' 'http://localhost:8080/v2/send'- a 201 with atimestampstring 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: anyone who can reach the container can send as this number)
export SELLERMAGNET_API_KEY="your-key-here"
export MY_SELLER_ID="A1MYSELLER0001" # your sellerId as it appears in offers[]
export SIGNAL_API_URL="http://127.0.0.1:8080" # your own signal-cli-rest-api container, no trailing slash
export SIGNAL_NUMBER="+15550001111" # the number linked to that container
export SIGNAL_RECIPIENTS='["+15550002222"]' # JSON array: E.164 numbers and/or "group.<base64-id>"
# 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_signal_alert.py >> alert.log 2>&1
signal-cli-rest-api (github.com/bbernhard/signal-cli-rest-api, checked 2026-11-25) describes the contract the script relies on: a successful POST /v2/send answers HTTP 201 with a JSON body whose timestamp field is a STRING, built with Go's strconv.FormatInt on the server side even though the underlying value is a millisecond epoch integer - a script that expects a bare JSON number will mis-parse it. A 400 has been observed in the wild both for a malformed payload and for "Specified account does not exist" when the sender number was never linked; a 429 carries a challenge_tokens array tied to Signal's own captcha flow, documented in the project's rate-limit-challenge endpoint, and is not something a client-side retry can wait out.
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 signal-cli-rest-api container costs nothing extra per message to post into. With a 2-check confirmation the worst-case delay before the chat 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.
| 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
Why does signal-cli-rest-api return the send timestamp as a string, not a number?
Its own Swagger schema types SendMessageResponse.Timestamp as a string, and the server builds it with strconv.FormatInt before writing the JSON - so a successful send answers HTTP 201 with a BODY like {"timestamp": "1744489180018"}, quotes included, even though it is really a millisecond epoch. A script that does int(body['timestamp']) works; one that assumes a bare JSON number does not.
Does a retry of a dropped Signal send risk a duplicate message?
Yes, and there is no defense against it on the Signal side: unlike Matrix's txnId or a webhook chat platform's dedup key, POST /v2/send carries no idempotency token at all, so retrying a request whose response was merely lost (not actually rejected) can deliver the same alert twice. That is exactly why this script sends once per confirmed change and does not retry on a dropped connection - a duplicate LOST message is a minor annoyance, a missed one is the actual risk this alert exists to avoid.
What does a 429 from signal-cli-rest-api actually mean, and can the script retry it?
It means the Signal server itself - not your container - is rate-limiting that phone number, and the response carries a challenge_tokens array for a CAPTCHA you solve by hand at signalcaptchas.org and submit to POST /v1/accounts/{number}/rate-limit-challenge. There is no Retry-After header to wait out, so an automatic retry just resends into the same limit; the script reports the 429 and the tokens instead of looping on it.
Why does the script separate 400 from 429 instead of treating every non-201 as the same failure?
A 400 (seen in practice for a malformed payload or an unregistered/unlinked sender number) will not go away on its own retry - it needs a code or configuration fix - while a 429 is a Signal-side rate limit that needs the captcha flow above. Logging them identically would hide which one actually applies.
Is a group recipient handled differently from a phone number recipient?
Not in the request shape: both go in the same recipients array in the POST /v2/send body, a phone number as E.164 ("+4****45...") and a group as the base64 group ID returned when the group was created or listed, prefixed "group." ("group.abCDEf123...="). The script treats SIGNAL_RECIPIENTS as an opaque list either way.
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 and sends nothing to Signal for that run, rather than posting a partial or misleading message.
Bottom line: compare buyBox.sellerId with your own seller ID, keep a per-ASIN streak, and POST one Signal message per confirmed CHANGE from the seeded baseline - remembering that the success body's timestamp is a quoted string, that there is no idempotency key so a dropped response is reported rather than retried, and that a 429 needs a manual captcha, not a loop. 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.