To get an Amazon Buy Box lost alert posted into Chatwork 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 Chatwork's Add Message endpoint with your API token in the X-ChatWorkToken header. The script below sends one message per run, tells a lost Buy Box apart from a suppressed one, sends the body the way Chatwork actually expects it (not JSON), 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.
- Chatwork's Add Message endpoint takes application/x-www-form-urlencoded, not JSON - the one webhook in this series that 400s on requests.post(url, json=...).
- A successful POST answers HTTP 200 with {"message_id": "789"}, never a boolean success flag; auth is a plain X-ChatWorkToken header, never a secret baked into the URL.
- Two different 429s exist: an account-wide 300-per-5-minute limit (x-ratelimit-remaining) and a stricter 10-per-10-seconds PER ROOM posting limit with its own error body.
- 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.
How is Chatwork's message API different from the rest of this series?
Generate a personal API token from Chatwork > Settings > API Token (developer.chatwork.com, checked 2026-11-29), then send it as the X-ChatWorkToken header on every call - there is no webhook URL to copy anywhere, unlike every other channel covered so far. Find your room id from the room's URL or the /rooms list endpoint, then POST to /rooms/{room_id}/messages with the message in a single body field. The catch: Chatwork expects that field as application/x-www-form-urlencoded, not a JSON object - sending requests.post(url, json={...}) gets a 400, because Chatwork never looks at the JSON content type at all for this endpoint.
| Response | Reading | Chatwork 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 Chatwork?
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_chatwork() sends every queued line as one form-encoded POST. 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. The two 429 bodies need to be told apart before deciding what to do: errors mentioning message posting means only this room's posting rate is too high (short, local problem), while x-ratelimit-remaining hitting "0" means the whole account's 5-minute budget is spent (stop calling anything for a while) - conflating the two would either back off far more than needed or not enough. A long batch is capped at MAX_LINES and the rendered body truncated to stay under a conservative character budget before it is sent, since Chatwork's own docs do not publish a hard limit for an [info] block the way some channels publish a message-size cap.
buybox_chatwork_alert.py - offers check, 2-check confirmation, one form-encoded POST per run
import json
import os
import re
import urllib.parse
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 Chatwork 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_BODY_CHARS = 2000 # conservative cap; Chatwork does not publish one for [info] blocks
MAX_LINES = 20
# Auth is a plain header, not a secret baked into the URL like every other channel in this series.
CHATWORK_API_TOKEN = os.environ["CHATWORK_API_TOKEN"]
CHATWORK_ROOM_ID = os.environ["CHATWORK_ROOM_ID"]
CHATWORK_URL = f"https://api.chatwork.com/v2/rooms/{CHATWORK_ROOM_ID}/messages"
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"{box.get('sellerName', '?')} ({holder}, {box.get('fulfillmentType', '?')})"
if isinstance(box.get("totalPrice"), (int, float)):
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))]
if mine:
detail += f", your offer {min(mine):.2f}"
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]:
lines = []
for asin in ASINS:
if not ASIN_RE.match(asin):
continue
try:
reading, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
if not state.get("stopped"):
lines.append("STOP: SellerMagnet returned " + str(err.status) + ", pausing checks until it clears")
state["stopped"] = True
return lines
continue
state["stopped"] = False
entry = state.get(asin, {"reading": None, "streak": 0})
if reading == entry["reading"]:
entry["streak"] += 1
else:
entry = {"reading": reading, "streak": 1, "alerted_lost": entry.get("alerted_lost", False)}
state[asin] = entry
if entry["streak"] == CONFIRM:
if reading == "mine" and entry.get("alerted_lost"):
lines.append(f"- {asin}: BACK, you hold the Buy Box again")
entry["alerted_lost"] = False
elif reading == "lost":
lines.append(f"- {asin}: LOST, held by {detail}")
entry["alerted_lost"] = True
state[asin] = entry
return lines
def post_to_chatwork(lines: list[str]) -> None:
if not lines:
return
shown = lines[:MAX_LINES]
body = "[info][title]Amazon Buy Box change, confirmed on 2 checks[/title]" + "\n".join(shown) + "[/info]"
if len(lines) > MAX_LINES:
body = body[:-len("[/info]")] + f"\n...and {len(lines) - MAX_LINES} more[/info]"
if len(body) > MAX_BODY_CHARS:
body = body[:MAX_BODY_CHARS - 20] + "\n...(truncated)[/info]"
# Chatwork's Add Message endpoint takes application/x-www-form-urlencoded, never JSON - every
# other channel in this series accepts a JSON payload, so this is the one webhook that 400s on
# requests.post(url, json=...) and needs data=urllib.parse.urlencode({"body": body}) instead.
resp = requests.post(
CHATWORK_URL,
headers={"X-ChatWorkToken": CHATWORK_API_TOKEN,
"Content-Type": "application/x-www-form-urlencoded"},
data=urllib.parse.urlencode({"body": body}),
timeout=10,
)
try:
parsed = resp.json()
except ValueError:
parsed = {}
if resp.status_code == 200 and "message_id" in parsed:
print(f"[chatwork] message_id={parsed['message_id']} {body}")
return
if resp.status_code == 429:
# Two separate limiters share this one status code: the account-wide 300-requests-per-5-min
# gate (x-ratelimit-remaining counts it down, no special body) and a stricter 10-posts-per-
# 10-seconds-per-room gate that Chatwork's own docs give a distinct body for. Telling them
# apart matters: hitting the account limit means stop sending anything for a while, hitting
# the per-room post limit means only THIS room's post needs to slow down.
errors = parsed.get("errors") or []
remaining = resp.headers.get("x-ratelimit-remaining")
if any("posting" in e.lower() for e in errors):
print(f"[chatwork] POST failed: 429 per-room message rate limit ({errors})")
elif remaining == "0":
print(f"[chatwork] POST failed: 429 account rate limit (resets {resp.headers.get('x-ratelimit-reset')})")
else:
print(f"[chatwork] POST failed: 429 {parsed}")
return
print(f"[chatwork] POST failed: {resp.status_code} {parsed}")
def main() -> None:
session = new_session()
state = _load_state()
lines = check(session, state)
post_to_chatwork(lines)
_save_state(state)
print(f"{len(ASINS)} checked, {1 if lines else 0} alert(s) sent")
if __name__ == "__main__":
main()
Five runs of the script (illustrative ASINs and sellers; [chatwork] = the message sent)
--- run 1 (illustrative ASINs and sellers)
3 checked, 0 alert(s) sent
--- run 2, B0EXAMPLE2 lost (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 3, same reading confirmed
[chatwork] message_id=789 [info][title]Amazon Buy Box change, confirmed on 2 checks[/title]- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99[/info]
3 checked, 1 alert(s) sent
--- run 4, back to mine (1st sighting, not yet confirmed)
3 checked, 0 alert(s) sent
--- run 5, back to mine, confirmed
[chatwork] message_id=789 [info][title]Amazon Buy Box change, confirmed on 2 checks[/title]- B0EXAMPLE2: BACK, you hold the Buy Box again[/info]
3 checked, 1 alert(s) sent
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST https://api.chatwork.com/v2/rooms/123456/messages \
-H "X-ChatWorkToken: your-api-token" \
-H "Content-Type: application/x-www-form-urlencoded" \
--data-urlencode 'body=[info][title]Amazon Buy Box change, confirmed on 2 checks[/title]- B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99[/info]'
# HTTP/1.1 200 OK
# Content-Type: application/json; charset=utf-8
# x-ratelimit-limit: 300
# x-ratelimit-remaining: 244
# {"message_id":"789"}

How do I set up the Chatwork Add Message API?
- Generate a personal API tokenGo to Chatwork > Settings (gear icon) > API Token and generate a token for your account; it inherits your own room access.
- Find the room idOpen the room in a browser and read the numeric id from the URL, or call
GET /roomswith the token to list every room id you belong to. - Treat the token as a secretThe token travels only in the
X-ChatWorkTokenheader, never the URL; Chatwork's docs are explicit it must not be put in a query string. - Send a test message
curl -X POST -H 'X-ChatWorkToken: your-token' --data-urlencode 'body=test' https://api.chatwork.com/v2/rooms/<room_id>/messages; a 200 response with{"message_id": ...}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: the token alone lets anyone post into this room as you)
export SELLERMAGNET_API_KEY="your-key-here"
export CHATWORK_API_TOKEN="your-chatwork-api-token"
export CHATWORK_ROOM_ID="123456"
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_chatwork_alert.py >> alert.log 2>&1
Chatwork's own API documentation (developer.chatwork.com, ChatWork_API_Documentation.pdf, checked 2026-11-29) describes the contract the script relies on: the Add Message endpoint takes a form-encoded body field and answers HTTP 200 with {"message_id": "789"} on success - never the JSON object body or boolean success flag most other channels in this series use, and never plain text the way Mattermost's ok body is. A bad token answers 401 with {"errors": ["Request was rejected because of invalid AuthToken."]}, and the two separate 429s (account-wide vs. per-room posting) are told apart by their body text, not just the status code.
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; Chatwork itself charges nothing extra for the Add Message API on a paid or free workspace you already use. With a 2-check confirmation the worst-case delay before the room 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
Does a Chatwork webhook post JSON like most of this series, or something else?
Neither JSON nor plain text. Chatwork's own API documentation (developer.chatwork.com, ChatWork_API_Documentation.pdf, checked 2026-11-29) has the Add Message endpoint (POST /rooms/{room_id}/messages) accept application/x-www-form-urlencoded with a single body form field, not a JSON body the way Slack, Discord, Mattermost, Rocket.Chat and every other channel in this series do. Send it with requests.post(url, json=...) and Chatwork answers a 400, because it never parses the JSON at all.
What does a successful post actually return?
HTTP 200 with a JSON body that carries exactly one field: {"message_id": "789"} (an opaque numeric-looking string, not a boolean success flag like Rocket.Chat or Google Chat). The script treats a 200 response with a message_id key as success and logs that id; a 200 without it is not treated as delivered.
Why does the script tell two different 429s apart?
Chatwork runs two separate limiters that both answer 429. The account-wide gate is 300 requests per 5 minutes, tracked by the x-ratelimit-remaining and x-ratelimit-reset response headers (developer.chatwork.com, checked 2026-11-29); hitting zero there means stop calling the API entirely until the reset time. Posting messages (and creating tasks) is capped separately at 10 calls per 10 seconds PER ROOM, and that 429's JSON body carries its own {"errors": ["Rate limit for message posting per room exceeded."]} line - a wholly different problem (only this room's posting needs to slow down, not the whole integration). The script reads the body text before deciding which backoff applies.
How is Chatwork authenticated, compared to the rest of this series?
A plain HTTP header, X-ChatWorkToken, carrying your personal API token, sent with a room id in the URL PATH (/rooms/{room_id}/messages) - closer to how the SellerMagnet API itself authenticates than to any webhook URL in this series. There is no opaque webhook URL to leak: the token alone is the credential, and Chatwork's docs are explicit that it must travel in the header, never the query string.
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 post one Chatwork message per run - remembering that the body must be form-encoded, not JSON, auth is a plain header, and the two 429s mean different things. 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.