forked from therippa/notify_labor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
207 lines (174 loc) · 7.45 KB
/
run.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import requests
import twilio.twiml
from flask import Flask
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from twilio.rest import TwilioRestClient
import time
import utils
app = Flask(__name__)
app.config.from_pyfile('config.py')
utils.init_db()
utils.make_recordings_directory()
MESSAGE = ''
voice = 'alice'
@app.route('/')
def index():
return 'go away'
@app.route('/list', methods=['POST', 'GET'])
def list_db():
if request.method == 'GET':
return render_template('list_form.html')
else:
phrase_text = request.form['txt-phrase']
if phrase_text == app.config['LABOR_PHRASE']:
numbers = utils.get_all_numbers()
return render_template('list.html', x=numbers)
else:
return 'Wrong Phrase sucka'
@app.route('/api/register', methods=['GET', 'POST'])
def register():
resp = twilio.twiml.Response()
resp.say('Welcome to the %s Notifier.' % app.config['BABY_NICKNAME'], voice=voice)
with resp.gather(numDigits=10, action=url_for('confirm'), method='POST') as g:
g.say('To register to receive a notification once the baby is born, please enter your '
'phone number starting with the 3 digit area code, followed by the 7 digit number', voice=voice)
return str(resp)
@app.route('/api/confirm', methods=['GET', 'POST'])
def confirm():
resp = twilio.twiml.Response()
digits = request.values.get('Digits', None)
digits_spaced = ','.join(ch for ch in digits)
with resp.gather(numDigits=1, action=url_for('confirm_route', number=digits), method='GET') as g:
g.say('You entered the number ' + digits_spaced + '. If this is correct, press 1. Otherwise, press 2.',
voice=voice)
return str(resp)
@app.route('/api/confirm_route')
def confirm_route():
resp = twilio.twiml.Response()
digit = request.args.get('Digits', None)
if digit == '1':
number = request.args.get('number', None)
resp.redirect(url=url_for('text_or_call', number=number), method='GET')
return str(resp)
else:
resp.redirect(url=url_for('register'))
return str(resp)
@app.route('/api/text_or_call')
def text_or_call():
resp = twilio.twiml.Response()
number = request.args.get('number', None)
with resp.gather(numDigits=1, action=url_for('save_number', number=number), method='GET') as g:
g.say('If you would like to receive a text message, press 1. If you would like to receive a'
' phone call, press 2.', voice=voice)
return str(resp)
@app.route('/api/save_number')
def save_number():
resp = twilio.twiml.Response()
digit = request.args.get('Digits', None)
number = request.args.get('number', None)
if digit == '1':
text = True
elif digit == '2':
text = False
else:
resp.say(digit+' is not a valid choice.')
resp.redirect(url_for('text_or_call', number=number), method='GET')
return str(resp)
number = '+1' + number
utils.insert_to_db(number, text)
resp.say('Thank you. You will receive a notification at that number once the baby is born.', voice=voice)
resp.say('Goodbye.', voice=voice)
resp.hangup()
return str(resp)
@app.route('/notify', methods=['GET', 'POST'])
def notify():
global MESSAGE
sendmessage = False
born = False
client = TwilioRestClient(app.config['SID'], app.config['AUTHTOKEN'])
if request.form['Body'].startswith(app.config['LABOR_PHRASE']):
MESSAGE = request.form['Body'].replace(app.config['LABOR_PHRASE'], '', 1)
sendmessage = True
if request.form['Body'].startswith(app.config['BORN_PHRASE']):
MESSAGE = request.form['Body'].replace(app.config['BORN_PHRASE'], '', 1)
sendmessage = True
born = True
if sendmessage:
numbers = utils.get_all_numbers()
"""
If the baby is born, and the subscriber wants to get a phone call, call them. Otherwise text them.
"""
for number in numbers:
if born:
if number[1] == 0:
client.calls.create(to=number[0], from_=app.config['NUMBER'],
url=app.config['URL'] + ':' + str(app.config['PORT']) + '/api/notify')
else:
params = {'to': number[0], 'from_': app.config['NUMBER'], 'body': MESSAGE}
if request.form['NumMedia'] == '1':
params['MediaUrl'] = request.form['MediaUrl0']
client.messages.create(**params)
else:
params = {'to': number[0], 'from_': app.config['NUMBER'], 'body': MESSAGE}
if request.form['NumMedia'] == '1':
params['MediaUrl'] = request.form['MediaUrl0']
client.messages.create(**params)
resp = twilio.twiml.Response()
resp.message('Finished notifying all {} numbers'.format(len(numbers)))
return str(resp)
if request.form['Body'].lower().startswith('join'):
number = request.form['From']
utils.insert_to_db(number, True)
resp = twilio.twiml.Response()
resp.message('You have been signed up for %s birth notifications! You will receive a text once Emily goes into labor and when the baby is born!' % app.config['BABY_NICKNAME'])
return str(resp)
resp = twilio.twiml.Response()
resp.message('%s are busy right now. Stay tuned for more updates :)' % app.config['PARENTS_NAME'])
return str(resp)
@app.route('/api/notify', methods=['GET', 'POST'])
def notify_number():
resp = twilio.twiml.Response()
resp.pause(length=1)
resp.say('Hello, this is your %s update. %s' % (app.config['BABY_NICKNAME'], MESSAGE), voice=voice)
with resp.gather(numDigits=1, action=url_for('record_menu'), method='POST') as g:
g.say('If you would like to leave a message for the happy family, please press 1. '
'If you do not wish to leave a message, you may hang up.', voice=voice)
return str(resp)
@app.route('/api/record_menu', methods=['GET', 'POST'])
def record_menu():
digit = request.values.get('Digits', None)
if digit == '1':
return redirect(url_for('record'))
else:
resp = twilio.twiml.Response()
resp.say('Thank you. Goodbye.', voice=voice)
resp.hangup()
return str(resp)
@app.route('/api/record', methods=['GET', 'POST'])
def record():
resp = twilio.twiml.Response()
resp.say('Record your message after the tone. Make sure to state your name, and note '
'that the recording is only 30 seconds. When done, press the pound sign.', voice=voice)
resp.record(maxLength='30', action=url_for('handle_recording'), finishOnKey='#')
return str(resp)
@app.route('/api/handle_recording', methods=['GET', 'POST'])
def handle_recording():
#recording_url will contain a URI.
# Need to append the twilio URL, since the URI is in reference to it
recording_url = request.values.get('RecordingUrl', None)
print(recording_url)
resp = twilio.twiml.Response()
resp.say('Thank you for leaving a message! Goodbye.', voice=voice)
resp.hangup()
time.sleep(2)
filename = 'recordings/'+request.values.get('To', None)+'.mp3'
r = requests.get(recording_url+'.mp3', stream=True)
with open(filename, 'wb') as fd:
for chunk in r.iter_content():
fd.write(chunk)
return str(resp)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=app.config['PORT'], debug=True)