To get an Amazon Buy Box lost alert in Google Chat today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and post to a Chat incoming webhook only when the same reading shows up on two checks in a row. The script below sends one message per confirmed change, threads every alert for one ASIN together, tells a lost Buy Box apart from a suppressed one, and costs one 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 your team.
- A Chat incoming webhook answers 200 on success but only echoes the message's name and thread.name, never the text back; threadKey groups every alert for one ASIN into one thread instead of a fresh message each time.
- Google Chat allows 1 message-create request per second per space, shared by every webhook registered in that space, and rejects anything over 32,000 bytes (text and cards combined).
- Each check costs 1 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 my alert need two secrets in one URL?
Because a Google Chat webhook URL carries both of its credentials as query parameters: key, a value shared by every webhook registered through the same Chat admin flow, and token, unique to this one webhook and the part that must stay secret (Google's own Chat webhook quickstart, checked 2026-11-14). The full URL looks like https://chat.googleapis.com/v1/spaces/SPACE_ID/messages?key=KEY&token=TOKEN; SPACE_ID identifies the space, not a credential by itself. Unlike Slack's single secret path or Teams' single sig parameter, losing either key or token here means recreating the webhook, and the whole URL belongs in an environment variable that never reaches version control.
| Response | Reading | Chat 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 Google Chat?
read_buy_box() turns one offers response into a reading, check() keeps a streak per ASIN in buybox_state.json and queues a fact once a new reading has been seen CONFIRM times in a row, and post_to_chat() sends each confirmed fact as its own message, threaded on that ASIN. get_with_retry comes from retry.py and ApiError and 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 message over the 32,000 byte limit is trimmed before it is sent rather than rejected outright.
buybox_gchat_alert.py - offers check, 2-check confirmation, one threaded Chat message per ASIN
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 Chat 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_BYTES = 32000 # Chat rejects a message over this, text + cards combined
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 message(asin: str, key: str, detail: str) -> str:
if key == "mine":
return f"BACK {asin}: you hold the Buy Box again"
if key == "suppressed":
return f"NONE {asin}: offers exist but Amazon features none (Buy Box suppressed)"
if key == "no-offers":
return f"EMPTY {asin}: no offers on the listing"
return f"LOST {asin}: Buy Box held by {detail}"
def post_to_chat(webhook_url: str, asin: str, text: str) -> bool:
"""One message per confirmed alert, threaded per ASIN. A webhook response only ever carries
name/thread.name on success, so the status code decides, not the body (unlike Slack's literal 'ok')."""
url = webhook_url + "&threadKey=" + asin + "&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD"
body = {"text": text, "thread": {"threadKey": asin}}
if len(json.dumps(body).encode("utf-8")) > MAX_BYTES:
text = text[:MAX_BYTES - 200] + " ...(truncated)"
body = {"text": text, "thread": {"threadKey": asin}}
try:
resp = requests.post(url, json=body, headers={"Content-Type": "application/json; charset=UTF-8"},
timeout=10)
except requests.RequestException as err:
print(f"chat unreachable: {type(err).__name__}") # never print the URL: key+token are secrets
return False
if resp.status_code == 200:
return True
print(f"chat refused the message: {resp.status_code} {resp.text[:80]}")
return False # 429 = the space's 1-write/sec quota, shared by every webhook in it
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], webhook_url: str) -> None:
session, state = new_session(), load_state()
alerts, problems, checked = [], [], 0
stopped = ""
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.setdefault(asin, {"last": "mine", "streak": 0, "reported": "mine"})
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, message(asin, key, detail)))
sent_count = 0
for asin, key, text in alerts:
if post_to_chat(webhook_url, asin, text):
state[asin]["reported"] = key # only after Chat answered 200, else re-sent next run
sent_count += 1
if stopped and state.get("_stopped") != stopped:
if post_to_chat(webhook_url, "stop", f"STOP checks stopped: {stopped}"):
state["_stopped"] = stopped
if not stopped:
state.pop("_stopped", None)
save_state(state)
for line in problems:
print(line)
not_sent = len(alerts) - sent_count
tail = "" if not_sent == 0 else f", {not_sent} NOT sent (retried next run)"
print(f"{checked} checked, {sent_count} alert(s) sent{tail}")
if __name__ == "__main__":
check(ASINS, os.environ["GOOGLE_CHAT_WEBHOOK_URL"])
Five runs of the script (illustrative ASINs and sellers; [google chat] = the message Chat received)
--- run 1 (illustrative ASINs and sellers)
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
[google chat] LOST B0EXAMPLE2: Buy Box held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer: not on the first offer page (thread: B0EXAMPLE2)
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
[google chat] BACK B0EXAMPLE2: you hold the Buy Box again (thread: B0EXAMPLE2)
1 checked, 1 alert(s) sent
The JSON body the webhook accepts, and the only fields Chat echoes back on success
{
"request": {
"text": "LOST B0EXAMPLE2: Buy Box held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD",
"thread": {"threadKey": "B0EXAMPLE2"}
},
"response_200": {
"name": "spaces/AAAAAAAAAAA/messages/XXXXXXXXXXX.XXXXXXXXXXX",
"thread": {"name": "spaces/AAAAAAAAAAA/threads/XXXXXXXXXXX"}
}
}

How do I create the Google Chat incoming webhook?
- Open the target spaceIn Chat on the web (not the mobile app, which cannot configure webhooks), open the space that should receive the alerts.
- Open Apps & integrationsClick the arrow next to the space title, then Apps & integrations, then Add webhooks.
- Name it and saveGive the webhook a name, optionally an avatar URL, and click Save.
- Copy the webhook URLClick More, then Copy link. The URL contains both the key and token query parameters needed to post; store the whole URL as one secret.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the key and token query parameters are both secrets)
export SELLERMAGNET_API_KEY="your-key-here"
export GOOGLE_CHAT_WEBHOOK_URL="https://chat.googleapis.com/v1/spaces/AAAAAAAAAAA/messages?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&token=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
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_gchat_alert.py >> alert.log 2>&1
Google's own Chat webhook documentation (developers.google.com/workspace/chat, checked 2026-11-14) describes the contract the script relies on: you POST a JSON body with a text field (or cardsV2) to the webhook URL with Content-Type: application/json; charset=UTF-8, and a successful post answers HTTP 200 with a Message body - but for a webhook request that body only ever populates name and thread.name, never the message content back, unlike Slack's plain-text ok. A payload with none of text, cards or cardsV2 is rejected with 400. Chat's own usage-limits page documents the per-space quota the script has to respect: 1 spaces.messages.create request per second, shared by every webhook registered in that space, not a private allowance per webhook; going over it answers 429. The maximum message size is 32,000 bytes, text and cards combined. Incoming webhooks are a Business or Enterprise Google Workspace feature with the admin setting that lets users add and use them turned on; they are not available on a personal Gmail account.
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 cost is the number of ASINs times the number of checks. With a 2-check confirmation the worst-case delay before Google Chat hears about a loss is about two intervals. Errors add to the 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 the alert URL need a threadKey and messageReplyOption?
So every alert for one ASIN lands in the same Chat thread instead of a new top-level message each time. threadKey is an arbitrary string in the message body; messageReplyOption on the webhook URL tells Chat to reply if that thread exists or start one if it does not (REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD). Without it, every run's alert is its own thread.
What does a successful Google Chat webhook call look like?
HTTP 200 with a JSON body, but for a webhook request Chat only ever populates the message's name and thread.name fields in that body, never the full message content back. That is different from Slack's plain-text 'ok' and Teams' 202 with no body at all, so the script checks the status code, not the body.
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 Chat returns 429?
429 means the space's own rate limit was hit: Google Chat allows only 1 message-create request per second per space, shared across every webhook registered in that space, not just this one. The alert is not marked as sent, so the next run posts the same fact again as long as the reading still holds.
Can two different alert scripts post to the same Chat space?
Yes, but they share that one request-per-second budget. If several webhooks in the same space all fire around the same time, some will get a 429 and should back off and retry, exactly like this script already does by leaving the alert unmarked.
What happens when my 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 post to Google Chat only when two checks agree, threaded one ASIN per thread. 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.