expephalon-demomodule/playsms/models.py

59 lines
1.7 KiB
Python
Raw Normal View History

from django.db.models import Model, CharField, BooleanField
from core.classes.sms import BaseSMSProvider, SMSNotSent
from urllib.parse import quote_plus
from urllib.request import urlopen
from typing import Union
import json
# Create your models here.
class PlaySMSServer(Model, BaseSMSProvider):
name = CharField(max_length=255, unique=True)
logo = CharField(max_length=255)
https = BooleanField(default=True)
host = CharField(max_length=255)
username = CharField(max_length=255)
token = CharField(max_length=255)
@property
def is_active(self):
return True
@property
def get_name(self):
return self.name
@staticmethod
def getError(status):
if status["error_string"]:
return status["error_string"]
try:
if int(status["data"][0]["error"]):
return int(status["data"][0]["error"])
finally:
return
def sendSMS(self, recipients: Union[str, list], message: str):
'''Send an SMS message to one or more recipients
:param recipients: Recipient phone number as a string, or a list of multiple phone number strings
:param message: Message to be sent as a string
'''
if isinstance(recipients, list):
recipients = ",".join(recipients)
url = 'http%s://%s/index.php?app=ws&u=%s&h=%s&op=pv&to=%s&msg=%s' % ("s" if self.https else "", self.host, self.username, self.token, recipients, quote_plus(message))
response = urlopen(url)
status = json.loads(response.read().decode())
error = PlaySMSServer.getError(status)
if error:
raise SMSNotSent(f'An error occurred trying to send the SMS: {error}')