Home / Blog / Amazon Buy Box Lost Alert in Lark: Read code, Not HTTP Status

Amazon Buy Box Lost Alert in Lark: Read code, Not HTTP Status

Get an Amazon Buy Box lost alert pushed to Lark (Feishu): poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one text message per run to a custom bot webhook. Lark always answers HTTP 200; the script reads the code field inside the JSON body instead. Costs one credit per ASIN per check.

November 28, 2026
8 min read
SellerMagnet Team
Share & Bookmark
Terminal window showing the Amazon Buy Box lost alert a Python script sent via Lark

To get an Amazon Buy Box lost alert pushed to Lark (or Feishu, its China edition) 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 Lark custom bot's webhook. The one thing every other channel in this series gets you ready for and Lark breaks the same way DingTalk does: 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 code field inside the JSON body. The script below tells a lost Buy Box apart from a suppressed one, retries the one code Lark actually wants retried, and costs one SellerMagnet credit per ASIN per check.

Key Takeaways

  • A Lark custom-bot send answers HTTP 200 on every outcome - the real result is the JSON body's code (0 = sent), never the HTTP status alone, the same shape as DingTalk's errcode in this series.
  • code 19021 is the one result in this series that means 'retry': Lark's documented per-webhook rate limit. The script waits 5s and resends once.
  • code 19002 means the HMAC sign did not verify (wrong secret or clock skew) - a setup problem, never retried.
  • The HMAC sign is computed over an EMPTY message using timestamp+"\n"+secret as the key, then base64 encoded - both fields travel in the request body, not the URL, unlike DingTalk's query-string sign.
  • 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 Lark's result inside the body, not the HTTP status?

Every custom-bot send is POST https://open.larksuite.com/open-apis/bot/v2/hook/<token> (open.larksuite.com "Custom bot usage guide", checked 2026-11-28), and the server answers HTTP 200 whether the message actually landed or not. The documented success body is {"code": 0, "msg": "success", "data": {}}, alongside legacy StatusCode/StatusMessage fields the same docs call redundant and say not to rely on. A non-zero code with a readable msg marks a failure - 19002 for a sign mismatch, 19021 for the rate limit, 19024 once the bot has been removed from the chat. Checking resp.status_code the way every non-DingTalk sibling channel in this series does would pass every one of these failure cases, because the status code itself never changes.

The four readings and the Lark message each one can trigger.
ResponseReadingLark message
buyBox.sellerId is your sellerIdmineBACK, after a confirmed loss
buyBox.sellerId is any other seller or "Amazon"lostLOST, with holder, price and your offer
buyBox is {} and buyBoxSuppressed is truesuppressedNONE
buyBox is {} and offers is []no-offersEMPTY

How do I build the Amazon Buy Box lost alert for Lark?

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_lark() sends every queued line as one bot 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 bot's Signature Verification is on, _signed_body() adds a fresh timestamp and an HMAC-SHA256 sign to the JSON body on every call, exactly as Lark's own signing recipe requires; when it is off, LARK_SECRET is left unset and the payload goes out unchanged.

buybox_lark_alert.py - offers check, 2-check confirmation, one bot send per run

import base64
import hashlib
import hmac
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 Lark 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

LARK_WEBHOOK = os.environ["LARK_WEBHOOK"]     # https://open.larksuite.com/open-apis/bot/v2/hook/<token>
LARK_SECRET = os.environ.get("LARK_SECRET")   # set only if the bot has "Signature Verification" enabled
MAX_BODY_CHARS = 28000                        # practical text-message cap, capped defensively under it
MAX_LINES = 200
RATE_LIMIT_CODE = 19021                       # "request too fast" (per-webhook throttle)


def _signed_body(payload: dict) -> dict:
    """Add timestamp+sign when Signature Verification is on. open.larksuite.com custom-bot docs
    (checked 2026-11-28): the HMAC-SHA256 key is "<timestamp>\\n<secret>" and the signed message is
    an EMPTY string - not the JSON body - then base64 encoded. Both fields travel in the body."""
    if not LARK_SECRET:
        return payload
    timestamp = str(int(time.time()))
    string_to_sign = f"{timestamp}\n{LARK_SECRET}"
    digest = hmac.new(string_to_sign.encode(), b"", digestmod=hashlib.sha256).digest()
    payload = dict(payload, timestamp=timestamp, sign=base64.b64encode(digest).decode())
    return payload


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 post_to_lark(lines: list[str]) -> bool:
    """One POST per run to the custom-bot webhook. Lark answers HTTP 200 even on a failure; the real
    result is the JSON body's `code` field (0 = sent), never the HTTP status. Returns True only on
    HTTP 2xx AND code 0."""
    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)
    if len(text) > MAX_BODY_CHARS:
        text = text[:MAX_BODY_CHARS - 20] + "\n...(truncated)"
    payload = _signed_body({"msg_type": "text", "content": {"text": text}})
    resp = requests.post(LARK_WEBHOOK, headers={"Content-Type": "application/json"},
                          data=json.dumps(payload), timeout=30)
    try:
        body = resp.json()
    except ValueError:
        print(f"[lark] non-JSON response, HTTP {resp.status_code}, left unreported")
        return False
    code, msg = body.get("code"), body.get("msg", "")
    if resp.status_code != 200:
        print(f"[lark] HTTP {resp.status_code}, left unreported")
        return False
    if code == 0:
        print(f"[lark] {text}")
        return True
    if code == RATE_LIMIT_CODE:
        # "request too fast": the documented per-webhook throttle. One fixed backoff-and-retry, same
        # shape as DingTalk's 130101 - the opposite of Flock's channel, which never reports a result at all.
        time.sleep(5)
        resp = requests.post(LARK_WEBHOOK, headers={"Content-Type": "application/json"},
                              data=json.dumps(payload), timeout=30)
        try:
            body = resp.json()
        except ValueError:
            body = {}
        if resp.status_code == 200 and body.get("code") == 0:
            print(f"[lark] {text}")
            return True
        print("[lark] still rate-limited after 1 retry, left unreported")
        return False
    if code in (19002, 19001, 9499):
        # sign mismatch / bad msg_type or content / malformed JSON - a setup problem, never retried.
        print(f"[lark] STOP code={code} {msg}")
        return False
    if code == 19024:
        # bot removed from the chat - retrying this run cannot put it back.
        print(f"[lark] STOP code={code} {msg} (bot not in chat)")
        return False
    print(f"[lark] code={code} {msg}, left unreported")
    return False


def main() -> None:
    session = new_session()
    state = _load_state()
    lines = check(session, state)
    sent = post_to_lark(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)
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
[lark] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD
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
[lark] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: BACK, you hold the Buy Box again
1 checked, 1 alert(s) sent

What the script actually POSTs (curl equivalent, illustrative values, Signature Verification on)

curl -s -X POST "https://open.larksuite.com/open-apis/bot/v2/hook/examplehook0001" \
  -H "Content-Type: application/json" \
  -d '{"msg_type": "text", "content": {"text": "B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"}, "timestamp": "1732000000", "sign": "abc123base64=="}'
# HTTP 200 {"code": 0, "msg": "success", "data": {}}  <- success is still just a 200, read code
Blueprint flow: offers check per ASIN, two-check confirmation, then one Lark send
A reading has to repeat before it reaches Lark; the result comes from code.

How do I create the bot and read its code?

  1. Add the botOpen the target group, Settings, Group Bots (or Bots), Add Bot, Custom Bot, and finish setup.
  2. Pick Signature Verification or notTurning it on gives you a secret and needs the timestamp+sign body pair on every call; leaving it off needs no secret at all.
  3. Copy the webhookhttps://open.larksuite.com/open-apis/bot/v2/hook/xxxx (or the open.feishu.cn equivalent). The token in the URL is the only thing addressing your bot; losing it means re-creating the bot.
  4. Send a test message and read codecurl -d '{"msg_type": "text", "content": {"text": "test"}}' <webhook>; the HTTP status is 200 either way, so check the body's code - 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 token lets anyone post to your group)
export SELLERMAGNET_API_KEY="your-key-here"
export LARK_WEBHOOK="https://open.larksuite.com/open-apis/bot/v2/hook/xxxxxxxxxxxxxxxxxxxxxxxx"
export LARK_SECRET="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"   # only if Signature Verification is on
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_lark_alert.py >> alert.log 2>&1

Lark's own custom-bot documentation (open.larksuite.com "Custom bot usage guide", checked 2026-11-28) describes the contract the script relies on: every response is HTTP 200 and carries code/msg (plus the legacy, explicitly-not-recommended StatusCode/StatusMessage pair); a sign is computed as base64(HMAC-SHA256(key = timestamp+"\n"+secret, message = empty)) and travels in the request body with timestamp. Third-party integration guides (not Lark's own docs) additionally report numeric codes for the common failures this script handles - a rate limit and a bot removed from its chat - 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; Lark's own custom-bot API is free for this volume, far under its per-webhook rate limit for a batch sent once per confirmed change. With a 2-check confirmation the worst-case delay before Lark 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.

Credits per tracked ASIN by check interval (1 credit per offers call).
Check intervalCredits per dayCredits per 30 daysWorst-case alert delay
Every 15 minutes962,880about 30 minutes
Every hour24720about 2 hours
Every 4 hours6180about 8 hours
Once a day130about 2 days
Blueprint table of credits per tracked ASIN for four check intervals and the alert delay
Shorter intervals cost more credits and cut the delay; the confirmation doubles it.

Frequently Asked Questions

Do I need a Lark/Feishu admin role before I can send?

No. Open the target group, Settings, Group Bots (or Bots), Add Bot, Custom Bot, and copy the webhook URL it hands you. Turning on Signature Verification shows you a secret once; neither step needs an app review or OAuth.

Why does Lark's response look nothing like Telegram's or Rocket.Chat's?

A custom-bot send always answers HTTP 200 (open.larksuite.com custom-bot usage guide, checked 2026-11-28), even on a failure. The real result lives inside the JSON body's code field: 0 means sent, anything else is an error, with a human-readable msg next to it. The same body also carries legacy StatusCode/StatusMessage fields the docs mark redundant and tell you not to use. That is 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['code'] after confirming the status is 200.

Why is the HMAC sign computed over an empty string?

It looks backwards the first time you read it: the signing key is timestamp + "\n" + secret, and the HMAC-SHA256 message it signs is empty, then the digest is base64 encoded (open.larksuite.com custom-bot guide, checked 2026-11-28). Unlike DingTalk, which puts timestamp and sign in the URL query, Lark expects both fields inside the JSON body alongside msg_type and content.

Why does code 19021 get retried when every other code here means stop?

19021 ("request too fast") is the documented per-webhook throttle on a custom bot. The script waits 5 seconds and resends the identical payload once; a second 19021 in a row is logged and dropped rather than looped.

What does code 19002 mean, and why isn't it retried?

19002 is a sign mismatch: either Signature Verification is on and LARK_SECRET is wrong or stale, or the bot's clock-skew tolerance rejected a timestamp. 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 Lark bot message per run - read code inside the body, never the HTTP status, and retry only the documented 19021 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.

Related Articles

Continue exploring topics related to this article.

Terminal window showing the Amazon Buy Box lost alert a Python script sent through Threema Gateway
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Threema: a Bare Message ID, Not JSON

Get an Amazon Buy Box lost alert sent through Threema Gateway: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm on a second check and POST one form-encoded message per run to send_simple. A successful send answers HTTP 200 with the new message's id as bare plain text, no JSON, while every failure gets its own HTTP status. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script sent via WeCom
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in WeCom: Read errcode, Not HTTP Status

Get an Amazon Buy Box lost alert pushed to WeCom (Enterprise WeChat): poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one markdown message per run to a group robot webhook. WeCom always answers HTTP 200; the script reads the errcode field inside the JSON body instead, and caps the message on UTF-8 bytes, not characters. Costs one credit per ASIN per check.

Nov 29, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script posted to Chatwork
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert in Chatwork: Form Body, Not JSON

Get an Amazon Buy Box lost alert posted straight into Chatwork: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check and POST one message per run through Chatwork's Add Message endpoint. Covers the X-ChatWorkToken header auth, the form-urlencoded body other channels get wrong by sending JSON, and the two separate 429 rate limiters. Tested Python, one credit per ASIN per check.

Nov 29, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime