Search code examples
pythonurllibkannel

How do I get rid of spaces in the 'message' when sending SMS via Kannel


I've setup Kannel in Ubuntu using a USB Modem and I can send SMS via the browser using the URL as seen below

localhost:13013/cgi-bin/sendsms?username=kannel&password=kannel&to=+254781923855&text='Kid got swag'

In python, I have the following script which works only if the message to be sent does not have spaces.

import urllib.request
def send_sms(mobile_no, message):
    url="http://%s:%d/cgi-bin/sendsms?username=%s&password=%s&to=%s&text=%s" \
    % ('localhost', 13013, 'kannel', 'kannel', str(mobile_no), message)
    f = urllib.request.urlopen(url)
    print("sms sent")

If I call the function with NO spaces in the message, it works and the message is sent.

sms.send_sms('+254781923855', 'kid_got_swag')

If I have spaces in the message, it fails with the error belw

sms.send_sms('+254781923855', 'kid got swag')

Traceback (most recent call last):
File "/home/lukik/workspace/projx/src/short_message.py", line 24, in <module>
sms.send_sms('+254781923855', 'kid got swag')
File "/home/lukik/workspace/projx/src/short_message.py", line 18, in send_sms
f = urllib.request.urlopen(url)
File "/usr/lib/python3.2/urllib/request.py", line 139, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.2/urllib/request.py", line 376, in open
response = meth(req, response)
File "/usr/lib/python3.2/urllib/request.py", line 488, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.2/urllib/request.py", line 414, in error
return self._call_chain(*args)
File "/usr/lib/python3.2/urllib/request.py", line 348, in _call_chain
result = func(*args)
File "/usr/lib/python3.2/urllib/request.py", line 496, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request

I've tried other variants of calling urllib but they all fail coz of the spaces in the message....


Solution

  • In your request you send via browser, the message is inside quotes -

    &text='Kid got swag'
    

    Try that in your request -

    url="http://%s:%d/cgi-bin/sendsms?username=%s&password=%s&to=%s&text='%s'" \
        % ('localhost', 13013, 'kannel', 'kannel', str(mobile_no), message)
    

    Notice the single quotes at &text='%s'.

    PS: I'd recommend using requests for requests like this. You could construct your urls better that way, like this -

    >>> payload = {'key1': 'value1', 'key2': 'value2'}
    >>> r = requests.get("http://httpbin.org/get", params=payload)