summaryrefslogtreecommitdiffstats
path: root/agenda/build sms gateway on puyak.r with gammu.md
blob: c8d19911bd6ff7ba8f95c0f9dadd2a041dec2ce1 (plain)
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
```
#!/usr/bin/env python3

import falcon
import json
import gammu
import sys

sm = gammu.StateMachine()
sm.ReadConfig()
sm.Init()


class GammuSMS:
    def on_post(self, req, resp):
        try:
            body = req.stream.read().decode()
            print('raw:', body)
            sys.stdout.flush()
            data = json.loads(body)
            print('json:', data, file=sys.stdout)
            sys.stdout.flush()
        except ValueError:
            resp.body = json.dumps({'status': 'error', 'message': 'malformed json body'})
            resp.status = falcon.HTTP_400
            return

        if 'number' not in data:
            resp.body = json.dumps({'status': 'error', 'message': 'missing required parameter `number`'})
            resp.status = falcon.HTTP_400

        elif 'message' not in data:
            resp.body = json.dumps({'status': 'error', 'message': 'missing required parameter `message`'})
            resp.status = falcon.HTTP_400

        else:
            # replace leading '+' with '00'
            if data['number'].startswith('+'):
                data['number'] = "00{}".format(data['number'][2:])

            if not data['number'].isdigit():
                resp.body = json.dumps({'status': 'error', 'message': 'illegal number given: "{}"'.format(data['number'])})
                resp.status = falcon.HTTP_400
                return

            message = {
                'SMSC': {'Location': 1},
                'Text': data['message'],
                'Number': data['number']
            }

            try:
                id = sm.SendSMS(message)
                resp.body = json.dumps({'status': 'ok', 'message': 'queued ({})'.format(id)})
                resp.status = falcon.HTTP_200
            except gammu.ERR_UNKNOWN as ex:
                resp.body = json.dumps({'error': str(ex)})
                resp.status = falcon.HTTP_500


api = falcon.API()
api.add_route('/sms', GammuSMS())
```

makefu and xkey founded the sms gateway taskforce