# Python client: receive an SMS code from a test or script

> One file, one dependency (requests), works on Python 3.9 and newer. It orders a number, polls getStatus at a safe rate, and closes the order whatever happens, so a crashed test never leaves money on hold.

Source: https://otpwatch.com/python
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## Install

```env title=".env.example"
# handler_api reference: https://otpwatch.com/python
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```bash title="shell"
# handler_api reference: https://otpwatch.com/python
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
python -m pip install requests
export SMS_API_KEY=...        # PowerShell: $env:SMS_API_KEY="..."
```

The key comes from the API section of the SimAggregator dashboard. It is shown once when issued; keep it in your secrets store, not in the repository.

## The client

```python title="otp_client.py"
# handler_api reference: https://otpwatch.com/python
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
"""Minimal handler_api.php client. Python 3.9+, pip install requests."""
import os
import random
import time
from typing import Optional

import requests

BASE_URL = os.getenv("SMS_API_BASE_URL", "https://sim-aggregator.org/stubs/handler_api.php")
WAITING = ("STATUS_WAIT_CODE", "STATUS_WAIT_RETRY")


class SmsApiError(Exception):
    """A refusal from the API, e.g. NO_NUMBERS or WRONG_MAX_PRICE:1.5."""

    def __init__(self, reply: str):
        super().__init__(reply)
        self.reply = reply
        self.code = reply.split(":", 1)[0]


class SmsClient:
    def __init__(self, api_key: str, base_url: str = BASE_URL, session: Optional[requests.Session] = None):
        self.api_key = api_key
        self.base_url = base_url
        self.session = session or requests.Session()

    def call(self, action: str, **params) -> str:
        query = {"action": action, "api_key": self.api_key}
        query.update({k: v for k, v in params.items() if v is not None})
        for attempt in range(6):
            r = self.session.get(self.base_url, params=query, timeout=30)
            r.raise_for_status()
            text = r.text.strip()
            if text != "REQUEST_LIMIT":
                return text
            time.sleep(min(2 ** attempt, 30) + random.random() / 2)  # back off with jitter
        raise SmsApiError("REQUEST_LIMIT")

    def balance(self) -> float:
        reply = self.call("getBalance")
        if not reply.startswith("ACCESS_BALANCE:"):
            raise SmsApiError(reply)
        return float(reply.split(":", 1)[1])

    def order(self, service: str, country: int, max_price: Optional[float] = None,
              duration: Optional[str] = None) -> "Activation":
        reply = self.call("getNumber", service=service, country=country, maxPrice=max_price, duration=duration)
        if not reply.startswith("ACCESS_NUMBER:"):
            raise SmsApiError(reply)
        _, activation_id, phone = reply.split(":", 2)
        return Activation(self, activation_id, phone)

    def status(self, activation_id: str) -> str:
        return self.call("getStatus", id=activation_id)

    def set_status(self, activation_id: str, status: int) -> str:
        return self.call("setStatus", id=activation_id, status=status)


class Activation:
    """One ordered number. Use it as a context manager so it is always closed."""

    def __init__(self, client: SmsClient, activation_id: str, phone: str):
        self.client, self.id, self.phone = client, activation_id, phone
        self.code: Optional[str] = None

    @property
    def e164(self) -> str:
        return "+" + self.phone

    def wait_code(self, timeout: float = 600, interval: float = 3) -> str:
        deadline = time.monotonic() + timeout
        while time.monotonic() < deadline:
            reply = self.client.status(self.id)
            if reply.startswith("STATUS_OK:"):
                self.code = reply.split(":", 1)[1]
                return self.code
            if not reply.startswith(WAITING):
                raise SmsApiError(reply)  # STATUS_CANCEL, NO_ACTIVATION, BAD_KEY...
            time.sleep(interval)
        raise TimeoutError(f"no SMS for activation {self.id} within {timeout}s")

    def another_code(self) -> None:
        self.client.set_status(self.id, 3)
        self.code = None

    # tries and pause are our choice, not an API rule: the docs only say
    # "too early to cancel, repeat the request later".
    def cancel(self, tries: int = 9, pause: float = 10) -> str:
        for attempt in range(tries):
            reply = self.client.set_status(self.id, 8)
            if reply != "EARLY_CANCEL_DENIED":
                return reply
            if attempt < tries - 1:
                time.sleep(pause)  # too early to cancel: repeat later
        raise RuntimeError(f"cancel {self.id}: still EARLY_CANCEL_DENIED after {tries} tries; cancel it later")

    def close(self) -> None:
        if self.code is not None:
            self.client.set_status(self.id, 6)  # finished, frees the slot
        else:
            self.cancel()                        # no code: money back to the balance

    def __enter__(self) -> "Activation":
        return self

    def __exit__(self, *exc) -> bool:
        self.close()
        return False
```

## Use it

```python title="example.py"
# handler_api reference: https://otpwatch.com/python
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
import os
from otp_client import SmsClient, SmsApiError

client = SmsClient(os.environ["SMS_API_KEY"])
print("balance:", client.balance())

try:
    with client.order("tg", 16, max_price=2.0) as act:   # Telegram, United Kingdom
        print("number:", act.e164)
        # ... make your app (or the service under test) send the SMS to act.e164 ...
        print("code:", act.wait_code(timeout=300))
except SmsApiError as err:
    if err.code == "WRONG_MAX_PRICE":
        print("price is above the cap, lowest now:", err.reply.split(":", 1)[1])
    elif err.code in ("NO_NUMBERS", "NO_BALANCE", "CHANNEL_LIMIT"):
        print("cannot order right now:", err.code)
    else:
        raise
```

The `with` block is the important part. If anything inside raises, `__exit__` cancels the order, repeating the cancel while the API answers `EARLY_CANCEL_DENIED` (too early, repeat later), so the hold returns to your balance and the slot is freed. If the cancel is still refused after the last try, it raises with the activation id. If the code arrived, it sends `setStatus` 6 instead.

## Polling inside the rate limit

The key allows 600 requests a minute. One activation polled every 3 seconds costs 20 of them. If you run many activations in parallel from one process, share one `SmsClient` and space the polls; with threads, size the pool so that `threads × 60 / interval` stays well under 600, and leave a fifth for orders and cancellations. `REQUEST_LIMIT` is already retried with backoff inside `call`.

## Async code

The same shape works with `httpx.AsyncClient`: make `call` an `async def`, replace `time.sleep` with `await asyncio.sleep`, and turn `Activation` into an async context manager with `__aenter__` and `__aexit__`. Keep one client per event loop.

## Unit tests without buying anything

The client takes a `session`, so tests can script the replies. No network, no money.

```python title="test_otp_client.py"
# handler_api reference: https://otpwatch.com/python
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
from otp_client import SmsClient


class FakeResponse:
    def __init__(self, text):
        self.text = text

    def raise_for_status(self):
        pass


class FakeSession:
    def __init__(self, replies):
        self.replies, self.calls = list(replies), []

    def get(self, url, params, timeout):
        self.calls.append(params)
        return FakeResponse(self.replies.pop(0))


def test_happy_path():
    s = FakeSession(["ACCESS_NUMBER:77:447700900123", "STATUS_WAIT_CODE", "STATUS_OK:004821", "ACCESS_ACTIVATION"])
    client = SmsClient("test", session=s)
    with client.order("tg", 16) as act:
        assert act.wait_code(interval=0) == "004821"   # leading zeros survive
    assert s.calls[-1]["status"] == 6


def test_cancel_when_test_fails():
    s = FakeSession(["ACCESS_NUMBER:78:447700900124", "ACCESS_CANCEL"])
    client = SmsClient("test", session=s)
    try:
        with client.order("tg", 16):
            raise RuntimeError("form did not load")
    except RuntimeError:
        pass
    assert s.calls[-1]["status"] == 8
```

## Notes

- Keep codes as strings. `int("004821")` silently becomes `4821`.
- `max_price` is in USD. If the pair costs more, the order is not placed and you get `WRONG_MAX_PRICE:<lowest price>`; see [price control](https://otpwatch.com/price-control.md).
- For repeat logins on the same number over several days, pass `duration="d3"` (or `d1`, `d7`): [renting a number over the API](https://otpwatch.com/rent-number-api.md).
- Using pytest and Selenium? The [Selenium page](https://otpwatch.com/selenium-otp-testing.md) wraps this client in a fixture.
