To get an Amazon Buy Box lost alert pushed into LINE today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST one JSON push message to the Messaging API's /v2/bot/message/push with your own X-Line-Retry-Key header. The script below sends one message per confirmed change, tells a lost Buy Box apart from a suppressed one, and - because LINE's retry key makes a retried send safe instead of risky - retries exactly once on a 500 or timeout using that same key, so a 409 on the retry reads as the earlier attempt having actually succeeded, not as a new failure.
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 push answers HTTP 200 with JSON sentMessages, a Number id - unlike signal-cli-rest-api's quoted-string timestamp for the same kind of field.
- X-Line-Retry-Key is a UUID YOU generate, kept live 24 hours: retry an ambiguous failure with the same key and a 409 means it already landed, with the original send's id recoverable from the x-line-accepted-request-id header.
- A 429 can mean two different things with opposite fixes: a short throughput limit, or the channel's monthly send quota - only the message text in the body tells them apart.
- 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 LINE.
How do I push a message into LINE from a script?
Create a Messaging API channel in the LINE Developers console (checked 2026-11-25), issue a long-lived channel access token under that channel's Messaging API tab, and add your LINE Official Account as a friend (or invite it into a group) so you have a to target - a userId, groupId or roomId, never a phone number or display handle. Sending itself is one POST to https://api.line.me/v2/bot/message/push with an Authorization: Bearer <token> header, a JSON body of to and a messages array (up to 5 message objects), and - for push, multicast, narrowcast and broadcast only, not reply - an X-Line-Retry-Key header carrying a UUID you mint yourself.
| Response | Reading | LINE 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 LINE?
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_line() pushes 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_line_alert.py - offers check, 2-check confirmation, one retry-keyed push per confirmed change
"""Push an Amazon Buy Box lost alert into a LINE chat via the Messaging API's push message endpoint.
Uses only the real sellermagnet.py / retry.py helpers (see the Python quickstart) for SellerMagnet calls.
The LINE send goes straight through requests.post to https://api.line.me/v2/bot/message/push with a
Bearer channel access token - there is no webhook secret in the URL and no HMAC signature to compute for
an OUTGOING push (signing only applies to LINE's webhook callbacks INTO your server, not this call).
"""
import json
import os
import re
import uuid
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 LINE 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
LINE_CHANNEL_ACCESS_TOKEN = os.environ["LINE_CHANNEL_ACCESS_TOKEN"] # long-lived channel access token
LINE_TO = os.environ["LINE_TO"] # a userId / groupId / roomId, not a phone number or handle
LINE_PUSH_URL = "https://api.line.me/v2/bot/message/push"
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_line(lines: list[str]) -> dict:
"""POST one push message to /v2/bot/message/push, carrying our own X-Line-Retry-Key (a UUID we mint,
not one LINE issues). A 200 answers with a sentMessages array whose id is a NUMBER, unlike Signal's
quoted-string timestamp. A 409 means a request with this exact retry key was already accepted - that is
success, not failure, and the accepted request's id comes back in the x-line-accepted-request-id header.
Only a 500 or a network timeout is retried, once, reusing the SAME key (that is the entire point of the
key: a blind retry without it could double-send, a retry WITH it either resends safely or gets the 409
telling us it already landed). A 4xx other than 409 is never retried; a 429 needs the body's message
read to know whether it is a throughput limit or the monthly send quota - the status code alone does
not say which."""
text = "Amazon Buy Box change, confirmed on 2 checks:\n" + "\n".join(lines[:MAX_LINES])
body = {"to": LINE_TO, "messages": [{"type": "text", "text": text}]}
headers = {"Authorization": f"Bearer {LINE_CHANNEL_ACCESS_TOKEN}",
"Content-Type": "application/json",
"X-Line-Retry-Key": str(uuid.uuid4())}
for attempt in (1, 2):
resp = requests.post(LINE_PUSH_URL, json=body, headers=headers, timeout=30)
try:
resp_body = resp.json()
except ValueError:
resp_body = {}
if resp.status_code == 200:
sent = resp_body.get("sentMessages") or [{}]
return {"accepted": True, "status": 200, "message_id": sent[0].get("id"), "retried": attempt > 1}
if resp.status_code == 409:
return {"accepted": True, "status": 409, "already_accepted": True,
"accepted_request_id": resp.headers.get("x-line-accepted-request-id"), "retried": attempt > 1}
if resp.status_code == 500 and attempt == 1:
continue # only retryable case, same X-Line-Retry-Key header reused
details = resp_body.get("details") or []
return {"accepted": False, "status": resp.status_code, "message": resp_body.get("message", "request failed"),
"details": [f"{d.get('property')}: {d.get('message')}" for d in details], "retried": attempt > 1}
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 LINE message(s) sent, 0 change line(s)")
return
result = post_to_line(lines)
retried_note = " (after 1 retry, same X-Line-Retry-Key)" if result.get("retried") else ""
if result["accepted"] and result["status"] == 200:
print(f"line push ok: sentMessages[0].id={result['message_id']!r} (number){retried_note}")
elif result["accepted"]:
print(f"line push already accepted (409): x-line-accepted-request-id={result['accepted_request_id']!r}"
f"{retried_note}")
else:
extra = f" details={result['details']}" if result.get("details") else ""
print(f"line push FAILED: HTTP {result['status']} {result['message']}{extra}{retried_note}")
print(f"{len(ASINS)} checked, {1 if result['accepted'] else 0} LINE 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 LINE message(s) sent, 0 change line(s)
--- run 2 (all three confirmed, baseline seeded silently, no backstory alert)
3 checked, 0 LINE message(s) sent, 0 change line(s)
--- run 3: B0EXAMPLE2 loses the Buy Box (1st sighting, not confirmed yet)
3 checked, 0 LINE message(s) sent, 0 change line(s)
--- run 4: same reading confirmed, a real CHANGE from the seeded baseline, LINE push sent
line push ok: sentMessages[0].id=14353798921116 (number)
3 checked, 1 LINE message(s) sent, 1 change line(s)
--- run 5: B0EXAMPLE2 is back (1st sighting, not confirmed yet)
3 checked, 0 LINE message(s) sent, 0 change line(s)
--- run 6: recovery confirmed; first attempt reads 500, retry with the SAME X-Line-Retry-Key reveals it had already gone through
line push already accepted (409): x-line-accepted-request-id='a1b2c3-request-99' (after 1 retry, same X-Line-Retry-Key)
3 checked, 1 LINE message(s) sent, 1 change line(s)
--- run 7: B0EXAMPLE2 loses it again (1st sighting, not confirmed yet)
3 checked, 0 LINE message(s) sent, 0 change line(s)
--- run 8: confirmed again, but this LINE channel hit its monthly send quota
line push FAILED: HTTP 429 You have reached your monthly limit.
3 checked, 0 LINE message(s) sent, 1 change line(s)
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST "https://api.line.me/v2/bot/message/push" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${LINE_CHANNEL_ACCESS_TOKEN}" \
-H "X-Line-Retry-Key: 123e4567-e89b-12d3-a456-426614174000" \
-d '{"to": "U4af4980629...", "messages": [{"type": "text", "text": "Amazon Buy Box change, confirmed on 2 checks:\n- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, yours 19.99"}]}'
# HTTP/1.1 200 OK
# Content-Type: application/json
# {"sentMessages": [{"id": 14353798921116, "quoteToken": "wDDV..."}]}

How do I get a LINE channel access token and target id?
- Create a Messaging API channelIn the LINE Developers console, create a provider and a Messaging API channel under it; this gives the LINE Official Account the script will push as.
- Issue a channel access tokenUnder that channel's Messaging API tab, issue a long-lived channel access token (or mint short-lived v2.1 tokens from your channel ID and secret if you prefer rotation).
- Add the bot and get a target idScan the channel's QR code with the LINE app to add it as a friend, or invite it into a group/room; the
userId(orgroupId/roomId) needed fortoshows up in your webhook'ssourceobject the first time that user messages the bot, or via LINE Official Account Manager > Settings. - Note the target idStore that id (e.g.
U4af4980629...) asLINE_TO; it is not a phone number, email or @handle. - Send a test push
curl -X POST -H 'Content-Type: application/json' -H 'Authorization: Bearer <token>' -H 'X-Line-Retry-Key: <uuid>' -d '{"to": "<target-id>", "messages": [{"type": "text", "text": "test"}]}' 'https://api.line.me/v2/bot/message/push'- a 200 with asentMessagesarray 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 has this token can push as your LINE Official Account)
export SELLERMAGNET_API_KEY="your-key-here"
export MY_SELLER_ID="A1MYSELLER0001" # your sellerId as it appears in offers[]
export LINE_CHANNEL_ACCESS_TOKEN="your-long-lived-channel-access-token"
export LINE_TO="U4af4980629..." # a userId, groupId or roomId - not a phone number or handle
# 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_line_alert.py >> alert.log 2>&1
The LINE Messaging API reference (developers.line.biz, checked 2026-11-25) describes the contract the script relies on: a successful POST /v2/bot/message/push answers HTTP 200 with a JSON body whose sentMessages[].id is a Number (not a string, unlike some other self-hosted bridges). A 409 on a request that carries an X-Line-Retry-Key already seen in the last 24 hours means the request is not re-processed - it answers with the originally accepted sentMessages and an x-line-accepted-request-id header, so a client-side retry after an ambiguous failure cannot cause a duplicate delivery the way an idempotency-free endpoint can. A 429 is documented with two separate causes that share the same status code: the per-endpoint throughput limit ("The API rate limit has been exceeded. Try again later.") and the monthly send quota ("You have reached your monthly limit.") - the fixes are opposite, so the script reports the message text rather than guessing.
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; pushing into LINE costs nothing extra on top. 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 is the id in a successful push response a plain number, not a quoted string?
LINE's reference types sentMessages.id as a Number and the live response matches it - unlike signal-cli-rest-api, which quotes its send timestamp as a string even though the Swagger doc types it as an integer. A script that blindly str()-converts every vendor id works either way; one that assumes a quoted string from LINE would just see a slightly odd but harmless comparison, since Python treats int and str equality as always false rather than raising.
What does the X-Line-Retry-Key header actually protect against?
It lets a client retry an AMBIGUOUS failure (a timeout, a dropped connection, a 500) without risking a duplicate send: resending the same request with the same key either succeeds once or, if LINE already accepted it, answers 409 with the original sentMessages and an x-line-accepted-request-id header instead of sending again. Push, multicast, narrowcast and broadcast accept it; the reply endpoint does not, because its single-use reply token already makes a duplicate reply impossible. The key must be a UUID you generate yourself - LINE never issues one - and it is only honoured for 24 hours; reusing it after that is treated as a brand-new request, i.e. a real duplicate.
Does the script sign the push request the way LINE webhook receivers have to?
No, and conflating the two is a common mistake. The x-line-signature HMAC-SHA256 check is something your server verifies on INCOMING webhook callbacks from LINE, using the channel secret. An OUTGOING push is authenticated the opposite way: a Bearer channel access token in the Authorization header, no signature involved at all.
Why does a 429 need the message body read instead of just a retry loop?
LINE returns the same 429 status for two different problems with opposite fixes: "The API rate limit has been exceeded. Try again later." is a short-lived throughput limit (2,000 requests per second for push, enforced with a token bucket that refills gradually), while "You have reached your monthly limit." means the channel used up its plan's free messages or configured paid cap for the month and will not recover by waiting. The script treats every 429 as non-retryable and reports the message text so the two are told apart by a human instead of being retried into the same wall.
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 LINE 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 push one LINE message per confirmed CHANGE from the seeded baseline - remembering that a successful send's id is a plain JSON number, that X-Line-Retry-Key makes retrying a dropped response safe instead of risky, and that a 429 needs its message text read before you know whether to back off or upgrade. 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.