To get an Amazon Buy Box lost alert sent through Viber today, poll /amazon-product-offers for each of your ASINs, compare buyBox.sellerId with your own seller ID, and call POST /pa/send_message once per run: https://chatapi.viber.com/pa/send_message with type: "text", receiver and text, authenticated by an X-Viber-Auth-Token header. Viber answers HTTP 200 for a success and for almost every failure alike, so the script reads the JSON status field, not the HTTP status code. The script below tells a lost Buy Box apart from a suppressed one, confirms a change on a second check, and costs one SellerMagnet credit per ASIN per check.
Key Takeaways
- Authentication is an
X-Viber-Auth-Tokenheader, the bot's own auth token, never a Bearer token or a secret baked into the URL. - A successful
POST /pa/send_messagestill answers HTTP 200 - the real result is the JSONstatusfield (0means ok) andstatus_message, never the HTTP status code. - The receiver must already be a subscribed Viber user:
receiverNotRegistered(5) andreceiverNotSubscribed(6) are two separate, documented reasons a send can never land. - Viber gives no client-set idempotency key like Pushbullet's guid, so the script retries only the one status it documents as transient (
12, tooManyRequests) and leaves every other failure for the next run rather than risk a duplicate send. - 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; 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 send.
How is Viber's status field different from Pushbullet, Telegram or LINE?
Every other channel in this series signals failure through the HTTP status code: Pushbullet answers a bad request with a non-200 status, Telegram's ok flag still rides inside a 200 but a malformed request gets 400 or 403, and LINE returns 400/401/409/429 directly. Viber (developers.viber.com, checked 2026-11-27) is the one channel in this series that answers almost every call, success or failure, with plain HTTP 200 and puts the real outcome entirely in the body: a numeric status (0 for success, a documented code otherwise) and a status_message string. A script written to check resp.status_code == 200 and stop there would treat every Viber failure as a success.
| Response | Reading | Viber message |
|---|---|---|
| buyBox.sellerId is your sellerId | mine | BACK, after a confirmed return |
| 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 Viber?
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_viber() sends every queued line as one POST /pa/send_message call and reads the JSON status field to decide what happened. 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. Only status 12 (tooManyRequests) is retried, once, after a fixed backoff, because it is the one status Viber documents as transient; receiverNotRegistered/receiverNotSubscribed and the billing statuses stop without retry since nothing about retrying changes a user who never subscribed or an empty balance; and the body is capped under Viber's documented 30 KB text message limit.
buybox_viber_alert.py - offers check, 2-check confirmation, one status-checked POST per run
import hashlib
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 Viber 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
VIBER_API = "https://chatapi.viber.com/pa/send_message"
VIBER_AUTH_TOKEN = os.environ["VIBER_AUTH_TOKEN"]
VIBER_RECEIVER_ID = os.environ["VIBER_RECEIVER_ID"] # the subscribed user's Viber ID, from the webhook callback
MAX_BODY_CHARS = 28000 # Viber's own docs cap a text message at 30 KB; capped
# defensively under that so the JSON envelope never pushes
# one oversized run over the documented limit
MAX_LINES = 200
# https://developers.viber.com/docs/api/rest-bot-api/ error codes (checked 2026-11-27)
PERMANENT_STATUS = {
2: "invalidAuthToken", 3: "badData", 4: "missingData",
5: "receiverNotRegistered", 6: "receiverNotSubscribed",
7: "publicAccountBlocked", 8: "publicAccountNotFound", 9: "publicAccountSuspended",
15: "publicAccountNotAuthorized",
}
BILLING_STATUS = {23: "freeMessagesExceeded", 24: "noBalance"}
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 _tracking_data(lines: list[str], window: int) -> str:
"""Viber has no client-set idempotency key like Pushbullet's guid, so tracking_data only carries an
audit fingerprint for our own logs/replies - it does NOT make a retried send safe at the vendor."""
digest = hashlib.sha256(("\n".join(lines) + str(window)).encode()).hexdigest()[:24]
return f"buybox-{digest}"
def post_to_viber(lines: list[str]) -> bool:
"""One POST /pa/send_message per run. Viber answers HTTP 200 even on failure; the real result is the
JSON status field (0 = ok), never the HTTP status code. Returns True only on status 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)"
tracking = _tracking_data(lines, window=int(time.time() // 60))
payload = {
"receiver": VIBER_RECEIVER_ID,
"min_api_version": 1,
"sender": {"name": "Buy Box Alert"},
"type": "text",
"text": text,
"tracking_data": tracking,
}
resp = requests.post(
VIBER_API,
headers={"X-Viber-Auth-Token": VIBER_AUTH_TOKEN, "Content-Type": "application/json"},
data=json.dumps(payload),
timeout=30,
)
try:
body = resp.json()
except ValueError:
print(f"[viber] non-JSON response, HTTP {resp.status_code}, left unreported")
return False
status, status_message = body.get("status"), body.get("status_message", "")
if status == 0:
print(f"[viber] message_token={body.get('message_token')} {text}")
return True
if status == 12:
# tooManyRequests: Viber's docs name the code but give no numeric Retry-After, so one fixed
# backoff-and-retry is as precise as this API gets (same shape as Pushbullet's undocumented 429,
# but signalled through status 12 instead of an HTTP status code).
time.sleep(5)
resp = requests.post(
VIBER_API,
headers={"X-Viber-Auth-Token": VIBER_AUTH_TOKEN, "Content-Type": "application/json"},
data=json.dumps(payload),
timeout=30,
)
try:
body = resp.json()
except ValueError:
body = {}
if body.get("status") == 0:
print(f"[viber] message_token={body.get('message_token')} {text}")
return True
print(f"[viber] still tooManyRequests after 1 retry, left unreported")
return False
if status in PERMANENT_STATUS:
# receiverNotRegistered/receiverNotSubscribed etc: the recipient has to re-subscribe to the bot
# before any further send can land, so retrying this run changes nothing.
print(f"[viber] STOP status={status} {status_message or PERMANENT_STATUS[status]}")
return False
if status in BILLING_STATUS:
print(f"[viber] STOP status={status} {status_message or BILLING_STATUS[status]} (billing)")
return False
print(f"[viber] status={status} {status_message}, left unreported")
return False
def main() -> None:
session = new_session()
state = _load_state()
lines = check(session, state)
sent = post_to_viber(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; [viber] = 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
[viber] message_token=4912661846655238145 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
[viber] message_token=4912661846655238145 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://chatapi.viber.com/pa/send_message \\
-H "X-Viber-Auth-Token: 445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9" \\
-H "Content-Type: application/json" \\
-d '{"receiver": "01234567890A=", "min_api_version": 1, "sender": {"name": "Buy Box Alert"},
"type": "text", "tracking_data": "buybox-9f2a1c0e8b3d4f5a",
"text": "Amazon Buy Box change, confirmed on 2 checks:
B0EXAMPLE2: LOST, held by Example Outlet (A2OTHERSELLER0, FBA) at 18.49 USD"}'
# {"status": 0, "status_message": "ok", "message_token": 4912661846655238145}

How do I create a Viber bot auth token?
- Create a Viber bot accountRegister a bot on the Viber Admin Panel (partners.viber.com). The auth token appears on the bot's "edit info" screen for admins.
- Set a webhookViber requires
set_webhookwith a reachable HTTPS URL beforesend_messageworks for most bots; the webhook also delivers thesubscribedevent with the user's Viber ID once someone adds the bot. - Get a subscribed receiver IDHave the test account add the bot in Viber and send it any message; the webhook callback's
sender.idis thereceivervalue every latersend_messagecall needs. - Send a test message
curl -H \"X-Viber-Auth-Token: <token>\" -H \"Content-Type: application/json\" -d '{\"receiver\":\"<id>\",\"type\":\"text\",\"sender\":{\"name\":\"test\"},\"text\":\"hello\"}' https://chatapi.viber.com/pa/send_message; the response should show\"status\": 0.
Environment file and a cron entry for a 15-minute check (flock -n prevents overlapping runs)
# .env (keep it out of git: the auth token can message every subscribed user of this bot)
export SELLERMAGNET_API_KEY="your-key-here"
export VIBER_AUTH_TOKEN="445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9" # bot's "edit info" screen
export VIBER_RECEIVER_ID="01234567890A=" # from the webhook's subscribed/message callback
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_viber_alert.py >> alert.log 2>&1
Viber's own REST Bot API documentation (developers.viber.com, checked 2026-11-27) describes the contract the script relies on: almost every response is HTTP 200, the real outcome is the numeric status field (0 for success) with a status_message string, a successful send also carries a message_token for later delivered/seen callbacks, and the receiver must already be subscribed to the bot or the send fails with a documented status (5 or 6). There is a documented 30 KB cap on a text message; a 3 (badData) or 4 (missingData) are real input problems and must not be retried unchanged, while 12 (tooManyRequests) gets exactly one retry and the billing statuses (23, 24) are logged and left for the account to be funded or the month to roll over.
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; Viber itself is free for this volume for a standard bot, unrelated to SellerMagnet credits (a billable bot only matters once payment messages are involved). With a 2-check confirmation the worst-case delay before Viber 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
Does Viber use HTTP status codes for errors, like Pushbullet?
No. developers.viber.com's REST Bot API (checked 2026-11-27) answers almost every call with HTTP 200, success or failure alike; the real result is the JSON status field (0 means ok) plus a status_message string. The script checks status, never resp.status_code, which is the opposite convention from Pushbullet, Gotify or LINE in this series.
Why does the receiver have to subscribe first?
Viber bots cannot message an arbitrary user ID. The docs define receiverNotSubscribed (status 6) for a user who has not opted into the bot and receiverNotRegistered (status 5) for an ID with no Viber account at all - two separate, documented reasons a send can never reach anyone, unlike every other channel in this series where a bad receiver mostly means a typo in a token or chat ID.
Does a client-set id make a retried send safe, the way Pushbullet's guid does?
No. Viber's send_message takes no caller-chosen de-dupe key; tracking_data is an opaque string Viber echoes back on the user's reply, not an idempotency token. A retried send after a timeout can create a second message, so the script only retries the one status Viber documents as transient (12, tooManyRequests) and leaves every other failure, including a timeout, for the next scheduled run instead of retrying blind.
What happens on a tooManyRequests (status 12)?
developers.viber.com lists status 12 by name but publishes no numeric Retry-After the way Telegram's retry_after or Zulip's retry-after field do. The script retries exactly once after a fixed 5-second backoff and gives up cleanly on a second 12.
How is noBalance different from freeMessagesExceeded?
Both are billing stops with their own status codes (24 and 23): freeMessagesExceeded means the bot's free-tier monthly message cap was reached, noBalance means a billable bot has no funds left for a paid send. Neither is retried; both leave the confirmed change unreported until the account is funded or the month rolls over.
What happens when my SellerMagnet credits run out?
The API answers 401 or 403, which is never billed. The script stops instead of calling the remaining ASINs and does not repeat the attempt until a run completes without a 401 or 403.
Bottom line: compare buyBox.sellerId with your own seller ID, keep a streak per ASIN, and send one Viber POST /pa/send_message call per run - check the JSON status field, never the HTTP status code, since Viber answers 200 either way. 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.