-
Notifications
You must be signed in to change notification settings - Fork 0
/
application.py
196 lines (151 loc) · 6.34 KB
/
application.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
from flask import redirect, request, render_template, Response, session
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql.expression import func
from functools import wraps
from sms_swap import create_app
from sms_swap.config import CONFIG_VARS
from sms_swap.models import Answer
from sms_swap.database import db
import twilio.twiml
from twilio.rest import TwilioRestClient
application = create_app()
@application.route("/")
def index():
# TODO: grab some recordings to show
return render_template('index.html')
@application.route("/respond", methods=['GET', 'POST'])
def respond():
"""Respond to incoming texts"""
resp = twilio.twiml.Response()
incoming_msg = request.values.get('Body', '')
# this clears all cookies
if(incoming_msg.lower()=='clear'):
session['seen_intro'] = False
session['seen_prompt'] = False
session['gave_ans'] = False
session['extra_msg'] = False
resp.sms("erasing my memory of our conversation")
return str(resp)
# # if exchange has been completed
# if session.get('extra_msg',False):
# session['extra_msg'] = False
# if incoming_msg.lower().startswith('y'):
# session['seen_prompt'] = False
# session['gave_ans'] = False
# elif incoming_msg.lower().startswith('n'):
# # TODO: ask for feedback?
# resp.sms('ok, later!')
# return str(resp)
if not session.get('seen_prompt',False):
# if this is the original interaction with a bot
if not session.get('seen_intro', False):
resp.sms("hello, stranger! I'm a fortune cookie SMS bot.\n\nwant a random fortune? reply by writing a fortune for someone else to crack open!")
session['seen_intro'] = True
# if the user is submitting additional fortunes
else:
resp.sms("want a random fortune? reply by writing a fortune for someone else to crack open!")
session['seen_prompt'] = True
elif not session.get('gave_ans',False):
# saving answer here
if incoming_msg: # only if there is a msg
new_ans = Answer(request.values.get('SmsSid'), request.values.get('From'), incoming_msg)
# TODO: error handling here
db.session.add(new_ans)
db.session.commit()
# grabbing a fortune from a stranger
# TODO: ensure that this is not a fortune from yourself
random_ans = Answer.query.filter_by(is_approved=True)\
.filter((Answer.from_number!=request.values.get('From'))|(Answer.from_number == None))\
.order_by(func.rand())\
.first()
if random_ans:
resp.sms("excellent, I'll sneak that into someone else's fortune cookie. here's your fortune:\n\n%s" %random_ans.answer_text)
if incoming_msg: # only if there is a msg
random_ans.view_count = random_ans.view_count+1
db.session.add(random_ans)
db.session.commit()
# alerting rec-giver when rec has been seen for the first time
if random_ans.from_number and random_ans.view_count==1:
client = TwilioRestClient(
CONFIG_VARS['TWILIO_ACCOUNT_SID'],
CONFIG_VARS['TWILIO_AUTH_TOKEN']
)
msg = "your fortune (%s) was just delivered to a stranger!" %random_ans.answer_text
message = client.messages.create(
to=random_ans.from_number,
from_=CONFIG_VARS['TWILIO_PHONE_NO'],
body=msg
)
else:
resp.sms("excellent, I'll sneak that into someone else's fortune cookie. here's your fortune:\n\n404 FORTUNE NOT FOUND")
session['gave_ans'] = True
elif not session.get('extra_msg',False):
session['extra_msg'] = True
resp.sms("if you want another fortune, text me again tomorrow!")
else:
return ''
return str(resp)
@application.route("/rollback", methods=['GET', 'POST'])
def rollback():
# TODO: figure out what's going on???
db.session.rollback()
return redirect('/respond')
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == CONFIG_VARS['ADMIN_USER'] and password == CONFIG_VARS['ADMIN_PASS']
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your credentials for that url', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
@application.route('/review')
@requires_auth
def review():
review_queue = Answer.query.filter_by(is_approved=None).all()
approved = Answer.query.filter_by(is_approved=True).all()
return render_template('review.html', review_queue = review_queue, approved=approved)
@application.route('/reviewtrash')
@requires_auth
def reviewtrash():
disapproved = Answer.query.filter_by(is_approved=False).all()
return render_template('reviewtrash.html', disapproved=disapproved)
@application.route('/approve/<ans_id>')
@requires_auth
def approve(ans_id):
ans = Answer.query.get(ans_id)
ans.is_approved = True
db.session.commit()
return redirect('/review')
@application.route('/disapprove/<ans_id>')
@requires_auth
def disapprove(ans_id):
ans = Answer.query.get(ans_id)
ans.is_approved = False
db.session.commit()
return redirect('/review')
@application.route('/addfortune', methods=['GET', 'POST'])
@requires_auth
def add_fortune():
if request.method == 'POST':
new_ans = Answer(None, None, request.form['fortune-text'])
new_ans.is_approved = True
db.session.add(new_ans)
db.session.commit()
return render_template('addfortune.html')
@application.route('/initialize')
@requires_auth
def initialize():
db.create_all()
return redirect('/')
if __name__ == "__main__":
application.run(host='0.0.0.0')