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():
''' class Gateway:
"""
A Python wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>. A Python wrapper around the SMS gateway from CPSMS <https://www.cpsms.dk/>.
Please look at the README for further description. Please look at the README for further description.
''' """
default_options = {
'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): options: dict[str, Any] = {}
'''
Initialize SMS gateway, with some options. @property
''' def default_options(self) -> dict[str, Any]:
return {
"recipients": [],
"message": "",
"callback_url": "",
"timestamp": "", # For delaying messages. Format: YYYYMMDDHHMM.
"utf8": True,
"flash": False,
"group": False,
"gateway_base_url": "https://www.cpsms.dk/sms/?",
}
def __init__(
self,
username: str,
password: str,
sender_name: str,
options: dict[str, Any] = None,
) -> None:
"""Initialize SMS gateway, with some options."""
self.options = self.default_options self.options = self.default_options
if options != None: if options is not None:
self.options.update(options) self.options.update(options)
self.options['username'] = username self.options["username"] = username
self.options['password'] = password self.options["password"] = password
self.options['from'] = sender_name self.options["from"] = sender_name
def add_recipient(self, number): def add_recipient(self, number: str) -> None:
''' """Add a number to the list of recipients."""
Add a number to the list of recipients. self.options["recipients"].append(number)
'''
self.options['recipients'].append(number)
def send(self, message = None): def send(self, message: str = None) -> Tuple[bool, str]:
''' """
Send the message specified in self.options to all recipients. Optionally, override the message to be sent. Send the message specified in self.options to all recipients.
'''
# Decide what to send Optionally, override the message to be sent.
if message == None: """
message = self.options['message'] # Decide what to send.
if message is None:
message = self.options["message"]
# Raise error if message is empty. # Raise error if message is empty.
if len(message) == 0: if message == "":
raise ValueError('Message empty.') raise ValueError("Message empty.")
# Raise error if message is too long. # Raise error if message is too long.
if len(message) > 459: if len(message) > 459:
raise ValueError('Message not allowed to be more than 459 characters. Current message is %i characters.' % len(message)) raise ValueError(
"Message not allowed to be more than 459 characters."
"Current message is %i characters." % len(message)
)
# Raise error if recipients is empty. # Raise error if recipients is empty.
if len(self.options['recipients']) == 0: if len(self.options["recipients"]) == 0:
raise ValueError('No recipients.') raise ValueError("No recipients.")
# Construct gateway URL. # Construct gateway URL.
options = [ options = [
('username', self.options['username']), ("username", self.options["username"]),
('password', self.options['password']), ("password", self.options["password"]),
('message', message.encode('utf-8')), ("message", message),
('from', self.options['from']), ("from", self.options["from"]),
('utf8', self.options['utf8']), ("utf8", int(self.options["utf8"])),
('flash', self.options['flash']), ("flash", int(self.options["flash"])),
('group', self.options['group']), ("group", int(self.options["group"])),
('url', self.options['callback_url']), ("url", self.options["callback_url"]),
] ]
for r in self.options['recipients']: for r in self.options["recipients"]:
options.append(('recipient[]', r)) options.append(("recipient[]", r))
if self.options['timestamp'] != '': if self.options["timestamp"] != "":
options.append(('timestamp', self.options['timestamp'])) options.append(("timestamp", self.options["timestamp"]))
url = self.options['gateway_base_url'] + urllib.urlencode(options) url = self.options["gateway_base_url"] + urlencode(options)
print(url)
# Send SMS. # Send SMS.
remote_call = urllib.urlopen(url) remote_call = urlopen(url)
result = remote_call.read() result = remote_call.read().decode()
remote_call.close() remote_call.close()
if result.find('<succes>') > -1: if result.find("<succes>") > -1:
return True, result return True, result
else: else:
return False, result 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",
],
) )