forked from codeforamerica/message_macon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sms.py
77 lines (62 loc) · 2.04 KB
/
sms.py
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
"""SMSified logic for the MTA application."""
import os
import requests as req
import three
if 'PRODUCTION_ENV' in os.environ:
# Then we'll use the actual SeeClickFix endpoint.
macon = three.city('macon')
else:
# Otherwise, it's testing.
macon = three.dev('http://seeclicktest.com/open311/v2')
class AddressError(Exception):
"""Can't parse an address from a text message."""
pass
class AuthenticationError(Exception):
"""
Error should be raised when the SMSified username and password
aren't known.
"""
pass
def auth():
"""
Get SMSified username and password authentication from environment
variables.
"""
try:
username = os.environ['SMS_USER']
password = os.environ['SMS_PASS']
except KeyError:
message = "You haven't set the SMS_USER and SMS_PASS env variables."
raise AuthenticationError(message)
return (username, password)
def process(text):
"""Process an incoming text message."""
number = text['senderAddress'].lstrip('tel:+')
message = text['message']
address, info = find_address(message)
post = macon.post('0', address=address, description=info, phone=number)
# Log the POST request to SeeClickFix.
print post
return respond(number)
def find_address(message):
"""Parse the address from a text message."""
data = message.split('. ')
length = len(data)
if length == 1:
raise AddressError("Can't process the address from your text message.")
elif length == 2:
description = data[1]
else:
description = '. '.join(data[1:])
street = data[0]
address = street + ' Macon, GA'
return address, description
def respond(number):
"""Send an SMS text message."""
user_pass = auth()
number = number.replace('-', '')
message = "Thanks for reporting your issue!"
params = {'address': number, 'message': message}
send = "https://api.smsified.com/v1/smsmessaging/outbound/4782467248/requests"
sms = req.post(send, auth=user_pass, params=params)
return sms