To get an Amazon Buy Box lost alert pushed to WeCom (Enterprise WeChat) today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST one markdown message per run to your WeCom group robot's webhook. The one thing every other channel in this series gets you ready for and WeCom breaks the same way DingTalk and Lark do: the HTTP response is always 200, success or failure, so the script never looks at resp.status_code alone for the outgoing call - it reads the errcode field inside the JSON body. WeCom adds its own trap on top: the markdown body is capped at 4096 bytes of UTF-8, not characters, so the script trims on the encoded length. The script below tells a lost Buy Box apart from a suppressed one, retries the one errcode WeCom actually wants retried, and costs one SellerMagnet credit per ASIN per check.
Key Takeaways
- A WeCom group-robot send answers HTTP 200 on every outcome - the real result is the JSON body's errcode (0 = sent), never the HTTP status alone, the same shape as DingTalk's errcode and Lark's code earlier in this series.
- errcode 45009 is the one result in this series that means 'retry' for WeCom: the documented per-robot rate limit of 20 messages a minute. The script waits 5s and resends once.
- errcode 93000 means the webhook key is invalid or the robot was removed from the group - a setup problem, never retried.
- The markdown content cap is 4096 BYTES of UTF-8, not characters; a character-count cap would let CJK text (3 bytes per character) through that WeCom still rejects. The script encodes first, then trims.
- buyBox is the featured offer: its sellerId is the seller who holds the Buy Box, the literal "Amazon" when Amazon does.
- 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.
- 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 is WeCom's result inside the body, not the HTTP status?
Every group-robot send is POST https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid> (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29), and the server answers HTTP 200 whether the message actually landed or not. The documented success body is {"errcode": 0, "errmsg": "ok"}. A non-zero errcode with a readable errmsg marks a failure. Checking resp.status_code the way every non-DingTalk, non-Lark sibling channel in this series does would pass every one of these failure cases, because the status code itself never changes.
| Response | Reading | WeCom 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 WeCom?
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_wecom() sends every queued line as one markdown 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, so the script refuses to start. _markdown_body() builds the text and, only if the UTF-8 encoding of it is over 4096 bytes, decodes a truncated slice back with errors="ignore" so a multi-byte character is never cut in half, then re-encodes to confirm the result fits.
buybox_wecom_alert.py - offers check, 2-check confirmation, one group-robot send 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 WeCom 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
WECOM_WEBHOOK = os.environ["WECOM_WEBHOOK"] # https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid>
MAX_MARKDOWN_BYTES = 4096 # developer.work.weixin.qq.com/document/path/91770: markdown content,
# max 4096 BYTES (utf-8), not characters - CJK text can hit this fast
MAX_LINES = 200
RATE_LIMIT_CODE = 45009 # documented cap: 20 messages/minute per webhook key
INVALID_BOT_CODE = 93000 # bad/rotated key, or the bot was removed from the group
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('fulfillment', '?')}) at {box.get('price')} {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 _markdown_body(lines: list[str]) -> str:
"""Build the markdown content and cap it to 4096 UTF-8 BYTES (WeCom counts bytes, not characters,
so this encodes first and trims on the encoded length, never on len(text))."""
text = "**Amazon Buy Box change, confirmed on 2 checks:**\n" + "\n".join(f"> {l}" for l in lines)
encoded = text.encode("utf-8")
if len(encoded) > MAX_MARKDOWN_BYTES:
encoded = encoded[:MAX_MARKDOWN_BYTES - 40].decode("utf-8", "ignore").encode("utf-8")
encoded += b"\n> ...(truncated)"
return encoded.decode("utf-8")
def post_to_wecom(lines: list[str]) -> bool:
"""One POST per run to the group robot webhook. WeCom answers HTTP 200 even on a failure; the
real result is the JSON body's `errcode` field (0 = sent), never the HTTP status alone. Returns
True only on HTTP 200 AND errcode 0."""
if not lines:
return False
if len(lines) > MAX_LINES:
lines = lines[:MAX_LINES] + [f"...and {len(lines) - MAX_LINES} more"]
text = _markdown_body(lines)
payload = {"msgtype": "markdown", "markdown": {"content": text}}
resp = requests.post(WECOM_WEBHOOK, headers={"Content-Type": "application/json"},
json=payload, timeout=30)
try:
body = resp.json()
except ValueError:
print(f"[wecom] non-JSON response, HTTP {resp.status_code}, left unreported")
return False
errcode, errmsg = body.get("errcode"), body.get("errmsg", "")
if resp.status_code != 200:
print(f"[wecom] HTTP {resp.status_code}, left unreported")
return False
if errcode == 0:
print(f"[wecom] {text}")
return True
if errcode == RATE_LIMIT_CODE:
# 20 messages/minute per webhook key (developer.work.weixin.qq.com/document/path/91770).
# One fixed backoff-and-retry, same shape as Lark's 19021 and DingTalk's 130101 in this series.
time.sleep(5)
resp = requests.post(WECOM_WEBHOOK, headers={"Content-Type": "application/json"},
json=payload, timeout=30)
try:
body = resp.json()
except ValueError:
body = {}
if resp.status_code == 200 and body.get("errcode") == 0:
print(f"[wecom] {text}")
return True
print("[wecom] still rate-limited after 1 retry, left unreported")
return False
if errcode == INVALID_BOT_CODE:
# bad/rotated key, or the robot was removed from the group - retrying this run cannot fix it.
print(f"[wecom] STOP errcode={errcode} {errmsg} (webhook key invalid or bot removed)")
return False
print(f"[wecom] errcode={errcode} {errmsg}, left unreported")
return False
def main() -> None:
session = new_session()
state = _load_state()
lines = check(session, state)
sent = post_to_wecom(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; bracketed line = the message sent)
--- run 1 (illustrative ASIN and seller)
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
[wecom] **Amazon Buy Box change, confirmed on 2 checks:**
> B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD
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
[wecom] **Amazon Buy Box change, confirmed on 2 checks:**
> B0EXAMPLE2: BACK, you hold the Buy Box again
3 checked, 1 alert(s) sent
What the script actually POSTs (curl equivalent, illustrative values)
curl -s -X POST "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=693a91f6-7xxx-4bc4-97a0-0ec2sifa5aaa" \
-H "Content-Type: application/json" \
-d '{"msgtype": "markdown", "markdown": {"content": "**Amazon Buy Box change, confirmed on 2 checks:**\n> B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"}}'
# HTTP 200 {"errcode": 0, "errmsg": "ok"} <- success is still just a 200, read errcode

How do I create the robot and read its errcode?
- Add the robotOpen the target WeCom group, Group Settings, Group Robots, Add a Robot, give it a name and finish setup.
- Copy the webhook URL
https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=<uuid>. The key in the URL is the only thing protecting this robot; treat it like a password and never commit it. - Send a test message and read errcode
curl -d '{\"msgtype\": \"text\", \"text\": {\"content\": \"test\"}}' <webhook>; the HTTP status is 200 either way, so check the body'serrcode- 0 is the only value that means it actually arrived. - Watch the rate limit20 messages a minute per robot. Route high-volume alerts through confirmation and batching rather than one message per reading.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the webhook key lets anyone post to your group)
export SELLERMAGNET_API_KEY="your-key-here"
export WECOM_WEBHOOK="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
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_wecom_alert.py >> alert.log 2>&1
WeCom's own message-push documentation (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29) describes the contract the script relies on: every response is HTTP 200 and carries errcode/errmsg, the markdown content type is capped at 4096 bytes of UTF-8, and the whole webhook is capped at 20 messages per minute. Third-party integration guides (not WeCom's own docs) additionally report the specific numeric codes this script handles - 45009 for the rate limit and 93000 for an invalid or removed robot - which is why those two are cited as community-reported rather than from the primary source.
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; WeCom's own group-robot API is free for this volume, far under its 20-message-a-minute rate limit for a batch sent once per confirmed change. With a 2-check confirmation the worst-case delay before WeCom 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 |

Frequently Asked Questions
Do I need a WeCom admin role before I can send?
No. Open the target group in WeCom, Group Settings, Group Robots, Add a Robot, give it a name, and copy the Webhook URL it hands you. That is the whole setup; there is no app review, OAuth or corp secret involved, unlike WeCom's self-built-app path.
Why does WeCom's response look nothing like Telegram's or Rocket.Chat's?
A group-robot send always answers HTTP 200 (developer.work.weixin.qq.com/document/path/91770, checked 2026-11-29), even on a failure. The real result lives inside the JSON body's errcode field: 0 means sent, anything else is an error, with a human-readable errmsg next to it. That is the same shape as DingTalk and Lark earlier in this series and the opposite of Telegram's ok boolean on a real HTTP status or Rocket.Chat's bare success true - this script never once branches on resp.status_code alone for the outgoing call, only on body['errcode'] after confirming the status is 200.
Why cap the markdown body on bytes, not characters?
The official limit is 4096 bytes of UTF-8, not 4096 characters (developer.work.weixin.qq.com/document/path/91770). A seller name or city in CJK script runs 3 bytes per character, so a character-count cap would let a body through that WeCom still rejects. The script encodes to UTF-8 first and trims on the encoded length, then decodes back with errors="ignore" so it never splits a multi-byte character in half.
Why does errcode 45009 get retried when every other errcode here means stop?
45009 is the documented per-webhook throttle: a single group robot is capped at 20 messages a minute. The script waits 5 seconds and resends the identical payload once; a second 45009 in a row is logged and dropped rather than looped.
What does errcode 93000 mean, and why isn't it retried?
93000 means the webhook key is invalid, or the robot that owned it has been removed from the group. Resending the exact same payload changes nothing, so the script reports it and stops instead of retrying.
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, sends 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 WeCom group-robot message per run - read errcode inside the body, never the HTTP status, cap the markdown on UTF-8 bytes, and retry only the documented 45009 rate limit. 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.