To get an Amazon Buy Box lost alert pushed to DingTalk today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and POST one text message per run to your DingTalk custom robot's webhook. The one thing every other channel in this series gets you ready for and DingTalk breaks: the HTTP response is always 200, success or failure, so the script never looks at resp.status_code for the outgoing call - only at the errcode field inside the JSON body. The script below tells a lost Buy Box apart from a suppressed one, retries the one errcode DingTalk actually wants retried, and costs one SellerMagnet credit per ASIN per check.
Key Takeaways
- A DingTalk robot send answers HTTP 200 on every outcome - the real result is the JSON body's errcode (0 = sent), never the HTTP status the way every sibling channel in this series works.
- errcode 130101 is the one result in this whole alert-channel series that lives inside an always-200 body and still means 'retry': DingTalk's documented 20-messages-per-minute per-robot throttle. The script waits 10s and resends once.
- errcode 310000 covers a sign mismatch (Sign security) or a missing registered keyword (Keyword security) - a setup problem, never retried.
- 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 DingTalk's result inside the body, not the HTTP status?
Every custom-robot send is POST https://oapi.dingtalk.com/robot/send?access_token=... (help.dingtalk.io "Send group chats using a custom bot", checked 2026-11-26), and the server answers HTTP 200 whether the message actually went out or not. The only way to know is to read the JSON body: {"errcode": 0, "errmsg": "ok"} on success, or a non-zero errcode with a human-readable errmsg on failure - 310000 for a sign or keyword problem, 130101 for the rate limit, 300001 if the webhook token no longer exists. Checking resp.status_code the way every sibling channel in this series does would pass every single failure case here, because the status code itself never changes.
| Response | Reading | DingTalk 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 DingTalk?
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_dingtalk() sends every queued line as one robot 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. When the robot's security setting is Sign, _signed_url() appends a fresh timestamp and an HMAC-SHA256 sign to the webhook on every call, exactly as DingTalk's own signing recipe requires; when it is Keyword instead, DINGTALK_SECRET is left unset and the URL goes out unchanged.
buybox_dingtalk_alert.py - offers check, 2-check confirmation, one robot send per run
import base64
import hashlib
import hmac
import json
import os
import re
import time
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 DingTalk 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
DINGTALK_WEBHOOK = os.environ["DINGTALK_WEBHOOK"] # https://oapi.dingtalk.com/robot/send?access_token=...
DINGTALK_SECRET = os.environ.get("DINGTALK_SECRET") # set only if the robot's security setting is "Sign"
MAX_MESSAGE_CHARS = 20000 # help.dingtalk.io text message practical cap
MAX_LINES = 20
RATE_LIMIT_ERRCODE = 130101 # "send too fast, exceed 20 times per minute"
def _signed_url() -> str:
"""Append timestamp+sign to the webhook when the robot's security setting is Sign (not Keyword)."""
if not DINGTALK_SECRET:
return DINGTALK_WEBHOOK
timestamp = str(round(time.time() * 1000))
string_to_sign = f"{timestamp}\n{DINGTALK_SECRET}"
digest = hmac.new(DINGTALK_SECRET.encode(), string_to_sign.encode(), digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(digest))
sep = "&" if "?" in DINGTALK_WEBHOOK else "?"
return f"{DINGTALK_WEBHOOK}{sep}timestamp={timestamp}&sign={sign}"
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))]
detail += f", your offer {mine[0]:.2f}" if mine else ""
return "lost", detail
def post_to_dingtalk(lines: list[str]) -> bool:
"""One text message per run. DingTalk always answers HTTP 200; the real result is errcode in the body.
errcode 0 = sent. errcode 130101 = rate limited (20 msg/min per robot), retried once after 10s with the
exact same text (the JSON body itself, never the HTTP status, carries that number). errcode 310000 means
either the sign did not match or (if the robot uses Keyword security instead of Sign) the text is missing
the registered keyword - both are a setup problem, not a transient one, so the script stops retrying and
reports it rather than looping. Anything else is logged and dropped; a dropped alert is not re-queued.
"""
if not lines:
return False
text = "\n".join(lines[:MAX_LINES])
if len(lines) > MAX_LINES:
text += f"\n...and {len(lines) - MAX_LINES} more"
if len(text) > MAX_MESSAGE_CHARS:
text = text[:MAX_MESSAGE_CHARS - 3] + "..."
payload = {"msgtype": "text", "text": {"content": f"[dingtalk] {text}"}}
for attempt in range(2):
resp = requests.post(_signed_url(), json=payload, timeout=30)
try:
body = resp.json()
except ValueError:
print(f"dingtalk: non-JSON response, HTTP {resp.status_code}")
return False
errcode = body.get("errcode")
if errcode == 0:
return True
if errcode == RATE_LIMIT_ERRCODE and attempt == 0:
time.sleep(10) # DingTalk's own guidance: 20 msg/min per robot, wait and resend
continue
print(f"dingtalk: errcode {errcode} ({body.get('errmsg')}), not retried")
return False
return False
def load_state() -> dict:
try:
with open(STATE_FILE) as f:
return json.load(f)
except FileNotFoundError:
return {}
def check() -> None:
session = new_session()
state = load_state()
lines, checked = [], 0
for asin in ASINS:
if not ASIN_RE.match(asin):
print(f"skip malformed ASIN: {asin}")
continue
try:
reading, detail = read_buy_box(session, asin)
except ApiError as err:
if err.status in (401, 403):
print(f"stop: {err.status}, no more calls this run")
break
print(f"skip {asin}: {err.status}")
continue
checked += 1
entry = state.get(asin, {"reading": reading, "streak": 1, "reported": reading})
if reading == entry["reading"]:
entry["streak"] += 1
else:
entry = {"reading": reading, "streak": 1, "reported": entry["reported"]}
if entry["streak"] >= CONFIRM and entry["reported"] != reading:
if reading == "lost":
lines.append(f"{asin}: LOST, held by {detail}")
elif reading == "mine" and entry["reported"] == "lost":
lines.append(f"{asin}: BACK, you hold the Buy Box again")
entry["reported"] = reading
state[asin] = entry
sent = post_to_dingtalk(lines)
with open(STATE_FILE, "w") as f:
json.dump(state, f)
print(f"{checked} checked, {1 if sent else 0} alert(s) sent" if lines else f"{checked} checked, 0 alert(s) sent")
if __name__ == "__main__":
check()
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 ---
[dingtalk] B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99
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 ---
[dingtalk] B0EXAMPLE2: BACK, you hold the Buy Box again
3 checked, 1 alert(s) sent
What the script actually POSTs (curl equivalent, illustrative values, Sign security)
curl -s -X POST "https://oapi.dingtalk.com/robot/send?access_token=xxxx×tamp=1732000000000&sign=abc%3D" \
-H "Content-Type: application/json" \
-d '{"msgtype": "text", "text": {"content": "[dingtalk] 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 DingTalk group, Group settings, Smart group assistant, Add robot, Custom, and finish setup.
- Pick a security settingSign gives you a secret and needs the timestamp+sign query pair on every call; Keyword instead requires one registered word somewhere in every message text and needs no secret at all.
- Copy the webhook
https://oapi.dingtalk.com/robot/send?access_token=xxxx. The access_token is the only thing addressing your robot; losing it means re-creating the robot. - 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.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the webhook access_token lets anyone post to your group)
export SELLERMAGNET_API_KEY="your-key-here"
export DINGTALK_WEBHOOK="https://oapi.dingtalk.com/robot/send?access_token=xxxxxxxxxxxxxxxx"
export DINGTALK_SECRET="SECxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # only if security = Sign
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_dingtalk_alert.py >> alert.log 2>&1
DingTalk's own documentation (help.dingtalk.io "Send group chats using a custom bot" and its custom-robot FAQ, both checked 2026-11-26, plus Alibaba Cloud SLS's published error-code table for the same API) describe the contract the script relies on: every response is HTTP 200 and carries errcode/errmsg; a single robot answering 130101 has hit the documented 20-messages-per-minute throttle and is told to wait before the next attempt; a 310000 means the sign did not verify or (under Keyword security) the text lacked the registered word, and resending the identical text changes neither. Messages have a practical length limit well under DingTalk's realm defaults, which is why the script caps and summarizes a long batch rather than risking an oversized call.
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; DingTalk's own robot API is free for this volume, far under its 20-messages-per-minute throttle for a batch sent once per confirmed change. With a 2-check confirmation the worst-case delay before DingTalk 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 DingTalk account or admin permission before I can send?
No enterprise app or admin role: open the target DingTalk group, Group settings, Smart group assistant, Add robot, Custom, and copy the webhook URL it hands you. If you also tick the Sign security option, it shows you a secret once; there is no OAuth step either way.
Why does DingTalk's response look nothing like Telegram's or Rocket.Chat's?
A DingTalk robot send always answers HTTP 200 (help.dingtalk.io, checked 2026-11-26), even on a failure. The real result lives entirely 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 opposite of Telegram's ok boolean on a real HTTP status, Rocket.Chat's bare {\"success\": true}, or Mattermost's plain-text ok - this script never once branches on resp.status_code for the outgoing call, only on body['errcode'].
Why does a 130101 get retried when every other errcode here means stop?
errcode 130101 is DingTalk's own documented per-robot throttle: a maximum of 20 messages a minute, and going over it answers 130101 \"send too fast, exceed 20 times per minute\" while still returning HTTP 200 (help.dingtalk.io custom-bot FAQ; Alibaba Cloud SLS error-code reference, both checked 2026-11-26). The script waits 10 seconds and resends the identical text once; a second 130101 in a row is logged and dropped rather than looped.
What does errcode 310000 mean, and why isn't it retried?
310000 covers two different setup problems with the same code: the HMAC sign does not match (wrong or stale DINGTALK_SECRET), or - if the robot is configured with Keyword security instead of Sign - the message text does not contain the one registered keyword. Resending the same text changes nothing in either case, so the script reports it and does not retry.
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 DingTalk robot message per run - read errcode inside the body, never the HTTP status, and retry only the documented 130101 throttle. 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.