Python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import urllib
import httplib

ENDPOINT = "get.spiricom.spirius.com:55001"
PATH = "/cgi-bin/sendsms?"
USER = "Username"
PASS = "Password"

def send_sms(sender, recipient, message):
try:
    params = {'User': USER,
              'Pass': PASS,
              'To': recipient,
              'From': sender,
              'Msg': message,
              'CharSet': 'utf-8'}
    query_args = urllib.urlencode(params)
    conn = httplib.HTTPSConnection(ENDPOINT)
    conn.request("GET", PATH + query_args)
    r = conn.getresponse()
    return "%d %s" % (r.status, r.reason)

    except Exception, e:
        sys.stderr.write(str(e))
        return ""

print send_sms("+46123456789", "+46123456789", "Hello world")

This example uses the third party library Requests, which makes sending HTTP requests easier.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import requests

URL = 'https://get.spiricom.spirius.com:55001/cgi-bin/sendsms'
USER = 'Username'
PASS = 'Password'

def send_sms(sender, recipient, message):
    try:
        _params = { 'User'   : USER,
                    'Pass'   : PASS,
                    'From'   : sender,
                    'To'     : recipient,
                    'Msg'    : message,
                    'CharSet': 'utf-8'}
        response = requests.get(URL, params=_params, timeout=10)
        return response.text
    except Exception, e:
        sys.stderr.write(str(e))
        return ""

print send_sms("+46123456789", "+46123456789", "Hello world")

Demonstrates how to handle rate-limit (http status code 409) and unresponsive endpoints.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib
import httplib
import unittest
import logging
from contextlib import closing

USERNAME = "Username"
PASSWORD = "Password"
CONNECTION_TIMEOUT = 10  # seconds
SMS_PROVIDERS = ["get1.spiricom.spirius.com", "get2.spiricom.spirius.com"]


def _do_send_sms_request(conn, request):
    """
    Send request to HTTP GET API.
    Retry if provider tell us we are sending faster than we have agreed.
    """
    for attempt in xrange(3):
        conn.request("GET", request)
        result = conn.getresponse()
        if result.status != httplib.CONFLICT:
            logging.warning("INFO: Request sent. Response: %s, %s, %s" %
                            (result.status, result.reason, result.read()))
            return result.status
    else:
        # Provider told us we are sending too fast. Wait then retry.
        time.sleep(1.5)


def send_sms(username, password, ext_id, from_type, from_number, to_number, sms_text):
    """
    Iterate over all available sms providers and attempt to setup a HTTP connection.
    When a connection is established, send request.
    If _do_send_sms_request() raises an exception (or connection times out), use next provider
    """
    from_number_enc = from_number.encode('iso-8859-1', 'ignore')
    sms_text_enc = sms_text.encode('utf-8', 'ignore')

        for endpoint in SMS_PROVIDERS:
            try:
                with closing(httplib.HTTPSConnection("%s:55001" % endpoint, timeout=CONNECTION_TIMEOUT)) as conn:

                    params = {
                        'User': username,
                        'Pass': password,
                        'To':   to_number,
                        'From': from_number_enc,
                        'FromType': from_type,
                        'Msg': sms_text_enc,
                        'CharSet': 'utf-8'
                    }

                    if len(ext_id) > 0:
                        params['ExtId'] = "List: " + ext_id

                    request = "/cgi-bin/sendsms?%s" % urllib.urlencode(params)
                    if _do_send_sms_request(conn, request) == httplib.ACCEPTED:
                        logging.warning("SMS was accepted")
                    else:
                        logging.warning("SMS was NOT accepted")
                    # Request was successfully sent, so we are done for now
                    return 1

            except Exception, e:
                logging.warning("WARNING: Failed to send request, connection problem: %s" % str(e))
                pass # retry using next endpoint in list

        return 0


class UnitTests(unittest.TestCase):

    def test_send_sms(self):
        result = send_sms(
            username=USERNAME,
            password=PASSWORD,
            ext_id="",
            from_type="I",
            from_number="+46123456789",
            to_number="+46123456789",
            sms_text="Test SMS")
        self.assertTrue(result)    
Back to top