To get an Amazon Buy Box lost alert by SMS, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and send one text through Twilio's Messages API only when the same reading shows up on two checks in a row. The script below sends one SMS per run, tells a lost Buy Box apart from a suppressed one, and treats Twilio's answer for what it actually is: confirmation that the message was queued, not that it was delivered.
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 text your phone.
- Twilio's 2xx answer on a Message create means queued, not delivered; status moves to sent, delivered, undelivered or failed later, which this script does not poll for.
- A 429 from Twilio is always safe to retry with backoff; a 401 (bad credentials) or a 400 (invalid 'To' number) is not - retrying repeats the same answer.
What does the offers endpoint tell you about who holds the Buy Box?
/amazon-product-offers reads one page of the live offer listing. buyBox is the featured offer with sellerId, sellerName and totalPrice; Amazon itself appears as the literal "Amazon" with its own ID in amazonSellerId. When buyBox is an empty object, buyBoxSuppressed says why: true means offers exist but Amazon shows no featured offer, false with an empty offers list means there is nothing to feature. The script maps every response to one of four readings; any holder other than you is the same lost reading, so a Buy Box that rotates between two other sellers still confirms a loss. Field details are in the Offer Listing API guide.
| Response | Reading | SMS text |
|---|---|---|
| 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 SMS alert?
read_buy_box() turns one offers response into a reading, check() keeps a streak per ASIN in buybox_state.json and queues a message once a new reading has been seen CONFIRM times in a row, and send_sms() POSTs all queued messages as one Twilio 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 LOST message names the holder, its fulfillment type and total price, and your own offer when it is on the first offer page, which is all the endpoint returns.
buybox_sms_alert.py - offers check, 2-check confirmation, one Twilio SMS 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 an SMS goes out
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
TWILIO_BASE = "https://api.twilio.com/2010-04-01"
TWILIO_ACCOUNT_SID = os.environ["TWILIO_ACCOUNT_SID"]
TWILIO_AUTH_TOKEN = os.environ["TWILIO_AUTH_TOKEN"]
TWILIO_FROM_NUMBER = os.environ["TWILIO_FROM_NUMBER"] # E.164, e.g. "+15551234567"
ALERT_TO_NUMBER = os.environ["ALERT_TO_NUMBER"] # E.164, your own phone
SMS_RETRYABLE = {429, 500, 502, 503}
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 SMS short: no "not on first page" prose
return "lost", detail # any other holder is the same reading: a rotation still confirms
def message(asin: str, key: str, detail: str) -> str | None:
if key == "lost":
return f"LOST {asin}: {detail}" if detail else f"LOST {asin}"
if key == "back":
return f"BACK {asin}: you hold the Buy Box again"
return None
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 a queued message only once a reading repeats CONFIRM times."""
entry = state.get(asin, {"streak_key": None, "streak": 0, "alerted": None})
if key == entry["streak_key"]:
entry["streak"] += 1
else:
entry = {"streak_key": key, "streak": 1, "alerted": entry["alerted"]} # keep 'alerted' across a reset
state[asin] = entry
if entry["streak"] < CONFIRM:
return None
if key == "mine":
if entry["alerted"] == "lost":
entry["alerted"] = None
return message(asin, "back", "")
return None
if key == "lost" and entry["alerted"] != "lost":
entry["alerted"] = "lost"
return message(asin, "lost", detail)
return None
def send_sms(body: str, attempts: int = 4) -> dict:
"""POST one SMS via the Twilio Messages resource. 429/5xx are safe to retry; everything else is not."""
url = f"{TWILIO_BASE}/Accounts/{TWILIO_ACCOUNT_SID}/Messages.json"
last = {"accepted": False, "status": None, "error_code": None, "error_message": "no attempt made"}
for attempt in range(1, attempts + 1):
resp = requests.post(
url, auth=(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN), timeout=15,
data={"From": TWILIO_FROM_NUMBER, "To": ALERT_TO_NUMBER, "Body": body},
)
try:
body_json = resp.json()
except ValueError:
body_json = {}
if resp.status_code in (200, 201):
# 201 only means Twilio queued the message; it is not a delivery confirmation (status is
# 'queued' here, not 'delivered' - that needs a StatusCallback or a later fetch).
return {
"accepted": True, "sid": body_json.get("sid"), "status": body_json.get("status"),
"num_segments": body_json.get("num_segments"), "error_code": body_json.get("error_code"),
}
last = {
"accepted": False, "status": resp.status_code,
"error_code": body_json.get("code"), "error_message": body_json.get("message", "request failed"),
}
if resp.status_code not in SMS_RETRYABLE or attempt == attempts:
return last
time.sleep(min(2 ** attempt, 60))
return last
def main() -> None:
session = new_session()
state = load_state()
queued: 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
msg = check(state, asin, key, detail)
if msg:
queued.append(msg)
save_state(state)
if not queued:
print(f"{len(ASINS)} checked, 0 SMS sent")
return
body = "SellerMagnet Buy Box alert:\n" + "\n".join(queued)
result = send_sms(body)
if result["accepted"]:
segs = result.get("num_segments") or "?"
print(f"[twilio] accepted sid={result['sid']} status={result['status']} segments={segs}")
else:
print(f"[twilio] NOT accepted: HTTP {result['status']} code={result.get('error_code')} "
f"{result.get('error_message')}")
print(f"{len(ASINS)} checked, {len(queued)} alert(s) queued, SMS accepted={result['accepted']}")
if __name__ == "__main__":
main()
Five runs of the script (illustrative ASINs and sellers; [twilio] = the API's own answer)
--- run 1 (illustrative ASINs and sellers)
3 checked, 0 SMS sent
--- run 2, one check later: B0EXAMPLE2's Buy Box flips (1st sighting, not confirmed yet)
3 checked, 0 SMS sent
--- run 3: same reading confirmed, one SMS sent
[twilio] accepted sid=SM2f8a9c1e0b7d4a5f8e9c0d1a2b3c4d5e status=queued segments=1
3 checked, 1 alert(s) queued, SMS accepted=True
--- run 4: B0EXAMPLE2 is back (1st sighting, not confirmed yet)
3 checked, 0 SMS sent
--- run 5: back-in-stock confirmed, one SMS sent
[twilio] accepted sid=SM2f8a9c1e0b7d4a5f8e9c0d1a2b3c4d5e status=queued segments=1
3 checked, 1 alert(s) queued, SMS accepted=True
Twilio's own answer to a successful Message create (trimmed, example values)
{
"sid": "SM2f8a9c1e0b7d4a5f8e9c0d1a2b3c4d5e",
"status": "queued",
"num_segments": "1",
"error_code": null,
"error_message": null,
"price": null,
"price_unit": "USD"
}

Why isn't Twilio's answer a delivery confirmation?
Because sending an SMS is two steps, and the REST API only does the first one. Twilio's Messages resource starts at status: "queued" the moment the create call answers 2xx, then moves through sending, sent and finally delivered, undelivered or failed as the upstream carrier and, where available, the destination handset report back - all of that happens after the HTTP response the script already has. Reading the real outcome needs either a StatusCallback URL configured on the message, or a later GET on the same Message resource by its sid. This script does neither: it logs the sid and the initial status, and calls the send itself done once Twilio has accepted it. That is the opposite of the Slack webhook version of this alert, where the synchronous 200 ok IS the delivery confirmation (the webhook endpoint received it, full stop).
Why wait for a second check before sending the SMS?
Because a single reading can be wrong in a way that looks real. When an offer page comes back with offer blocks that cannot be parsed, the response is a 200 with an empty offers list, the same shape as a listing with no offers. With CONFIRM = 2 the script alerts on the second check that sees the same reading, so a loss reaches your phone one interval later than the first sighting and a one-off reading never does. A failed call (a billed 404, a 502 or 503 after four attempts, a timeout) neither confirms nor resets the streak. A recovery needs two mine readings too, so a Buy Box that flips back for one check does not send a BACK text.
How do I set up Twilio for the alert?
- Create a Twilio account and get a phone numberSign up at twilio.com, then buy or claim a trial number with SMS capability from the Console's Phone Numbers page.
- Copy the Account SID and Auth TokenBoth are on the Console dashboard. Store them as TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN, never in the script.
- Set the From and To numbersTWILIO_FROM_NUMBER is the Twilio number you just got; ALERT_TO_NUMBER is your own phone, both in E.164 format (for example +15551234567).
- Verify the recipient on a trial accountA Twilio trial account can only text numbers you have verified in the Console; a live account with a paid number has no such limit.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the Auth Token is a secret)
export SELLERMAGNET_API_KEY="your-key-here"
export TWILIO_ACCOUNT_SID="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
export TWILIO_AUTH_TOKEN="your-auth-token-here"
export TWILIO_FROM_NUMBER="+15551234567" # your Twilio number
export ALERT_TO_NUMBER="+15557654321" # your own phone
export MY_SELLER_ID="A1MYSELLER0001" # your sellerId as it appears in offers[]
# crontab -e: every 15 minutes, 3 ASINs = 288 SellerMagnet credits a day; flock -n skips an overlapping run
*/15 * * * * cd /opt/buybox && . ./.env && flock -n .lock .venv/bin/python buybox_sms_alert.py >> alert.log 2>&1
Which Twilio errors are safe to retry?
Only 429 and the 5xx range. Twilio's error 20429 ("Too many requests") means the account's REST API concurrency or rate limit was hit, and Twilio's own documentation calls every 429 safe to retry after backing off. A 401 means the Account SID or Auth Token is wrong, and a 400 with error 21211 means the To number is invalid or unroutable - neither improves on a second try, so the script gives up on those immediately instead of burning attempts and segments on an answer that cannot change.
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. Start with the gap between the holder's price and your offer in the text, then your delivery date and stock. The Buy Box price gap guide shows why the lowest price alone does not decide it.
How many SMS segments does an alert cost?
One segment per 160 GSM-7 characters (70 for UCS-2), and Twilio bills every segment it sends. Combining several ASINs into one message in one run keeps the segment count predictable instead of paying for N separate texts; the script's own num_segments read-back from Twilio's response shows the real count rather than assuming it. On top of that, each offers check still costs 1 SellerMagnet credit per ASIN regardless of whether it ends up alerting, the same as the Slack version of this alert.
| Alert size | Approx. body length | Segments | Twilio bills |
|---|---|---|---|
| 1 ASIN lost | under 160 chars | 1 | 1 |
| 2 ASINs lost in one run | around 190 chars | 2 | 2 |
| 3 ASINs lost in one run | around 230 chars | 2 | 2 |
| 4 ASINs lost in one run | around 280 chars | 2 | 2 |
| 5 ASINs lost in one run | around 330 chars | 3 | 3 |
| 8 ASINs lost in one run | around 480 chars | 4 | 4 |

Frequently Asked Questions
Does Twilio's 2xx response mean the SMS was delivered?
No. A 2xx on the create call only means Twilio accepted the message and queued it; status starts at queued and only later becomes sent, delivered, undelivered or failed as carrier receipts arrive. Reading that final status needs a StatusCallback URL or a later fetch, which this script does not do - it only confirms Twilio accepted the request.
Why wait for a second check before sending the SMS?
An offer page can come back without parsable offers, which reads the same as a lost Buy Box. Waiting for the same reading on two checks in a row filters a one-off reading at the cost of one interval, the same convention as the Slack alert version of this script.
What happens if Twilio answers 429?
429 means the account's REST API concurrency or rate limit was hit; Twilio's own docs say every 429 is safe to retry. The script backs off and retries up to the attempt cap before giving up for that run; the SellerMagnet state is unaffected either way, so the next run tries again.
Why does a long alert cost more than one segment?
SMS bodies over 160 GSM-7 characters (70 for UCS-2) are split into multiple segments, and Twilio bills every segment. Combining several ASINs' alerts into one message in one run keeps the segment count predictable; the script's own num_segments read-back shows the real count.
How do I find my own seller ID for MY_SELLER_ID?
Use the sellerId of your own offer in the offers[] list of one of your ASINs. That is the exact value buyBox.sellerId carries when you hold the Buy Box.
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 no SMS for that run.
Bottom line: compare buyBox.sellerId with your own seller ID, keep a streak per ASIN, and text yourself through Twilio only when two checks agree - and remember that Twilio's 2xx means queued, not delivered. 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.