Send SMS with Python

One function on top of the requests library covers every call of the API. Python 3.8 or newer; install requests with pip install requests.

The helper

# budgetsms.py
import os
import requests

BASE = "https://api.budgetsms.net/"
AUTH = {
    "username": os.environ["BUDGETSMS_USERNAME"],
    "userid": os.environ["BUDGETSMS_USERID"],
    "handle": os.environ["BUDGETSMS_HANDLE"],
}


class BudgetSmsError(Exception):
    """Raised when the API answers ERR <code>; the code is in .code (see the error code list)."""

    def __init__(self, code: str):
        super().__init__(f"BudgetSMS error {code}")
        self.code = code


def call(endpoint: str, **params) -> str:
    """Calls sendsms, testsms, checkcredit, np, hlr or checksms and returns the text after 'OK '."""
    response = requests.get(BASE + endpoint + "/", params={**AUTH, **params}, timeout=20)
    response.raise_for_status()
    status, _, rest = response.text.strip().partition(" ")
    if status != "OK":
        raise BudgetSmsError(rest)
    return rest


def pricing() -> dict:
    """Your price per SMS part for every operator, keyed by operator id."""
    response = requests.get(BASE + "getpricing/", params=AUTH, timeout=20)
    response.raise_for_status()
    return response.json()

Send an SMS

from is a reserved word in Python, so pass the sender id through a dictionary:

from budgetsms import call, BudgetSmsError

try:
    result = call("sendsms", **{"from": "BudgetSMS"}, to="31612345678", msg="Hello from BudgetSMS")
    sms_id = int(result.split()[0])      # keep it for the delivery report
    print("sent, message id", sms_id)
except BudgetSmsError as e:
    print("not sent:", e.code)

Use "testsms" while developing: same parameters and answer format, but it is a simulator: no SMS is sent and nothing is charged, the message id and price in the answer are random, and about one in five calls returns a random ERR 2xxx so your error handling gets exercised (the destination number is not checked). Add price=1, mccmnc=1 or credit=1 to get the price and number of parts, the receiver's network or your remaining credit after the message id.

Credit, number lookup and delivery status

credit = float(call("checkcredit"))                       # 123.455

mcc, mnc, price = call("np", to="31612345678").split()   # "204", "08", "0.0640": current network and your price

status = int(call("checksms", smsid=64354593))           # 1 = delivered; see the DLR status list

for operator_id, row in pricing().items():
    print(row["countryname"], row["operatorname"], row["price"])

Receive delivery reports (Push DLR) with Flask

Enter the URL of this route in the control panel under Push DLR; we call it with GET on every status update.

from flask import Flask, request

app = Flask(__name__)


@app.get("/dlr")
def dlr():
    sms_id = int(request.args.get("id", 0))        # message id from the sendsms response
    status = int(request.args.get("status", -1))   # 1 = delivered, 2 and 3 = failed; full list: DLR status
    date = int(request.args.get("date", 0))        # unix timestamp
    # update your own records here
    return "OK", 200