To get an Amazon Buy Box lost alert sent through Threema today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST a form-encoded body to Threema Gateway's send_simple endpoint: https://msgapi.threema.ch/send_simple with from, to, text and secret as plain form fields. The catch: a successful send answers HTTP 200 with the new message's id as bare text/plain, not a JSON object - the only channel in this series with nothing to parse on success at all. The script below tells a lost Buy Box apart from a suppressed one, confirms a change on a second check, and costs one SellerMagnet credit per ASIN per check.
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 page you.
- A successful send_simple call answers HTTP 200 with the message id as bare text, not JSON - the opposite of WeCom's errcode field or Chatwork's {"message_id": ...} body.
- Every documented failure gets its own HTTP status (400/401/402/404/413/429/500), unlike a channel that wraps success and failure in the same 200.
- Auth is
from/secretform fields, not a header and not part of the URL, so a logged request URL alone cannot be replayed to send a message. - 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.
Why does a successful Threema send return plain text, not JSON?
Threema Gateway's own API reference (gateway.threema.ch/en/developer/api, checked 2026-11-29) documents send_simple's success response as HTTP 200 with the new message's id in the body as text/plain - a short hex string like 061e0c7bb2154b2a, nothing else. Every other channel in this series on a successful send answers with either an empty body (GroupMe), a JSON field (Chatwork's message_id, WeCom's errcode) or a status code alone (Bark); Threema is the only one where the whole response is a bare, unstructured id. A script that tries resp.json() the way the WeCom or Chatwork scripts in this series do would crash on every single successful Threema send.
| Response | Reading | Threema message |
|---|---|---|
| buyBox.sellerId is your sellerId | mine | BACK, after a confirmed return |
| 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 Threema?
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_threema() sends every queued line as one form-encoded send_simple call and reads the HTTP status plus the raw body to decide what happened. 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. Only HTTP 429 (rate limited) is retried, once, after a fixed backoff, because it is the one status Threema's docs describe as transient; 400, 401, 402, 404 and 413 all stop without retry, since nothing about resending the identical payload fixes a bad recipient, a dead secret, an empty credit balance, an unresolved phone/email or a message that is already too long; and the body is capped at the 3,500-byte limit the docs state for text, measured in UTF-8 bytes.
buybox_threema_alert.py - offers check, 2-check confirmation, one status-checked POST 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 Threema 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
THREEMA_API = "https://msgapi.threema.ch/send_simple"
THREEMA_FROM = os.environ["THREEMA_FROM"] # your 8-char Gateway API identity (starts with '*')
THREEMA_SECRET = os.environ["THREEMA_SECRET"] # Gateway API secret, sent in the form body, never a header
THREEMA_TO = os.environ["THREEMA_TO"] # recipient Threema ID (8 chars), the only recipient form this
# script uses; gateway.threema.ch also accepts phone/email
MAX_BODY_BYTES = 3500 # gateway.threema.ch: text caps at 3,500 bytes UTF-8
MAX_LINES = 60 # keeps the batch comfortably under the 3,500-byte limit
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:
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"held by {box.get('sellerName', 'unknown')} ({holder}, {box.get('fulfillmentType', '?')}) at {box.get('totalPrice')} {currency}"
return "lost", detail
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(session, state: dict) -> list[str]:
"""Advance the streak for every ASIN, return the lines to push this run (confirmed changes only)."""
lines = []
for asin in ASINS:
if not ASIN_RE.match(asin):
continue
reading, detail = read_buy_box(session, asin)
entry = state.get(asin)
if entry is None:
state[asin] = {"reading": reading, "streak": CONFIRM, "reported": reading} # seed, no false alert
continue
if entry["reading"] == reading:
entry["streak"] = min(entry["streak"] + 1, CONFIRM)
else:
entry["reading"], entry["streak"] = reading, 1
if entry["streak"] >= CONFIRM and entry["reported"] != reading:
entry["reported"] = reading
if reading == "lost":
lines.append(f"{asin}: LOST, {detail}")
elif reading == "mine":
lines.append(f"{asin}: BACK, you hold the Buy Box again")
return lines
def post_to_threema(lines: list[str]) -> bool:
"""One POST per run to send_simple. gateway.threema.ch's own docs (checked 2026-11-29) are the opposite
of Chatwork's form body: Threema also takes application/x-www-form-urlencoded, but a successful send
answers HTTP 200 with the new message's id as bare text/plain, not a JSON object - there is no field to
parse at all, just a status line and a body string. Every documented failure is a distinct HTTP status,
never a 200 with an error payload."""
if not lines:
return False
if len(lines) > MAX_LINES:
lines = lines[:MAX_LINES] + [f"...and {len(lines) - MAX_LINES} more"]
text = "Amazon Buy Box change, confirmed on 2 checks:\n" + "\n".join(lines)
while len(text.encode("utf-8")) > MAX_BODY_BYTES:
lines = lines[:-1]
if not lines:
text = text.encode("utf-8")[:MAX_BODY_BYTES - 20].decode("utf-8", "ignore") + "\n...(truncated)"
break
text = "Amazon Buy Box change, confirmed on 2 checks:\n" + "\n".join(lines) + "\n...(truncated)"
payload = {"from": THREEMA_FROM, "to": THREEMA_TO, "text": text, "secret": THREEMA_SECRET}
resp = requests.post(THREEMA_API, data=payload, timeout=30)
if resp.status_code == 200:
# The body is the raw message id, e.g. "061e0c7bb2154b2a" - nothing to parse, just confirm it is
# non-empty before trusting it, since an empty 200 body has never been observed as documented.
msg_id = resp.text.strip()
print(f"[threema] {text} (message id {msg_id or '?'})")
return bool(msg_id)
if resp.status_code == 429:
# gateway.threema.ch: rate-limiting triggered. One fixed backoff-and-retry, same pattern as the
# one documented transient status in the rest of this series.
time.sleep(5)
resp = requests.post(THREEMA_API, data=payload, timeout=30)
if resp.status_code == 200:
msg_id = resp.text.strip()
print(f"[threema] {text} (message id {msg_id or '?'})")
return bool(msg_id)
print(f"[threema] still HTTP {resp.status_code} after 1 retry, left unreported")
return False
if resp.status_code == 402:
# no Gateway credits remain - a billing problem, not a transient fault; retrying changes nothing.
print("[threema] STOP HTTP 402 (no Gateway credits remain), left unreported")
return False
if resp.status_code in (400, 401, 404, 413):
# a bad recipient/mode (400), wrong identity or secret (401), unresolved phone/email (404), or an
# oversized body (413): every one is a setup problem that resending the same payload cannot fix.
print(f"[threema] STOP HTTP {resp.status_code}, left unreported")
return False
print(f"[threema] HTTP {resp.status_code}, left unreported")
return False
def main() -> None:
session = new_session()
state = _load_state()
lines = check(session, state)
sent = post_to_threema(lines)
_save_state(state)
print(f"{len(ASINS)} checked, {1 if sent else 0} alert(s) sent")
if __name__ == "__main__":
main()
Five runs of the script (illustrative ASIN and seller; [threema] = 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
[threema] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD (message id 061e0c7bb2154b2a)
1 checked, 1 alert(s) sent
--- run 4, back to mine (1st sighting, not yet confirmed)
1 checked, 0 alert(s) sent
--- run 5, back to mine, confirmed
[threema] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: BACK, you hold the Buy Box again (message id 061e0c7bb2154b2a)
1 checked, 1 alert(s) sent
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST https://msgapi.threema.ch/send_simple \\
-d "from=*SMALERT1" -d "to=ABCD1234" -d "secret=test-secret-0001" \\
--data-urlencode "text=Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"
# HTTP/1.1 200 OK
# 061e0c7bb2154b2a

How do I get a Threema Gateway identity, secret and recipient?
- Register a Gateway accountSign up at gateway.threema.ch and choose basic mode (no end-to-end key management needed for
send_simple); Threema issues an 8-character API identity (from, usually starting with*) and a secret. - Top up Gateway creditsEach
send_simplecall costs 1 credit; a 402 response means the balance is empty and the call was not sent. - Get the recipient's Threema IDAsk the recipient for their 8-character Threema ID directly, or send to their phone number (
phone) or email (email) and let Threema Gateway resolve it; an unresolved phone or email answers 404. - Send a test message
curl -d \\"from=<id>\\" -d \\"secret=<secret>\\" -d \\"to=<threema id>\\" --data-urlencode \\"text=hello\\" https://msgapi.threema.ch/send_simple; a successful call answersHTTP/1.1 200 OKwith the new message's id as the entire body.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the secret alone authenticates every send from this identity)
export SELLERMAGNET_API_KEY="your-key-here"
export THREEMA_FROM="*SMALERT1" # your 8-char Gateway API identity
export THREEMA_SECRET="your-gateway-secret-here"
export THREEMA_TO="ABCD1234" # the recipient's 8-char Threema ID
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_threema_alert.py >> alert.log 2>&1
Threema Gateway's own developer documentation (gateway.threema.ch/en/developer/api, checked 2026-11-29) describes the contract the script relies on: send_simple needs from, to (or phone/email), text (max 3,500 bytes UTF-8) and secret as form fields, a successful call answers HTTP 200 with the new message's id as plain text, and every documented failure carries its own distinct status (400 invalid recipient or not basic mode, 401 wrong identity/secret, 402 no credits, 404 unresolved phone/email, 413 oversized message, 429 rate limited, 500 temporary error). There is no retry-after header and no idempotency key on this endpoint, so 429 gets exactly one retry after a fixed backoff and every other failure is left alone, since nothing about resending the identical payload can fix a dead secret or an empty credit balance.
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 Threema Gateway send costs its own separate Gateway credit, unrelated to SellerMagnet's. With a 2-check confirmation the worst-case delay before Threema 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 |

| HTTP status | Meaning | What it means for the alert |
|---|---|---|
| 200 | OK | Sent (body is the new message id, plain text) |
| 400 | Bad Request | Invalid recipient or not basic mode, never retried |
| 401 | Unauthorized | Wrong API identity or secret, never retried |
| 402 | Payment Required | No Gateway credits remain, never retried |
| 404 | Not Found | Phone/email recipient could not be resolved, never retried |
| 413 | Payload Too Large | Message over 3,500 bytes, never retried |
| 429 | Too Many Requests | Rate limited, the one status retried once |
| 500 | Server Error | Temporary Threema outage, left for the next run |
Frequently Asked Questions
Does a successful Threema Gateway send return JSON, like most of this series?
No. gateway.threema.ch's own API reference (checked 2026-11-29) documents the send_simple endpoint's success response as HTTP 200 with the new message's id returned as plain text/plain, not wrapped in any JSON object. There is no field to read: the script keeps the raw body, checks it is non-empty, and prints it as the delivered message's id. Calling .json() on that response raises a decode error, since there was never any JSON to parse.
Where does the API secret travel, compared to a webhook URL or a header token?
In the POST form body, alongside from, to and text, never in a header and never in the URL. The Gateway API identity (from, 8 characters, usually starting with *) and its secret are issued together when you register a Gateway account at gateway.threema.ch; unlike a WeCom or GroupMe webhook URL, there is nothing secret in the request URL itself, so a logged or cached URL alone cannot be replayed to send a message.
Why does HTTP status alone decide success here, unlike WeCom's errcode field?
Because Threema's docs define one HTTP status per outcome, with no shared 200-for-everything wrapper: 400 for an invalid recipient, 401 for a wrong identity or secret, 402 for no credits, 404 for an unresolved phone or email, 413 for an oversized message, 429 for the rate limit and 500 for a temporary fault, next to the single 200 for a real send. A script that reads an errcode field the way the WeCom or Telegram scripts in this series do would find nothing to read on a Threema failure, since the body on an error response carries no guaranteed structure at all.
Can send_simple message a Threema ID directly, or only a phone number or email?
All three are accepted as the recipient, as long as the account is enabled for basic mode: to for a direct 8-character Threema ID (what this script uses), or phone/email for gateway.threema.ch to resolve from its own directory, which is the one case that can answer 404 if no matching Threema user is found for that phone or email.
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 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, posts 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 Threema send_simple call per run - the only thing to check is the HTTP status and whether the body carries a non-empty message id, since there is no JSON at all to parse. 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.