smstrade-0.2.4/0000755000175000017500000000000012343700340012675 5ustar janjan00000000000000smstrade-0.2.4/setup.py0000644000175000017500000000427312343677664014443 0ustar janjan00000000000000# -*- python -*- # -*- coding: utf-8 -*- # # Copyright (C) 2014 Jan Dittberner from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand import sys class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) long_description = "" with open('README.rst', 'r') as README: long_description += README.read() long_description += """ License ======= """ with open('LICENSE', 'r') as LICENSE: long_description += LICENSE.read() long_description += """ Changes ======= """ with open('ChangeLog.rst') as CHANGES: long_description += CHANGES.read() setup( name="smstrade", url="https://gitorious.org/python-smstrade", description=( "a Python library and command line tool to send SMS via the smstrade" " service."), long_description=long_description, requires=['requests', 'appdirs'], author="Jan Dittberner", author_email="jan@dittberner.info", packages=find_packages(exclude=['tests']), setup_requires=['vcversioner'], license="MIT", vcversioner={ 'version_module_paths': ['smstrade/_version.py'], }, entry_points={ 'console_scripts': [ 'smstrade_send = smstrade:send_sms', 'smstrade_balance = smstrade:account_balance', ], }, tests_require=['pytest', 'httpretty'], cmdclass = {'test': PyTest}, classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Topic :: Communications', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Utilities', ], ) smstrade-0.2.4/examples/0000755000175000017500000000000012343700340014513 5ustar janjan00000000000000smstrade-0.2.4/examples/smstrade.ini0000644000175000017500000000164612301414235017044 0ustar janjan00000000000000[smstrade] # enable the following line to really send SMS #debug = False # get your key from https://login.smstrade.de/index.php?gateway key = TheKeyFromSMSTrade # your sender identifier (only used for gold and direct routes) #from = +491701234567 from = YOURID # set the route to one of basic, gold, direct. Default is basic #route = basic # enable return of message ids. Default is False #enable-message-id = True # enable return of costs. Default is False #enable-cost = True # enable return of message count. Default is False #enable-count = True # enable delivery reports. Default is False #enable-delivery-reports = True # enable response (only for route basic). Default is False #enable-response = True # enable longer SMS built of multiple messages. Default is False #enable-concat = True # define a charset for encoding messages and sender identifier (UTF-8, # ISO-8859-1 or ISO-8859-15). Default is ASCII #charset = UTF-8 smstrade-0.2.4/setup.cfg0000644000175000017500000000013012343700340014510 0ustar janjan00000000000000[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 smstrade-0.2.4/smstrade.egg-info/0000755000175000017500000000000012343700340016211 5ustar janjan00000000000000smstrade-0.2.4/smstrade.egg-info/dependency_links.txt0000644000175000017500000000000112343700340022257 0ustar janjan00000000000000 smstrade-0.2.4/smstrade.egg-info/top_level.txt0000644000175000017500000000001112343700340020733 0ustar janjan00000000000000smstrade smstrade-0.2.4/smstrade.egg-info/SOURCES.txt0000644000175000017500000000052712343700340020101 0ustar janjan00000000000000ChangeLog.rst LICENSE MANIFEST.in README.rst setup.cfg setup.py version.txt examples/smstrade.ini smstrade/__init__.py smstrade/_version.py smstrade.egg-info/PKG-INFO smstrade.egg-info/SOURCES.txt smstrade.egg-info/dependency_links.txt smstrade.egg-info/entry_points.txt smstrade.egg-info/top_level.txt tests/__init__.py tests/test_smstrade.pysmstrade-0.2.4/smstrade.egg-info/entry_points.txt0000644000175000017500000000014112343700340021503 0ustar janjan00000000000000[console_scripts] smstrade_balance = smstrade:account_balance smstrade_send = smstrade:send_sms smstrade-0.2.4/smstrade.egg-info/PKG-INFO0000644000175000017500000001400612343700340017307 0ustar janjan00000000000000Metadata-Version: 1.1 Name: smstrade Version: 0.2.4 Summary: a Python library and command line tool to send SMS via the smstrade service. Home-page: https://gitorious.org/python-smstrade Author: Jan Dittberner Author-email: jan@dittberner.info License: MIT Description: About smstrade ============== Smstrade is a `Python `_ library that can be used to send SMS via the service of `smstrade.eu `_. The http(s) API is documented at http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf. Installation ------------ You can either install smstrade from the `Python Package Index`_ PyPI or from the `Git repository`_. To install from PyPI you may use `pip`_:: pip install smstrade To install from Git you need to clone the repository and run setup.py:: git clone https://git.gitorious.org/python-smstrade/python-smstrade.git cd python-smstrade python setup.py develop .. note:: Be aware that you need write access to you Python installation to perform the last step above. You may also use a `virtualenv`_ environment to run a sandboxed version of smstrade. .. _Python Package Index: https://pypi.python.org/pypi/smstrade/ .. _Git Repository: https://gitorious.org/python-smstrade/python-smstrade .. _pip: https://pypi.python.org/pypi/pip/ .. _virtualenv: https://pypi.python.org/pypi/virtualenv/ Usage ----- Sending SMS ........... You may either use the API for SMS sending:: import smstrade api = smstrade.SMSTrade() api.key = 'yourkey' api.send_sms(['00491701234567'], 'Test message') or do the same with the command line tool:: smstrade_send --key yourkey 00491701234567 'Test message' You get help for the command line tool by running:: smstrade_send -h .. note:: You can place all the configuration values into an ini file. See examples/smstrade.ini for an example. Before you really send SMS messages you need to put ``debug = False`` in your smstrade.ini. The file smstrade.ini is searched in system dependent paths as well as in the current directory. The search path is printed when invoking :literal:`smstrade_send -h` together with the description of the ``--config`` parameter. The smstrade.ini file is shared with the smstrade_balance tool. Getting the account balance ........................... Use the API for getting your account balance:: import smstrade api = smstrade.SMSTradeBalanceAPI() api.key = 'yourkey' balance = api.get_balance() or do the same with the command line tool:: smstrade_balance --key yourkey License ======= Copyright (c) 2014 Jan Dittberner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Changes ======= Release 0.2.4 (2014-06-04) -------------------------- * add Python3 support Release 0.2.3 (2014-02-22) -------------------------- * exclude tests in setup.py's find_packages Release 0.2.2 (2014-02-22) -------------------------- * include missing LICENSE and version.txt files in MANIFEST.in Release 0.2.1 (2014-02-21) -------------------------- * fix typo, use dlr instead of dir * improve tests Release 0.2 (2014-02-20) ------------------------ * add support for account balance request Release 0.1 (2014-02-20) ------------------------ * Initial release * support for the SMS sending API documented in http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities Requires: requests Requires: appdirs smstrade-0.2.4/MANIFEST.in0000644000175000017500000000012012301664511014427 0ustar janjan00000000000000include *.rst include LICENSE include examples/smstrade.ini include version.txt smstrade-0.2.4/ChangeLog.rst0000644000175000017500000000124312343676471015277 0ustar janjan00000000000000Release 0.2.4 (2014-06-04) -------------------------- * add Python3 support Release 0.2.3 (2014-02-22) -------------------------- * exclude tests in setup.py's find_packages Release 0.2.2 (2014-02-22) -------------------------- * include missing LICENSE and version.txt files in MANIFEST.in Release 0.2.1 (2014-02-21) -------------------------- * fix typo, use dlr instead of dir * improve tests Release 0.2 (2014-02-20) ------------------------ * add support for account balance request Release 0.1 (2014-02-20) ------------------------ * Initial release * support for the SMS sending API documented in http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf smstrade-0.2.4/smstrade/0000755000175000017500000000000012343700340014517 5ustar janjan00000000000000smstrade-0.2.4/smstrade/__init__.py0000644000175000017500000005571512343676471016666 0ustar janjan00000000000000# -*- python -*- # -*- coding: utf-8 -*- # # Copyright (C) 2014 Jan Dittberner import six from ._version import __version__ if six.PY2: from ConfigParser import SafeConfigParser, NoOptionError else: from configparser import ConfigParser as SafeConfigParser, NoOptionError from base64 import b16encode from datetime import datetime from locale import getpreferredencoding from pprint import pformat import appdirs import binascii import argparse import codecs import decimal import logging import os import requests #: default configuration files CONFIGFILES = [ os.path.join(appdirs.site_config_dir('smstrade'), 'smstrade.ini'), os.path.join(appdirs.user_config_dir('smstrade'), 'smstrade.ini'), 'smstrade.ini'] #: default values for configuration DEFAULTS = { 'url': 'https://gateway.smstrade.de/', 'balanceurl': 'https://gateway.smstrade.de/credits/', 'route': 'basic', 'debug': 'True', # debug is set to True to avoid costs 'enable-cost': 'False', 'enable-message-id': 'False', 'enable-count': 'False', 'enable-delivery-reports': 'False', 'enable-response': 'False', 'enable-concat': 'False', # concat is disabled to avoid costs 'charset': 'ascii', } #: characters allowed in GSM 03.38 GSM0338_CHARS = ( u'@£$¥èéùìòÇ\nØø\rÅå' u'Δ_ΦΓΛΩΠΨΣΘΞ' + six.unichr(27) + u'ÆæÉ' u' !"#¤%&\'()*+,-./' u'0123456789:;<=>?' u'¡ABCDEFGHIJKLMNO' u'PQRSTUVWXYZÄÖÑܧ' u'abcdefghijklmno' u'pqrstuvwxyzäöñüà' ) #: characters allowed in GSM 03.38 that occupy two octets GSM0338_TWO_OCTET_CHARS = u'€' + six.unichr(12) + r'[\]^{|}~' # Message types defined in API documentation #: Message type flash MESSAGE_TYPE_FLASH = 'flash' #: Message type unicode MESSAGE_TYPE_UNICODE = 'unicode' #: Message type binary MESSAGE_TYPE_BINARY = 'binary' #: Message type voice MESSAGE_TYPE_VOICE = 'voice' # Route names defined in API documentation #: Route basic ROUTE_BASIC = 'basic' #: Route gold ROUTE_GOLD = 'gold' #: Route direct ROUTE_DIRECT = 'direct' # Status codes defined in API documentation #: Status receiver number not valid STATUS_INVALID_RECEIVER_NUMBER = 10 #: Status sender number not valid STATUS_INVALID_SENDER_NUMBER = 20 #: Status message text not valid STATUS_INVALID_MESSAGE_TEXT = 30 #: Status message type not valid STATUS_INVALID_MESSAGE_TYPE = 31 #: Status SMS route not valid STATUS_INVALID_SMS_ROUTE = 40 #: Status identification failed STATUS_IDENTIFICATION_FAILED = 50 #: Status not enough balance in account STATUS_NOT_ENOUGH_BALANCE = 60 #: Status network does not support the route STATUS_NETWORK_NOT_SUPPORTED_BY_ROUTE = 70 #: Status feature is not possible by the route STATUS_FEATURE_NOT_POSSIBLE_FOR_ROUTE = 71 #: Status handover to SMSC failed STATUS_SMSC_HANDOVER_FAILED = 80 #: Status SMS has been sent successfully STATUS_OK = 100 logging.basicConfig(level=logging.INFO) log = logging.getLogger(__name__) class SMSTradeError(Exception): """ Custom exception type. """ class SMSTradeAPIBase(object): """ Base class for smstrade.eu API clients. """ def __init__(self, config=None, section='smstrade'): """ Initialize a new SMSTradeAPIBase instance. :param ConfigParser config: use the specified configuration instead of the default configuration :param str section: use the specified section in the configuration """ if config: self.config = config else: self.config = SafeConfigParser(defaults=DEFAULTS) conffiles = self.config.read(CONFIGFILES) if not conffiles: log.warning(( u'none of the configuration files (%s) found, trying' u' to continue with default values and command line' u' arguments'), ", ".join(CONFIGFILES)) self.config.add_section(section) self.key = None if self.config.has_section(section): try: self.key = self.config.get(section, 'key') except NoOptionError as e: log.warning(u"configuration is incomplete: %s", e) else: log.warning(u"configuration section %s does not exist.", section) def prepare_args(self, kwargs): """ Take a dictionary with keyword arguments, usually parsed from the command line and set existing attributes of this instance. :param dict kwargs: dictionary of keyword arguments """ for key, value in kwargs.items(): if value is not None: setattr(self, key, value) class SMSTradeAPI(SMSTradeAPIBase): """ Abstraction of the `smstrade.eu `_ http(s) mail sending API. """ def __init__(self, config=None, section='smstrade'): """ Initialize a new SMSTradeAPI instance. :param ConfigParser config: use the specified configuration instead of the default configuration :param str section: use the specified section in the configuration """ super(SMSTradeAPI, self).__init__(config, section) self.response = None self.sender = None self.reference = None self.senddate = None self.messagetype = None self.udh = None if self.config.has_section(section): try: self.url = self.config.get(section, 'url') self.route = self.config.get(section, 'route') self.debug = self.config.getboolean(section, 'debug') self.cost = self.config.getboolean(section, 'enable-cost') self.message_id = self.config.getboolean( section, 'enable-message-id') self.count = self.config.getboolean(section, 'enable-count') self.reports = self.config.getboolean( section, 'enable-delivery-reports') self.response = self.config.getboolean( section, 'enable-response') self.concat = self.config.getboolean(section, 'enable-concat') self.charset = self.config.get(section, 'charset') self.sender = self.config.get(section, 'from') except NoOptionError as e: log.warning(u"configuration is incomplete: %s", e) else: log.warning(u"configuration section %s does not exist.", section) log.debug(self.__dict__) def _handle_response_body(self, body): """ Handle parsing of response body. :param str body: response body """ log.info("response body:\n%s", body) lines = body.splitlines() try: retval = { 'status': int(lines[0]), } if self.message_id: retval['message_id'] = lines[1] if self.cost: retval['cost'] = decimal.Decimal(lines[2]) if self.count: retval['count'] = int(lines[3]) except IndexError: raise SMSTradeError('malformed response') return retval def _add_optional_flags(self, request_params): if self.debug: request_params['debug'] = 1 if self.cost: request_params['cost'] = 1 if self.message_id: request_params['message_id'] = 1 if self.count: request_params['count'] = 1 if self.reports: request_params['dlr'] = 1 if self.response and self.route == ROUTE_BASIC: request_params['response'] = 1 return request_params def _add_optional_fields(self, request_params): if self.reference is not None: request_params['ref'] = self.reference if self.senddate is not None: request_params['senddate'] = self.senddate if self.messagetype is not None: request_params['messagetype'] = self.messagetype return request_params def _build_request_parameters(self, recipient): """ Build the request parameter dictionary based on fields in this SMSTradeAPI instance. :param str recipient: recipient calling number """ request_params = { 'key': self.key, 'to': recipient, 'route': self.route, } if self.route in (ROUTE_GOLD, ROUTE_DIRECT): request_params['from'] = self.sender.encode(self.charset) if self.charset != 'ascii': request_params['charset'] = self.charset request_params = self._add_optional_flags(request_params) request_params = self._add_optional_fields(request_params) return request_params def _send_normal_message(self, recipient, text): """ Send a normal SMS message to the given recipient. :param str recipient: recipient calling number :param unicode text: unicode SMS message text """ request_params = self._build_request_parameters(recipient) request_params['message'] = text.encode(self.charset) if self.concat: request_params['concat'] = 1 response = requests.post(self.url, data=request_params) response.raise_for_status() return self._handle_response_body(response.text) def _send_unicode_message(self, recipient, text): """ Send a unicode SMS message to the given recipient. :param str recipient: recipient calling number :param unicode text: unicode SMS message text """ request_params = self._build_request_parameters(recipient) request_params['message'] = b16encode(text.encode('utf_16_be')) response = requests.post(self.url, data=request_params) response.raise_for_status() return self._handle_response_body(response.text) def _send_binary_message(self, recipient, text): """ Send a binary SMS message to the given recipient. :param str recipient: recipient calling number :param str text: hexadecimal representation of the binary data """ request_params = self._build_request_parameters(recipient) request_params['message'] = text if self.udh is not None: request_params['udh'] = self.udh response = requests.post(self.url, data=request_params) response.raise_for_status() return self._handle_response_body(response.text) def _send_voice_message(self, recipient, text): """ Send a voice SMS message to the given recipient. :param str recipient: recipient calling number :param unicode text: the message text """ request_params = self._build_request_parameters(recipient) request_params['message'] = text.encode(self.charset) response = requests.post(self.url, data=request_params) response.raise_for_status() return self._handle_response_body(response.text) def _send_message(self, recipient, text): """ Send an SMS to a single recipient. :param str recipient: recipient calling number :param str text: SMS message text """ if ((self.messagetype is None) or (self.messagetype == MESSAGE_TYPE_FLASH)): return self._send_normal_message(recipient, text) elif self.messagetype == MESSAGE_TYPE_UNICODE: return self._send_unicode_message(recipient, text) elif self.messagetype == MESSAGE_TYPE_BINARY: return self._send_binary_message(recipient, text) elif self.messagetype == MESSAGE_TYPE_VOICE: return self._send_voice_message(recipient, text) else: raise SMSTradeError(u"unknown message type %s" % self.messagetype) def _gsm0338_length(self, text): charcount = 0 for char in text: if char in GSM0338_CHARS: charcount += 1 elif char in GSM0338_TWO_OCTET_CHARS: charcount += 2 else: raise SMSTradeError( u"character %s is not allowed in GSM messages." % char) return charcount def _check_normal_message(self, text): """ Perform a plausibility check on the given message text. :param str text: the message to check """ charcount = self._gsm0338_length(text) if ((self.concat and charcount > 1530) or (not self.concat and charcount > 160)): message = "too many characters in message" if not self.concat and charcount <= 1530: message += ", you may try to use concat" raise SMSTradeError(message) try: text.encode(self.charset) except ValueError: raise SMSTradeError(( "The message can not be encoded with the chosen character set" " %s") % self.charset) def _check_unicode_message(self, text): """ Perform a plausibility check on the given unicode message text. :param str text: the message to check """ for char in text: code = ord(char) if (code >= 0xd800 and code <= 0xdfff) or (code > 0xffff): raise SMSTradeError( u"the message can not be represented in UCS2") if len(text) > 70: raise SMSTradeError( u"too many characters in message, unicode SMS may contain up" u" to 70 characters") def _check_binary_message(self, text): """ Perform a plausibility check on the given binary message text. :param str text: the message to check """ try: length = len(codecs.decode(six.b(text.lower()), 'hex_codec')) if length > 140: raise SMSTradeError( u'too many bytes in message, binary messages may contain' u' up to 140 bytes') except: raise SMSTradeError('message cannot be encoded as bytes') def _check_voice_message(self, text): """ Perform a plausibility check on the give message intended to be sent as voice message. :param str text: the message to check """ if self._gsm0338_length(text) > 160: raise SMSTradeError(u'too many GSM characters in message') def _check_message(self, text): if ((self.messagetype is None) or (self.messagetype == MESSAGE_TYPE_FLASH)): self._check_normal_message(text) elif self.messagetype == MESSAGE_TYPE_UNICODE: self._check_unicode_message(text) elif self.messagetype == MESSAGE_TYPE_BINARY: self._check_binary_message(text) elif self.messagetype == MESSAGE_TYPE_VOICE: self._check_voice_message(text) else: raise SMSTradeError( u"message type %s is unknown" % self.messagetype) def send_sms(self, to, text, **kwargs): """ Send an SMS to recipients in the to parameter. :param list to: list of recipient calling numbers :param str text: SMS message text :param dict kwargs: keyword arguments that override values in the configuration files """ self.prepare_args(kwargs) retval = {} for recipient in to: self._check_message(text) retval[recipient] = self._send_message(recipient, text) return retval class SMSTradeBalanceAPI(SMSTradeAPIBase): """ Abstraction of the `smstrade.eu `_ http(s) account balance API. """ def __init__(self, config=None, section='smstrade'): """ Initialize a new SMSTradeBalanceAPI instance. :param ConfigParser config: use the specified configuration instead of the default configuration :param str section: use the specified section in the configuration """ super(SMSTradeBalanceAPI, self).__init__(config, section) if self.config.has_section(section): self.url = self.config.get(section, 'balanceurl') else: log.warning(u"configuration section %s does not exist.", section) log.debug(self.__dict__) def get_balance(self, **kwargs): """ Get the account balance from smstrade.eu and return it as a :pyclass:`decimal.Decimal` instance. :param dict kwargs: keyword arguments that override values in the configuration files """ self.prepare_args(kwargs) if self.key is None: raise SMSTradeError( u'you need to define an API key either in a configuration' u' file or on the command line') response = requests.get(self.url, params={'key': self.key}) response.raise_for_status() return decimal.Decimal(response.text) def hexstr(value): """ Check whether the given hexadecimal value can successfully be decoded to bytes. :param str value: string of hexadecimal representations of bytes """ try: codecs.decode(six.b(value.lower()), 'hex_codec') except TypeError as te: raise argparse.ArgumentTypeError(te.message) except binascii.Error as be: raise argparse.ArgumentTypeError(be) return value def secondssinceepoch(seconds): """ Check whether the given value is a valid timestamp after the current timestamp. :param str seconds: string value that represents an int specifying a timestamp relative to the UNIX epoch """ value = int(seconds) if datetime.fromtimestamp(value) < datetime.now(): raise argparse.ArgumentTypeError( "timestamps in the past are not allowed.") return value def send_sms(cmdline=None): """ Send SMS from the command line. :param list cmdline: list of command line arguments """ parser = argparse.ArgumentParser( description="Send one or more SMS via the smstrade.eu API") parser.add_argument( '-c', '--config', type=argparse.FileType('r'), help=( "alternative configuration instead of the default configuration" "files:\n {0}").format(", ".join(CONFIGFILES))) parser.add_argument( '-s', '--section', type=str, default='smstrade', help='use the specified section in the configuration file') parser.add_argument( '-k', '--key', type=str, help="personal identification code") parser.add_argument( '-f', '--from', dest='sender', type=str, help="source identifier (ignored for route basic)") parser.add_argument( '-r', '--route', choices=[ROUTE_BASIC, ROUTE_GOLD, ROUTE_DIRECT], help='SMS route') parser.add_argument( '-d', '--debug', action='store_const', const=True, help='activate debug mode') parser.add_argument( '--cost', action='store_const', const=True, help='enable output of sending costs') parser.add_argument( '-m', '--message-id', action='store_const', const=True, dest='message_id', help='enable output of message ids') parser.add_argument( '--count', action='store_const', const=True, help='enable output of message count') parser.add_argument( '--dlr', action='store_const', const=True, dest='reports', help='enable delivery reports') parser.add_argument( '--response', action='store_const', const=True, help='enable receiving of reply SMS (only for route basic)') parser.add_argument( '--ref', type=str, dest='reference', help='add an own reference for this message') parser.add_argument( '-l', '--concat', action='store_const', const=True, help='send as linked (longer) SMS') parser.add_argument( '--charset', choices=['UTF-8', 'ISO-8859-1', 'ISO-8859-15'], help=( "character set of the message (defaults to current locale's" " charset) converted to UTF-8 if necessary")) parser.add_argument( '--senddate', type=secondssinceepoch, help='send time delayed SMS at the given time (UNIX timestamp)') parser.add_argument( '--messagetype', choices=[ MESSAGE_TYPE_FLASH, MESSAGE_TYPE_UNICODE, MESSAGE_TYPE_BINARY, MESSAGE_TYPE_VOICE], help='enable sending of flash, unicode, binary or voice messages') parser.add_argument( '--udh', type=hexstr, help='hexadecimal representation of bytes for a binary message') parser.add_argument( '--version', action='version', version='%(prog)s ' + __version__) parser.add_argument( 'to', nargs='+', type=str, help="receiver of the SMS",) parser.add_argument( 'smstext', type=six.text_type, help="the text content of the SMS message to send") if cmdline is not None: args = parser.parse_args(cmdline) else: args = parser.parse_args() config = None if args.config: config = SafeConfigParser(defaults=DEFAULTS) config.readfp(args.config) smstrade = SMSTradeAPI(config=config, section=args.section) to = args.to smstext = args.smstext del args.config del args.section del args.to del args.smstext try: retval = smstrade.send_sms(to, smstext, **args.__dict__) log.info("Return value:\n%s", pformat(retval)) except SMSTradeError as e: log.error(e) def account_balance(cmdline=None): """ Get the smstrade.eu account balance from the command line. :param list cmdline: list of command line arguments """ parser = argparse.ArgumentParser( description="Send one or more SMS via the smstrade.eu API") parser.add_argument( '-c', '--config', type=argparse.FileType('r'), help=( "alternative configuration instead of the default configuration" "files:\n {0}").format(", ".join(CONFIGFILES))) parser.add_argument( '-s', '--section', type=str, default='smstrade', help='use the specified section in the configuration file') parser.add_argument( '-k', '--key', type=str, help="personal identification code") if cmdline is not None: args = parser.parse_args(cmdline) else: args = parser.parse_args() config = None if args.config: config = SafeConfigParser(defaults=DEFAULTS) config.readfp(args.config) smstradebalance = SMSTradeBalanceAPI( config=config, section=args.section) del args.config del args.section try: balance = smstradebalance.get_balance(**args.__dict__) log.info(u"Your smstrade balance : %.03f €", balance) except SMSTradeError as e: log.error(e) smstrade-0.2.4/smstrade/_version.py0000644000175000017500000000017212343700337016723 0ustar janjan00000000000000 # This file is automatically generated by setup.py. __version__ = '0.2.4' __sha__ = 'g19d040f' __revision__ = 'g19d040f' smstrade-0.2.4/tests/0000755000175000017500000000000012343700340014037 5ustar janjan00000000000000smstrade-0.2.4/tests/__init__.py0000644000175000017500000000000012301223753016140 0ustar janjan00000000000000smstrade-0.2.4/tests/test_smstrade.py0000644000175000017500000002514412343676471017321 0ustar janjan00000000000000# -*- python -*- # -*- coding: utf-8 -*- import six if six.PY2: from ConfigParser import SafeConfigParser else: from configparser import ConfigParser as SafeConfigParser import argparse import decimal import httpretty import os import pytest import smstrade import tempfile import time @pytest.fixture() def cleandir(): newpath = tempfile.mkdtemp() os.chdir(newpath) @pytest.fixture() def api(): testconfig = SafeConfigParser(defaults=smstrade.DEFAULTS) testconfig.add_section('smstrade') testconfig.set('smstrade', 'key', 'testkey') testconfig.set('smstrade', 'from', 'testsender') return smstrade.SMSTradeAPI(testconfig) def test_SMSTradeError(): exception = smstrade.SMSTradeError(u"a new test") assert str(exception) == 'a new test' @pytest.mark.usefixtures('cleandir') def test_SMSTradeAPI_init(): smstrade.SMSTradeAPI() class TestSMSTradeAPI(object): def test__gsm0338_length(self, api): assert api._gsm0338_length(u'a') == 1 assert api._gsm0338_length(u'€') == 2 assert api._gsm0338_length(u'a€') == 3 with pytest.raises(smstrade.SMSTradeError): api._gsm0338_length(u'Ł') def test__check_normal_message(self, api): api._check_normal_message(160 * u'a') with pytest.raises(smstrade.SMSTradeError): api._check_normal_message(161 * u'a') api.concat = True api._check_normal_message(1530 * u'a') with pytest.raises(smstrade.SMSTradeError): api._check_normal_message(1531 * u'a') def test__encoding_normal_message(self, api): api.charset = 'ISO-8859-1' api._check_normal_message(160 * u'a') with pytest.raises(smstrade.SMSTradeError): api._check_normal_message(80 * u'€') api.charset = 'ISO-8859-15' api._check_normal_message(80 * u'€') with pytest.raises(smstrade.SMSTradeError): api._check_normal_message(160 * u'Ω') api.charset = 'UTF-8' api._check_normal_message(160 * u'Ω') def test__check_unicode_message(self, api): api._check_unicode_message(70 * u'€') with pytest.raises(smstrade.SMSTradeError): api._check_unicode_message(70 * six.unichr(0x120AE)) with pytest.raises(smstrade.SMSTradeError): api._check_unicode_message(71 * u'€') def test__check_binary_message(self, api): api._check_binary_message(140 * 'a0') with pytest.raises(smstrade.SMSTradeError): api._check_binary_message(141 * 'a0') with pytest.raises(smstrade.SMSTradeError): api._check_binary_message(30 * 'r0') def test__check_voice_message(self, api): api._check_voice_message(160 * u'a') with pytest.raises(smstrade.SMSTradeError): api._check_voice_message(161 * u'a') def test__check_message(self, api): api._check_message(160 * u'a') api.messagetype = 'flash' api._check_message(160 * u'a') api.messagetype = 'unicode' api._check_message(70 * u'€') api.messagetype = 'binary' api._check_message(140 * 'a0') api.messagetype = 'voice' api._check_message(160 * u'a') api.messagetype = 'wrong' with pytest.raises(smstrade.SMSTradeError): api._check_message('does not matter') def test__handle_response_body(self, api): assert api._handle_response_body('100') == { 'status': smstrade.STATUS_OK} assert api._handle_response_body(str( smstrade.STATUS_NOT_ENOUGH_BALANCE)) == { 'status': smstrade.STATUS_NOT_ENOUGH_BALANCE} assert api._handle_response_body('100\n12345678') == { 'status': smstrade.STATUS_OK} api.message_id = True assert api._handle_response_body('100\n12345678') == { 'status': smstrade.STATUS_OK, 'message_id': '12345678'} with pytest.raises(smstrade.SMSTradeError): api._handle_response_body('100') assert api._handle_response_body('100\n12345678\n0') == { 'status': smstrade.STATUS_OK, 'message_id': '12345678'} api.cost = True assert api._handle_response_body('100\n12345678\n0') == { 'status': smstrade.STATUS_OK, 'message_id': '12345678', 'cost': decimal.Decimal('0')} api.message_id = False assert api._handle_response_body('100\n\n0.055') == { 'status': smstrade.STATUS_OK, 'cost': decimal.Decimal('0.055')} assert api._handle_response_body('100\n\n0.055\n1') == { 'status': smstrade.STATUS_OK, 'cost': decimal.Decimal('0.055')} api.count = True assert api._handle_response_body('100\n\n0.055\n1') == { 'status': smstrade.STATUS_OK, 'cost': decimal.Decimal('0.055'), 'count': 1} api.message_id = True assert api._handle_response_body('100\n12345678\n0.055\n1') == { 'status': smstrade.STATUS_OK, 'message_id': '12345678', 'message_id': '12345678', 'cost': decimal.Decimal('0.055'), 'count': 1} @pytest.mark.usefixtures('cleandir') def test__add_optional_flags(self, api): for attrname, param in ( ('debug', 'debug'), ('cost', 'cost'), ('message_id', 'message_id'), ('count', 'count'), ('reports', 'dlr'), ('response', 'response')): setattr(api, attrname, True) request_params = {} request_params = api._add_optional_flags(request_params) assert request_params[param] == 1 api.route = smstrade.ROUTE_GOLD api.response = True request_params = {} api._add_optional_flags(request_params) assert 'response' not in request_params @pytest.mark.usefixtures('cleandir') def test__add_optional_fields(self, api): for attrname, param, value in ( ('reference', 'ref', 'myref0815'), ('senddate', 'senddate', int(time.time() + 100)), ('messagetype', 'messagetype', 'flash')): setattr(api, attrname, value) request_params = {} request_params = api._add_optional_fields(request_params) assert request_params[param] == value @pytest.mark.usefixtures('cleandir') def test__build_request_parameters(self, api): api.key = 'Testkey' assert api._build_request_parameters('01717654321') == { 'key': 'Testkey', 'to': '01717654321', 'route': 'basic', 'debug': 1} api.route = smstrade.ROUTE_GOLD api.charset = 'UTF-8' api.sender = u'Dönermann' assert api._build_request_parameters('01717654321') == { 'key': 'Testkey', 'to': '01717654321', 'route': 'gold', 'debug': 1, 'from': u'Dönermann'.encode('UTF-8'), 'charset': 'UTF-8'} def test__send_normal_message(self, api): httpretty.enable() httpretty.register_uri(httpretty.POST, api.url, body='100') assert api._send_message('01717654321', 'Test') == { 'status': smstrade.STATUS_OK} httpretty.register_uri(httpretty.POST, api.url, body='100\n\n\n4') api.concat = True api.count = True assert api._send_message('01717654321', 140 * 'Test') == { 'status': smstrade.STATUS_OK, 'count': 4} def test__send_binary_message(self, api): httpretty.enable() httpretty.register_uri(httpretty.POST, api.url, body='100') api.messagetype = smstrade.MESSAGE_TYPE_BINARY api.udh = '040b02000820de' assert api._send_message('01717654321', u'48656c6c6f') == { 'status': smstrade.STATUS_OK} def test__send_message(self, api): httpretty.enable() httpretty.register_uri(httpretty.POST, api.url, body='100') assert api._send_message('01717654321', u'Test') == { 'status': smstrade.STATUS_OK} for messagetype, message in ( (smstrade.MESSAGE_TYPE_FLASH, u'Test'), (smstrade.MESSAGE_TYPE_UNICODE, u'Привет мир'), (smstrade.MESSAGE_TYPE_BINARY, u'48656c6c6f'), (smstrade.MESSAGE_TYPE_VOICE, u'Test')): api.messagetype = messagetype assert api._send_message('01717654321', message) == { 'status': smstrade.STATUS_OK} with pytest.raises(smstrade.SMSTradeError): api.messagetype = 'invalid' api._send_message('01717654321', u'Test') def test_send_sms(self, api): httpretty.enable() httpretty.register_uri(httpretty.POST, api.url, body='100') testargs = {'wrong': 'does not matter', 'from': 'test'} result = api.send_sms(['00491717654321'], 'Test', **testargs) assert result == {'00491717654321': {'status': smstrade.STATUS_OK}} @pytest.mark.usefixtures('cleandir') def test_empty_conffile(): with open('dummy.ini', 'w') as inifile: inifile.write('') conf = SafeConfigParser() conf.read(['dummy.ini']) smstrade.SMSTradeAPI(conf) smstrade.SMSTradeBalanceAPI(conf) def test_hexstr(): assert smstrade.hexstr('A0a0') == 'A0a0' with pytest.raises(argparse.ArgumentTypeError): smstrade.hexstr('R0') def test_secondssinceepoch(): timestamp = str(int(time.time() + 100)) assert smstrade.secondssinceepoch(timestamp) == int(timestamp) timestamp = str(int(time.time() - 100)) with pytest.raises(argparse.ArgumentTypeError): smstrade.secondssinceepoch(timestamp) @pytest.mark.usefixtures('cleandir') def test_send_sms(): httpretty.enable() httpretty.register_uri(httpretty.POST, smstrade.DEFAULTS['url'], body='100') with pytest.raises(SystemExit): smstrade.send_sms([]) smstrade.send_sms(['00491717654321', 'Test']) smstrade.send_sms(['--messagetype', 'binary', '00491717654321', 'Test']) with open('dummy.ini', 'w') as inifile: inifile.write('[smstrade]\nkey = fake') smstrade.send_sms(['--config', 'dummy.ini', '00491717654321', 'Test']) @pytest.mark.usefixtures('cleandir') def test_account_balance(): httpretty.enable() httpretty.register_uri( httpretty.GET, smstrade.DEFAULTS['balanceurl'], body='0.000') smstrade.account_balance([]) smstrade.account_balance(['--key', 'fake']) with open('dummy.ini', 'w') as inifile: inifile.write('[smstrade]\nkey = fake') smstrade.account_balance(['--config', 'dummy.ini']) smstrade-0.2.4/README.rst0000644000175000017500000000444412301432660014373 0ustar janjan00000000000000About smstrade ============== Smstrade is a `Python `_ library that can be used to send SMS via the service of `smstrade.eu `_. The http(s) API is documented at http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf. Installation ------------ You can either install smstrade from the `Python Package Index`_ PyPI or from the `Git repository`_. To install from PyPI you may use `pip`_:: pip install smstrade To install from Git you need to clone the repository and run setup.py:: git clone https://git.gitorious.org/python-smstrade/python-smstrade.git cd python-smstrade python setup.py develop .. note:: Be aware that you need write access to you Python installation to perform the last step above. You may also use a `virtualenv`_ environment to run a sandboxed version of smstrade. .. _Python Package Index: https://pypi.python.org/pypi/smstrade/ .. _Git Repository: https://gitorious.org/python-smstrade/python-smstrade .. _pip: https://pypi.python.org/pypi/pip/ .. _virtualenv: https://pypi.python.org/pypi/virtualenv/ Usage ----- Sending SMS ........... You may either use the API for SMS sending:: import smstrade api = smstrade.SMSTrade() api.key = 'yourkey' api.send_sms(['00491701234567'], 'Test message') or do the same with the command line tool:: smstrade_send --key yourkey 00491701234567 'Test message' You get help for the command line tool by running:: smstrade_send -h .. note:: You can place all the configuration values into an ini file. See examples/smstrade.ini for an example. Before you really send SMS messages you need to put ``debug = False`` in your smstrade.ini. The file smstrade.ini is searched in system dependent paths as well as in the current directory. The search path is printed when invoking :literal:`smstrade_send -h` together with the description of the ``--config`` parameter. The smstrade.ini file is shared with the smstrade_balance tool. Getting the account balance ........................... Use the API for getting your account balance:: import smstrade api = smstrade.SMSTradeBalanceAPI() api.key = 'yourkey' balance = api.get_balance() or do the same with the command line tool:: smstrade_balance --key yourkey smstrade-0.2.4/LICENSE0000644000175000017500000000204212301146270013700 0ustar janjan00000000000000Copyright (c) 2014 Jan Dittberner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. smstrade-0.2.4/PKG-INFO0000644000175000017500000001400612343700340013773 0ustar janjan00000000000000Metadata-Version: 1.1 Name: smstrade Version: 0.2.4 Summary: a Python library and command line tool to send SMS via the smstrade service. Home-page: https://gitorious.org/python-smstrade Author: Jan Dittberner Author-email: jan@dittberner.info License: MIT Description: About smstrade ============== Smstrade is a `Python `_ library that can be used to send SMS via the service of `smstrade.eu `_. The http(s) API is documented at http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf. Installation ------------ You can either install smstrade from the `Python Package Index`_ PyPI or from the `Git repository`_. To install from PyPI you may use `pip`_:: pip install smstrade To install from Git you need to clone the repository and run setup.py:: git clone https://git.gitorious.org/python-smstrade/python-smstrade.git cd python-smstrade python setup.py develop .. note:: Be aware that you need write access to you Python installation to perform the last step above. You may also use a `virtualenv`_ environment to run a sandboxed version of smstrade. .. _Python Package Index: https://pypi.python.org/pypi/smstrade/ .. _Git Repository: https://gitorious.org/python-smstrade/python-smstrade .. _pip: https://pypi.python.org/pypi/pip/ .. _virtualenv: https://pypi.python.org/pypi/virtualenv/ Usage ----- Sending SMS ........... You may either use the API for SMS sending:: import smstrade api = smstrade.SMSTrade() api.key = 'yourkey' api.send_sms(['00491701234567'], 'Test message') or do the same with the command line tool:: smstrade_send --key yourkey 00491701234567 'Test message' You get help for the command line tool by running:: smstrade_send -h .. note:: You can place all the configuration values into an ini file. See examples/smstrade.ini for an example. Before you really send SMS messages you need to put ``debug = False`` in your smstrade.ini. The file smstrade.ini is searched in system dependent paths as well as in the current directory. The search path is printed when invoking :literal:`smstrade_send -h` together with the description of the ``--config`` parameter. The smstrade.ini file is shared with the smstrade_balance tool. Getting the account balance ........................... Use the API for getting your account balance:: import smstrade api = smstrade.SMSTradeBalanceAPI() api.key = 'yourkey' balance = api.get_balance() or do the same with the command line tool:: smstrade_balance --key yourkey License ======= Copyright (c) 2014 Jan Dittberner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Changes ======= Release 0.2.4 (2014-06-04) -------------------------- * add Python3 support Release 0.2.3 (2014-02-22) -------------------------- * exclude tests in setup.py's find_packages Release 0.2.2 (2014-02-22) -------------------------- * include missing LICENSE and version.txt files in MANIFEST.in Release 0.2.1 (2014-02-21) -------------------------- * fix typo, use dlr instead of dir * improve tests Release 0.2 (2014-02-20) ------------------------ * add support for account balance request Release 0.1 (2014-02-20) ------------------------ * Initial release * support for the SMS sending API documented in http://www.smstrade.eu/pdf/SMS-Gateway_HTTP_API_v2_en.pdf Platform: UNKNOWN Classifier: Development Status :: 4 - Beta Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: MIT License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Topic :: Communications Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Utilities Requires: requests Requires: appdirs smstrade-0.2.4/version.txt0000644000175000017500000000002012343700337015121 0ustar janjan000000000000000.2.4-0-g19d040f