To get an Amazon Buy Box lost alert pushed to Telegram today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and call Telegram's sendMessage once per run: POST https://api.telegram.org/bot<token>/sendMessage with chat_id and text. No webhook server, no signing, just a bot token from @BotFather and a chat_id. The script below tells a lost Buy Box apart from a suppressed one, retries the one 4xx Telegram actually wants retried, and costs one SellerMagnet credit per ASIN per check.
Key Takeaways
- Every sendMessage response is JSON with a boolean ok field, success in result, failure in error_code/description - unlike ntfy's id/time/event body, Mattermost's plain-text ok, or Rocket.Chat's bare {"success": true}.
- A 429 is the one 4xx in this whole alert-channel series that gets retried: Telegram's own response carries parameters.retry_after, the exact number of seconds to wait before trying again (core.telegram.org/bots/faq).
- A 400 "chat not found" or a 403 "bot was blocked by the user" are real input problems and are never retried, same as every sibling channel's hard 4xx class.
- 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.
How is Telegram's sendMessage different from ntfy, Mattermost or Rocket.Chat?
There is no account-free publishing like ntfy: a bot has to exist (@BotFather hands you a token) and the target chat has to have contacted the bot at least once before the bot can message it, which is how you discover its chat_id in the first place (via getUpdates). Once set up, every call to sendMessage (core.telegram.org/bots/api, checked 2026-11-25) answers with the same JSON envelope regardless of method: {"ok": true, "result": {...}} on success, or {"ok": false, "error_code": N, "description": "..."} on failure. That single ok boolean is the whole contract; there is no separate HTTP-status-only check like ntfy's, and no plain-text or bare-JSON success body like Mattermost's or Rocket.Chat's.
| Response | Reading | Telegram 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 Telegram?
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_telegram() sends every queued line as one sendMessage call. 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. A new ASIN seeds its state to whatever it first reads, so a listing that starts out suppressed never fires a false alert just for staying that way. Lines are capped and summarized before the message reaches sendMessage's documented 4,096-character limit, instead of letting Telegram reject an oversized call.
buybox_telegram_alert.py - offers check, 2-check confirmation, one sendMessage 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 Telegram 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_MESSAGE_CHARS = 4096 # core.telegram.org/bots/api sendMessage: text is 1-4096 characters
MAX_LINES = 20 # keep well under the 4096-char body even with long lines
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 line_for(asin: str, key: str, detail: str) -> str:
text = {"mine": "BACK, you hold the Buy Box again",
"suppressed": "NONE, offers exist but Amazon features none",
"no-offers": "EMPTY, no offers on the listing"}.get(key, f"LOST, held by {detail}")
return f"{asin}: {text}"
def build_message(lines: list[str]) -> str:
# sendMessage: text is 1-4096 characters. Summarize instead of truncating mid-line.
if len(lines) > MAX_LINES:
lines = lines[:MAX_LINES] + [f"+{len(lines) - MAX_LINES} more, see the dashboard"]
header = "Amazon Buy Box change, confirmed on 2 checks:\n"
body = header + "\n".join(lines)
while len(body) > MAX_MESSAGE_CHARS and lines:
lines = lines[:-1] + ["+1 more, see the dashboard"]
body = header + "\n".join(lines)
return body
def post_to_telegram(token: str, chat_id: str, lines: list[str]) -> bool:
"""One message per run. The response is ALWAYS JSON with a boolean `ok` field (core.telegram.org/bots/api,
"Making requests", checked 2026-11-25) - unlike ntfy's id/time/event body with no status field, Mattermost's
plain-text `ok`, or Rocket.Chat's bare `{"success": true}`. A 429 (Too Many Requests) is the one exception to
"4xx means stop" every sibling channel in this series follows: Telegram answers it with
`{"ok": false, "error_code": 429, "parameters": {"retry_after": N}}` (core.telegram.org/bots/faq, "My bot is
hitting limits") and expects exactly one retry after sleeping `retry_after` seconds, not a permanent give-up.
A 400 "chat not found" (the bot was never started by, or added to, that chat_id) or a 403 (the user blocked
the bot) are genuine input problems and must not be retried."""
if not lines:
return True
payload = {"chat_id": chat_id, "text": build_message(lines)}
url = f"https://api.telegram.org/bot{token}/sendMessage"
for attempt in range(2): # at most one retry, only for the 429 class
try:
resp = requests.post(url, data=payload, timeout=10)
except requests.RequestException as err:
print(f"telegram unreachable: {type(err).__name__}")
if attempt == 0:
time.sleep(5)
continue
return False
try:
body = resp.json()
except ValueError:
body = {}
if body.get("ok"):
return True
if resp.status_code == 429 and attempt == 0:
wait = (body.get("parameters") or {}).get("retry_after", 1)
print(f"telegram 429, retrying after {wait}s") # the one retryable 4xx in this series
time.sleep(wait)
continue
print(f"telegram rejected the message: {resp.status_code} {body.get('description')}") # input problem
return False
return False
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], token: str, chat_id: str) -> None:
session, state = new_session(), load_state()
alerts, problems, checked, stopped = [], [], 0, ""
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.get(asin)
if s is None:
# first-ever sighting of this ASIN: seed state to it so a steady reading never alerts as a change
s = state[asin] = {"last": key, "streak": 1, "reported": key}
continue
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, line_for(asin, key, detail)))
lines = [line for _, _, line in alerts]
if stopped and state.get("_stopped") != stopped:
lines.append(f"STOP: checks stopped: {stopped}") # said once, not every run
sent = post_to_telegram(token, chat_id, lines)
if sent:
for asin, key, _ in alerts:
state[asin]["reported"] = key # only after Telegram answered ok:true, else re-sent
if stopped:
state["_stopped"] = stopped
if not stopped:
state.pop("_stopped", None)
save_state(state)
for line in problems:
print(line)
print(f"{checked} checked, {len(alerts)} alert(s) {'sent' if sent else 'NOT sent, retried next run'}")
if __name__ == "__main__":
check(ASINS, os.environ["TELEGRAM_BOT_TOKEN"], os.environ["TELEGRAM_CHAT_ID"])
Five runs of the script (illustrative ASIN and seller; [telegram] = 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
[telegram] Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD, your offer 19.99
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
[telegram] 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)
curl -s -X POST https://api.telegram.org/bot123456:ABC-token/sendMessage \
-d chat_id=123456789 \
-d text="Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"
# {"ok": true, "result": {"message_id": 42, "date": 1732000000, "text": "..."}}

How do I create the bot and find my chat_id?
- Create the botMessage @BotFather in Telegram, send
/newbot, pick a name and a username ending inbot. It replies with your bot's token. - Start a chat with the botSearch for your bot's username and send it any message (for example
/start). A bot cannot message a chat it has not been contacted by first. - Read your chat_idOpen
https://api.telegram.org/bot<token>/getUpdatesin a browser; the JSON it returns includesmessage.chat.idfor the message you just sent. A private chat with a single user has a positive id; a group's id is negative. - Send a test message
curl -d chat_id=<id> -d text=test https://api.telegram.org/bot<token>/sendMessage; it should arrive in the chat within a few seconds and the response should carry"ok": true.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the bot token lets anyone send as your bot)
export SELLERMAGNET_API_KEY="your-key-here"
export TELEGRAM_BOT_TOKEN="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11"
export TELEGRAM_CHAT_ID="123456789" # from getUpdates after messaging the bot once
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_telegram_alert.py >> alert.log 2>&1
Telegram's own documentation (core.telegram.org/bots/api, "Making requests", and core.telegram.org/bots/faq, "My bot is hitting limits", both checked 2026-11-25) describe the contract the script relies on: every response carries ok, and a single chat should not receive more than one message per second or it starts answering 429 with a machine-readable retry_after. That is the only 4xx in this alert-channel series worth retrying; a 400 (bad chat_id, or a chat the bot was never added to) or a 403 (the user blocked the bot) are real input problems and must not be retried unchanged, while a 5xx or no reply at all is Telegram's own temporary problem and gets exactly one retry. Messages over 4,096 characters are rejected outright with a 400, which is why the script summarizes a long batch rather than letting Telegram reject the whole 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; Telegram's Bot API itself is free for this volume, far under the one-message-per-second-per-chat guidance for a batch sent once per confirmed change. With a 2-check confirmation the worst-case delay before Telegram 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
Do I need a Telegram account or app registration before I can send?
You need a bot (create one with @BotFather, which hands you a token) and a chat_id: either your own, found by messaging the bot once and reading the chat_id back from getUpdates, or a group's. There is no webhook server and no OAuth, but unlike ntfy's zero-step public topic, a Telegram bot cannot message a chat until that chat has contacted it first.
Does Telegram's response look like ntfy's, Mattermost's or Rocket.Chat's?
No. sendMessage always answers with JSON that carries a boolean ok field (core.telegram.org/bots/api, "Making requests", checked 2026-11-25): ok:true with the sent message in result, or ok:false with error_code and description. That is different from ntfy's id/time/event body with no status field, Mattermost's plain-text ok, and Rocket.Chat's bare {"success": true}; this script checks body.get("ok") and nothing else.
Why does a 429 get retried here when every other channel's 4xx means stop?
Telegram's rate-limit response is a documented exception. core.telegram.org/bots/faq ("My bot is hitting limits") says to avoid sending more than one message per second to the same chat; go over it and you get HTTP 429 with {"ok": false, "error_code": 429, "parameters": {"retry_after": N}}, which tells you exactly how long to wait. The script sleeps for that many seconds and retries once; every other 4xx (400 chat not found, 403 blocked by the user) is a real input problem and is never retried.
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 the bot's chat_id is wrong or the user blocked the bot?
A wrong or never-started chat_id answers 400 with description "Bad Request: chat not found"; a user who blocked the bot answers 403 "Forbidden: bot was blocked by the user". Both are genuine input problems, so the script logs them and leaves the alert unreported for the next run rather than retrying the same request.
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 send one Telegram sendMessage call per run - retry only the documented 429, never a 400 or 403. 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.