DEV Community

Reseller Ledger
Reseller Ledger

Posted on

Building a simple order-status poller for an SMM panel API (with code)

Building a simple order-status poller for an SMM panel API (with code)

Most reseller tools start the same way. You place an order through a panel API, you get an order id back, and then you need to know when that order leaves Pending. A dashboard is fine when you have four tickets open. It is a poor system once you have a queue, a client waiting on a screenshot, or a script that places twenty orders at once.

This post builds a small poller you can run on your own machine. It talks to a generic panel API v2 endpoint: one URL that accepts action=add, action=status and action=services as form fields. That request shape is used by a large number of reseller panels, so the same client works against a local mock today and a live endpoint later. The code uses only the Python standard library. A mock server in the same folder walks an order through Pending, In progress and Completed in a few seconds, which is enough to practise the loop without waiting on a real delivery.

There are three small files, mock_panel.py, panel_client.py and poller.py, and all of their code is below, with the reasons for each choice.

Eyeglasses resting in front of a monitor, with code reflected in the lenses

What the API actually gives you

A typical panel API v2 is not a resourceful REST tree. It is a single POST, usually to a path such as /api/v2, with application/x-www-form-urlencoded fields. The three calls a poller needs look like this:

POST /api/v2
Content-Type: application/x-www-form-urlencoded

key=YOUR_API_KEY&action=services
Enter fullscreen mode Exit fullscreen mode
POST /api/v2
Content-Type: application/x-www-form-urlencoded

key=YOUR_API_KEY&action=add&service=101&link=https://example.com/p/demo&quantity=50
Enter fullscreen mode Exit fullscreen mode
POST /api/v2
Content-Type: application/x-www-form-urlencoded

key=YOUR_API_KEY&action=status&order=1001
Enter fullscreen mode Exit fullscreen mode

A successful add returns {"order": 1001}. A successful status returns a small object with status, start_count and remains. Many panels also accept a batch form, which is the one you should prefer once you are watching more than one id:

key=YOUR_API_KEY&action=status&orders=1001,1002,1003
Enter fullscreen mode Exit fullscreen mode

Two quirks catch people out. First, business errors often arrive as HTTP 200 with {"error": "Incorrect order ID"} in the body, so a client that only checks the status code will miss them. Second, status labels are not a formal enum. You will see In progress, InProgress, Partial, Canceled and Cancelled in the wild. The poller below normalises those strings before it decides whether to keep watching.

Design goals

A useful poller is boring in the right ways:

  • It treats Pending, In progress, Processing and Awaiting as open, and Completed, Partial, Canceled, Cancelled, Refunded and Error as finished.
  • It batches status lookups so ten open orders become one HTTP call, not ten.
  • It writes the last status to a JSON state file after every successful round, so a restart does not forget work that is still open.
  • It backs off when the endpoint is slow or returns HTTP 429, and it does not use the mock's short delays against a live panel.
  • It never retries action=add just because a status call failed. Placement and polling are different jobs. The follow-up post in this series covers retries and idempotency for placement.

A mock you can run locally

The mock is a short http.server that implements the three actions and a predictable lifecycle. Orders begin as Pending for a couple of seconds, move to In progress, then finish as Completed. Ids that end in 7 finish as Partial, so you can see that path too. After a handful of requests in a short window it returns HTTP 429 with a Retry-After header, which the poller already knows how to wait out.

def _snapshot(self, order: dict, now: float) -> dict:
    age = now - order["created_at"]
    quantity = order["quantity"]
    if age < 2:
        status, remains = "Pending", quantity
    elif age < 5:
        status, remains = "In progress", max(0, quantity // 2)
    else:
        if str(order["id"]).endswith("7"):
            status, remains = "Partial", max(1, quantity // 5)
        else:
            status, remains = "Completed", 0
    return {
        "status": status,
        "start_count": order["start_count"],
        "remains": str(remains),
    }
Enter fullscreen mode Exit fullscreen mode

Start it in one terminal:

python3 mock_panel.py
# Mock panel API v2 at http://127.0.0.1:18765/api/v2
# Demo key: demo-key
Enter fullscreen mode Exit fullscreen mode

The port is 18765 only because that is a quiet number on many machines. Pass --port if you already have something on it. The demo key is demo-key. There is no live balance and no outbound call.

A small client

The client wraps those form posts, turns body-level error keys into exceptions, and maps HTTP 429 onto a RateLimitError that carries Retry-After when the header is present. Timeouts and 5xx responses become TemporaryError, which the poller treats as "wait, then try the status call again."

@dataclass
class PanelClient:
    api_url: str
    api_key: str
    timeout: float = 30.0
    user_agent: str = "panel-poller/1.0"

    @classmethod
    def from_env(cls) -> "PanelClient":
        url = os.environ.get("PANEL_API_URL", "http://127.0.0.1:18765/api/v2")
        key = os.environ.get("PANEL_API_KEY", "demo-key")
        return cls(api_url=url, api_key=key)

    def request(self, **params: Any) -> Any:
        payload = {"key": self.api_key, **params}
        data = urllib.parse.urlencode(payload, doseq=True).encode("utf-8")
        req = urllib.request.Request(
            self.api_url,
            data=data,
            method="POST",
            headers={
                "Content-Type": "application/x-www-form-urlencoded",
                "User-Agent": self.user_agent,
                "Accept": "application/json",
            },
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                body = resp.read().decode("utf-8", errors="replace")
                return json.loads(body)
        except urllib.error.HTTPError as exc:
            body = exc.read().decode("utf-8", errors="replace")
            if exc.code == 429:
                raw = exc.headers.get("Retry-After")
                retry_after = float(raw) if raw else None
                raise RateLimitError(retry_after, body) from exc
            raise TemporaryError(f"HTTP {exc.code}: {body}") from exc
        except (TimeoutError, urllib.error.URLError) as exc:
            raise TemporaryError(str(exc)) from exc
Enter fullscreen mode Exit fullscreen mode

services(), add_order(), status() and statuses() all go through a thin _call() helper that raises PanelError when the JSON body contains error. Keep the API key in PANEL_API_KEY. Do not put it in the source file, in a screenshot, or in a repository.

The poll loop

The interesting part is not the HTTP. It is the bookkeeping. Open order ids live in a JSON file. Each round, the poller asks for all of them in one batch, prints status, remains and start_count, writes the file, and sleeps. If a label is unrecognised, the poller keeps watching. A typo in a status string should not look like success.

OPEN_STATUSES = {
    "pending", "in progress", "processing", "awaiting", "inprogress",
}
TERMINAL_STATUSES = {
    "completed", "partial", "canceled", "cancelled",
    "refunded", "error", "failed",
}

def normalize_status(value: str | None) -> str:
    return (value or "").strip().lower().replace("_", " ").replace("-", " ")

def is_open(status: str | None) -> bool:
    text = normalize_status(status)
    if text in OPEN_STATUSES:
        return True
    if text in TERMINAL_STATUSES:
        return False
    return bool(text)
Enter fullscreen mode Exit fullscreen mode

On a rate limit, honour Retry-After when it is present. On any other temporary error, sleep a random time in [0, min(cap, base * 2**attempt)] — full jitter, not a fixed staircase that makes every crashed worker retry in lockstep. Successful rounds do not use that backoff. They wait for a base interval plus a little noise. There is no benefit in asking a panel for a new status every two seconds when delivery often takes minutes.

def next_delay(attempt: int, base: float, cap: float) -> float:
    raw = min(cap, base * (2 ** max(0, attempt)))
    return random.uniform(0, raw)
Enter fullscreen mode Exit fullscreen mode

The state file is replaced atomically (write a .tmp, then rename) so a crash mid-write does not leave you with half a document. Each record keeps the last status, remains, start_count and a Unix timestamp. That is already enough to answer "when did this leave Pending?" without scraping a dashboard later.

A developer at a desk with two laptops and a monitor, looking at a document

Running it

In a second terminal, from the folder with the three files:

# Place one demo order and watch it through to a terminal state.
python3 poller.py \
  --place 101 \
  --link https://example.com/p/demo \
  --qty 50 \
  --interval 1 \
  --state /tmp/panel-orders.json
Enter fullscreen mode Exit fullscreen mode

You should see a few Pending lines, then In progress with a lower remains, then Completed. To watch ids you already have — including one that will finish as Partial if you placed it on the mock and the id ends in 7:

python3 poller.py --watch 1001,1007 --state /tmp/panel-orders.json
Enter fullscreen mode Exit fullscreen mode

Against the mock, a one-second interval is fine because the lifecycle is only a few seconds long. Against a live panel, start around 30 seconds and cap error backoff around 60 to 90 seconds. If you poll tighter than that on a shared endpoint, you will meet the rate limiter, and you will not learn anything earlier that you could not learn half a minute later.

How to read start_count, remains and Partial

start_count is the figure the panel recorded when it began work, often a public follower or view count on the target. Save it. If a client later asks "did this even start?", that number is the first thing you look at, and it is awkward to reconstruct after the fact.

remains is how much of the quantity is still outstanding. It should fall while the status is In progress. If it never moves, and the status never moves either, you are not looking at a slow delivery. You are looking at a stuck order, and that is a support ticket, not a reason to tighten the poll interval.

Partial is terminal in this poller, and it should be. The panel has stopped, and part of the quantity was not delivered. Your next step is whatever the panel's refill or support process is, not another status call every ten seconds. Do not place a second order on the same link until you know whether a refill will run. Two orders on one link at once are a common way to void a refill window.

Canceled and Cancelled are both treated as finished. So is Refunded. If your own shop's customer should be told, that notification is a separate path. The poller's job is to notice the terminal state and stop spending requests.

What not to do

Do not put action=add inside the poll loop "just to be safe." If a placement already succeeded and the response was lost, a retry will create a second order. Keep a local map of client ticket to order id, and treat placement as a one-shot with its own retry rules. That is the subject of the next post.

Do not poll completed ids forever. Once an order is terminal, drop it from the open list. A weekly report can read the state file; it does not need to ask the panel again.

Do not share one API key across a debug script, a production worker and a colleague's laptop without a plan to rotate it. If the key leaks, every order on the account can be placed or queried with it. Most panels let you regenerate the key; do that if it has ever sat in a chat log.

Do not assume the mock's timing is a service-level target. It is a teaching aid. Live start times vary by service, and a panel that delivers carefully in a few hours is often more useful than one that marks Completed quickly and then drops.

Pointing the same poller at a live endpoint

Once the loop behaves against the mock, set PANEL_API_URL to the real /api/v2 URL and PANEL_API_KEY to a key from the panel's dashboard. Place a low-quantity order on a test service and a link you control. A public smm reseller panel that documents this same action=add / action=status request shape is enough to practise against. Keep the interval at half a minute or more, and read the panel's own notes on rate limits if they are published.

If the live panel does not support orders= batch status, the client's statuses() path already falls back to a single order= call when you pass one id. For several ids you can loop in your own code, with the token bucket from the next post sitting in front of each call so a naive loop does not become a burst.

The poller will not make a weak service good. It will make a good integration quieter: fewer missed Partial states, fewer "is this still pending?" messages, and a file you can read when a client asks what happened last Tuesday.

Top comments (0)