From b2b4b097bbdcd9814a2d9c07333d3508aa49ef01 Mon Sep 17 00:00:00 2001 From: Klaus-Uwe Mitterer Date: Sat, 24 Oct 2020 11:12:12 +0200 Subject: [PATCH] Initial version --- __init__.py | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 __init__.py diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..6398f69 --- /dev/null +++ b/__init__.py @@ -0,0 +1,51 @@ +import urllib.request +import urllib.parse +import json + +URL = "https://kumisms.com/api/v1/" + +class InvalidCredentials(Exception): + pass + +class SendFailed(Exception): + pass + +class RateUnavailable(Exception): + pass + +class KumiSMS: + def __init__(self, key, endpoint=URL): + self.key = key + self.endpoint = endpoint + self.check() + + def send(self, recipient, text): + endpoint = urllib.parse.urljoin(self.endpoint, "send/") + content = self._request(endpoint, {"recipient": recipient, "text": text}) + if content["status"] == "error": + raise SendFailed(content["error_message"]) + return True + + def balance(self): + endpoint = urllib.parse.urljoin(self.endpoint, "balance/") + return self._request(endpoint)["balance"] + + def rate(self, recipient, text=""): + endpoint = urllib.parse.urljoin(self.endpoint, "rate/") + content = self._request(endpoint, {"recipient": recipient, "text": text}) + if content["status"] == "error": + raise RateUnavailable(content["error_message"]) + return content["rate"] + + def check(self): + return bool(self.balance()) + + def _request(self, url, data=None): + data = {"key": self.key}.update(data) + body = json.dumps(data) + request = urllib.request.urlopen(url, body) + content = json.loads(request.read()) + if content["status"] == "error": + if content["error_message"] == "Incorrect API key": + raise InvalidCredentials(content["error_message"]) + return content