#!/usr/bin/env python3 """SendPier Send API — read how much of your allowance is left. Requirements: Python 3.9 or newer. Standard library only, no packages. Usage: export SENDPIER_API_KEY='sp_live_...' export SENDPIER_DOMAIN='example.com' python3 get_quota.py Check this before a large batch rather than after a 429: once the allowance is spent, every further message is refused with quota_exceeded until the period rolls over or you add credits. """ import json import os import sys import urllib.error import urllib.request API_BASE = "https://api.sendpier.com" def sendpier_get(path, timeout=30): """One GET to the Send API. Returns (status, parsed_body_or_None, raw_text). """ key = os.environ.get("SENDPIER_API_KEY", "") domain = os.environ.get("SENDPIER_DOMAIN", "") if not key or not domain: sys.exit("set SENDPIER_API_KEY and SENDPIER_DOMAIN first") request = urllib.request.Request( API_BASE + path, headers={ "Authorization": "Bearer " + key, "X-Domain-Name": domain, "Accept": "application/json", }, method="GET", ) try: with urllib.request.urlopen(request, timeout=timeout) as response: status = response.status raw = response.read().decode("utf-8") except urllib.error.HTTPError as error: status = error.code raw = error.read().decode("utf-8", "replace") except urllib.error.URLError as error: sys.exit("connection failed: {}".format(error.reason)) try: parsed = json.loads(raw) except ValueError: parsed = None return status, parsed, raw def main(): status, body, raw = sendpier_get("/v1/quota") print(raw) if status != 200: sys.exit("request failed with HTTP {}".format(status)) quota = body or {} print( "{}: {} of {} used, {} left this period".format( quota.get("domain"), quota.get("used_this_month"), quota.get("monthly_limit"), quota.get("remaining"), ), file=sys.stderr, ) # A pause before you run out is cheaper than a batch that dies halfway. if (quota.get("remaining") or 0) < 100: print("warning: fewer than 100 messages left", file=sys.stderr) if __name__ == "__main__": main()