Update to work with Python 3 (only)

Also bump the version to 0.2
This commit is contained in:
Mikkel Munch Mortensen 2021-09-02 17:33:39 +02:00
parent 51a67b3451
commit ba182c025c
Signed by: decibyte
GPG key ID: 261C257C74AA764B
5 changed files with 136 additions and 116 deletions

View file

@ -1,5 +1,5 @@
THIS IS THIS IS
A Python wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>. A Python 3 wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>.
THIS IS NOT THIS IS NOT
Some sort of magic, free SMS gateway. Some sort of magic, free SMS gateway.

View file

@ -0,0 +1,3 @@
"""The cpsms package."""
from .cpsms import Gateway

View file

@ -1,8 +1,5 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-'
""" """
Copyright 2010, 2011 Mikkel Munch Mortensen <3xm@detfalskested.dk>. Copyright 2010-2021 Mikkel Munch Mortensen <3xm@detfalskested.dk>.
This file is part of SMS Gateway. This file is part of SMS Gateway.
@ -20,89 +17,105 @@ You should have received a copy of the GNU General Public License
along with SMS Gateway. If not, see <http://www.gnu.org/licenses/>. along with SMS Gateway. If not, see <http://www.gnu.org/licenses/>.
""" """
import urllib, getopt import getopt
from urllib.parse import urlencode
from urllib.request import urlopen
from typing import Any, Tuple
class Gateway():
'''
A Python wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>.
Please look at the README for further description. class Gateway:
''' """
default_options = { A Python wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>.
'recipients' : [],
'message' : '', # Should be a unicode string.
'callback_url' : '',
'timestamp' : '', # For delaying messages. Format: YYYYMMDDHHMM.
'utf8' : 1,
'flash' : 0,
'group' : 0,
'gateway_base_url' : 'https://www.cpsms.dk/sms/?'
}
options = {}
def __init__(self, username, password, sender_name, options = None): Please look at the README for further description.
''' """
Initialize SMS gateway, with some options.
'''
self.options = self.default_options
if options != None:
self.options.update(options)
self.options['username'] = username options: dict[str, Any] = {}
self.options['password'] = password
self.options['from'] = sender_name
def add_recipient(self, number): @property
''' def default_options(self) -> dict[str, Any]:
Add a number to the list of recipients. return {
''' "recipients": [],
self.options['recipients'].append(number) "message": "",
"callback_url": "",
"timestamp": "", # For delaying messages. Format: YYYYMMDDHHMM.
"utf8": True,
"flash": False,
"group": False,
"gateway_base_url": "https://www.cpsms.dk/sms/?",
}
def send(self, message = None): def __init__(
''' self,
Send the message specified in self.options to all recipients. Optionally, override the message to be sent. username: str,
''' password: str,
# Decide what to send sender_name: str,
if message == None: options: dict[str, Any] = None,
message = self.options['message'] ) -> None:
"""Initialize SMS gateway, with some options."""
self.options = self.default_options
if options is not None:
self.options.update(options)
# Raise error if message is empty. self.options["username"] = username
if len(message) == 0: self.options["password"] = password
raise ValueError('Message empty.') self.options["from"] = sender_name
# Raise error if message is too long. def add_recipient(self, number: str) -> None:
if len(message) > 459: """Add a number to the list of recipients."""
raise ValueError('Message not allowed to be more than 459 characters. Current message is %i characters.' % len(message)) self.options["recipients"].append(number)
# Raise error if recipients is empty. def send(self, message: str = None) -> Tuple[bool, str]:
if len(self.options['recipients']) == 0: """
raise ValueError('No recipients.') Send the message specified in self.options to all recipients.
# Construct gateway URL. Optionally, override the message to be sent.
options = [ """
('username', self.options['username']), # Decide what to send.
('password', self.options['password']), if message is None:
('message', message.encode('utf-8')), message = self.options["message"]
('from', self.options['from']),
('utf8', self.options['utf8']),
('flash', self.options['flash']),
('group', self.options['group']),
('url', self.options['callback_url']),
]
for r in self.options['recipients']: # Raise error if message is empty.
options.append(('recipient[]', r)) if message == "":
raise ValueError("Message empty.")
if self.options['timestamp'] != '': # Raise error if message is too long.
options.append(('timestamp', self.options['timestamp'])) if len(message) > 459:
raise ValueError(
"Message not allowed to be more than 459 characters."
"Current message is %i characters." % len(message)
)
url = self.options['gateway_base_url'] + urllib.urlencode(options) # Raise error if recipients is empty.
if len(self.options["recipients"]) == 0:
raise ValueError("No recipients.")
# Send SMS. # Construct gateway URL.
remote_call = urllib.urlopen(url) options = [
result = remote_call.read() ("username", self.options["username"]),
remote_call.close() ("password", self.options["password"]),
if result.find('<succes>') > -1: ("message", message),
return True, result ("from", self.options["from"]),
else: ("utf8", int(self.options["utf8"])),
return False, result ("flash", int(self.options["flash"])),
("group", int(self.options["group"])),
("url", self.options["callback_url"]),
]
for r in self.options["recipients"]:
options.append(("recipient[]", r))
if self.options["timestamp"] != "":
options.append(("timestamp", self.options["timestamp"]))
url = self.options["gateway_base_url"] + urlencode(options)
print(url)
# Send SMS.
remote_call = urlopen(url)
result = remote_call.read().decode()
remote_call.close()
if result.find("<succes>") > -1:
return True, result
else:
return False, result

View file

@ -1,8 +1,5 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-'
""" """
Copyright 2010, 2011 Mikkel Munch Mortensen <3xm@detfalskested.dk>. Copyright 2010-2021 Mikkel Munch Mortensen <3xm@detfalskested.dk>.
This file is part of SMS Gateway. This file is part of SMS Gateway.
@ -23,13 +20,18 @@ along with SMS Gateway. If not, see <http://www.gnu.org/licenses/>.
import cpsms import cpsms
# The easiest way to send a single message. # The easiest way to send a single message.
gateway1 = cpsms.Gateway('username', 'password', 'SMS Test') gateway1 = cpsms.Gateway("username", "password", "Sender Name")
gateway1.add_recipient('+4512345678') gateway1.add_recipient("+4512345678")
print gateway1.send(u'One way of sending a massage.') print(gateway1.send("One way of sending a massage."))
# The easiest way to send a message to multiple recipients. # The easiest way to send a message to multiple recipients.
gateway2 = cpsms.Gateway('username', 'password', 'SMS Test', { gateway2 = cpsms.Gateway(
'recipients' : ['+4512345678', '+4587654321'], "username",
'message' : u'Another way of sending a message.', "password",
}) "SMS Test",
print gateway2.send() {
"recipients": ["+4512345678", "+4587654321"],
"message": "Another way of sending a message.",
},
)
print(gateway2.send())

View file

@ -2,20 +2,22 @@ from distutils.core import setup
setup( setup(
name='cpsms', name="cpsms",
packages=['cpsms'], packages=["cpsms"],
version='0.1', version="0.2",
author='Mikkel Munch Mortensen', author="Mikkel Munch Mortensen",
author_email='3xm@detfalskested.dk', author_email="3xm@detfalskested.dk",
url='https://github.com/decibyte/cpsms', url="https://github.com/decibyte/cpsms",
description='A Python wrapper around the SMS gateway ' \ description=(
'from CPSMS <https://www.cpsms.dk/>.', "A Python wrapper around the SMS gateway from "
classifiers = [ "CPSMS <https://www.cpsms.dk/>."
'Programming Language :: Python', ),
'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', classifiers=[
'Operating System :: OS Independent', "Programming Language :: Python",
'Development Status :: 4 - Beta', "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
'Intended Audience :: Developers', "Operating System :: OS Independent",
'Topic :: Communications :: Telephony', "Development Status :: 4 - Beta",
] "Intended Audience :: Developers",
"Topic :: Communications :: Telephony",
],
) )