-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
executable file
·379 lines (298 loc) · 11.7 KB
/
server.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/python
from flask import Flask, request, redirect
import twilio.twiml
import random
import requests
import json
import omdb
from googleplaces import GooglePlaces, types, lang
from microsofttranslator import Translator
from yahoo_finance import Share
gp_api_key = 'AIzaSyAX_75N29J--rh3Qj9gXjMBVx9IuD_Um74'
google_places = GooglePlaces(gp_api_key)
bing_api_key = 'oeToVPEyRZIASRK2n2byOU1x0EMatLIpd8kCIvwXmMw'
# For TESTing -- START
from twilio.rest import TwilioRestClient
# For TESTing -- END
app = Flask(__name__)
# For TESTing -- START
def send_sms_to_jitesh(message):
# Credentials owner: [email protected]
# Find these values at https://twilio.com/user/account
account_sid = "ACe9748f2bce3601801167fa0791836c3e"
auth_token = "cef3bac7ba6d045c7e6cf4b6c21581eb"
client = TwilioRestClient(account_sid, auth_token)
message = client.messages.create(to="+918095718111", from_="+18779545971",
body=message)
# For TESTing -- END
noIntent = [
"I'm having trouble understanding you, could you rephrase your question?",
"I didn't catch that, could you rephrase your query?",
"Sorry, I didn't understand that. Try rephrasing your request."
]
@app.route("/no_intent", methods=['POST'])
def no_intent():
resp = twilio.twiml.Response()
message = random.choice(noIntent)
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/sos", methods=["POST"])
def sos(dict_response):
resp = twilio.twiml.Response()
query_text = dict_response["_text"].lower()
# remove sos prefix and clean location string
if query_text.find("sos ") != -1:
query_text = query_text[4:]
if query_text.find(" sos") != -1:
query_text = query_text[:-4]
if query_text.find("help ") != -1:
query_text = query_text[5:]
if query_text.find(" help") != -1:
query_text = query_text[:-5]
query_result = google_places.nearby_search(location=query_text, keyword='hospital', radius=5000, types=[types.TYPE_HOSPITAL])
number_of_places = 0
message = "List of Hospitals:\n"
for place in query_result.places:
if number_of_places < 3:
number_of_places += 1
message = message + place.name
place_info = place.get_details()
message = message + ", Ph: " + place.local_phone_number + "\n"
else:
break
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/weather", methods=['POST'])
def weather(entities):
resp = twilio.twiml.Response()
location = entities['location'][0]['value'].lower()
response = requests.get(url="http://api.openweathermap.org/data/2.5/weather?q=" + location + "&APPID=500d01a6ece6498b1cbf94ed23519119")
dict_response = json.loads(response.text)
temperature_in_celsius = round(dict_response['main']['temp'] - 273.15, 2)
humidity = dict_response['main']['humidity']
weather_description = dict_response['weather'][0]['description']
message = "The weather in " + location + ": " + weather_description + ". "
message += "The temperature is: " + str(temperature_in_celsius) + " C."
message += "The humidity is: " + str(humidity) + " %."
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/navigate", methods=['POST'])
def navigate(entities):
resp = twilio.twiml.Response()
destination = entities['to'][0]['value']
origin = entities['from'][0]['value'].lower()
key = "GSC5hkB0CEmUyk4nI2MY~HxNEzo1P1bHB1sX8EzDJpA~AmYeCHqvBerEI06DBSKWfo4pgB1w9Krgk7EH6lhGqqf3s5RaJArOzWJ-SL6AYVVw"
bingMapsResponse = requests.get(url="http://dev.virtualearth.net/REST/V1/Routes/Driving?wp.0=" + origin + "&wp.1=" + destination + "&avoid=minimizeTolls&key="+key)
bingMaps_dict = json.loads(bingMapsResponse.text)
resources = bingMaps_dict.get('resourceSets')[0].get('resources')
routeLegs = resources[0].get('routeLegs')
message = ""
distance = routeLegs[0].get('routeSubLegs')[0].get('travelDistance')
message += "Total Trip Distance: " + str(distance) + " km\n"
duration = routeLegs[0].get('routeSubLegs')[0].get('travelDuration')
message += "Total Trip Duration: " + str(duration/60) + " min \n"
itineraryItems = routeLegs[0].get('itineraryItems')
count = 1
for item in itineraryItems:
message += str(count) + ". " + item.get('instruction').get('text') + " ("
message += str(item.get('travelDistance')) + " km, "
message += str(item.get('travelDuration') / 60 ) + " min)"
message += "\n"
count +=1
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/translate", methods=['POST'])
def translate(entities):
resp = twilio.twiml.Response()
message = ""
text_for_translation = entities['phrase_to_translate'][0]['value']
language = entities['language'][0]['value'].lower()
if language == "spanish":
language = "es"
elif language == "french":
language = "fr"
elif language == "german":
language = "de"
elif language == "chinese":
language = "zh-CHS"
else:
message = "Language not supported!"
if message != "Language not supported!":
message = "Translation for " + text_for_translation + " to " + language + ":\n"
translator = Translator('SMSAssistant', 'fhV+AdYFiK0QfQ4PFys+oQ/T0xiBBVQa32kxxbP55Ks=')
message += translator.translate(text_for_translation, language)
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/news", methods=['POST'])
def getNews(entities):
resp = twilio.twiml.Response()
newstopic = entities['news_topic'][0]['value'].lower()
# default topic
if newstopic is None:
newstopic = "world"
response = requests.get(url='https://api.datamarket.azure.com/Bing/Search/News?$format=json&Query=%27' + newstopic + "%27", \
auth=(bing_api_key, bing_api_key))
news_dict = json.loads(response.text)
news = news_dict.get('d').get('results')
message = ""
if len(news) >= 5:
message = "Here are the top 5 stories about " + newstopic + ":\n"
for x in range(0, 5):
message += str(x+1) + ". " + news[x].get('Title') + ".\n"
else:
message = "Here are the top news stories about " + newstopic + ":\n"
for item in news:
message += "- " + item.get('Title') + "\n"
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/imdb", methods=['POST'])
def imdb(dict_response):
resp = twilio.twiml.Response()
query_text = dict_response['_text'].lower()
if query_text.find("imdb ") != -1:
query_text = query_text[5:]
response = omdb.request(t='' + query_text + '', r='json')
data = json.loads(response.text)
message = ""
mediatype = data["Type"]
year = data["Year"]
title = data["Title"]
if mediatype == "movie":
message += "Found a Movie, \"" + title + "\" (" + year + ")\n"
elif mediatype == "series":
message += "Found a TV show, \"" + title + "\" (" + year + ")\n"
for key in data:
if key in ["Rated", "Runtime", "Genre", "Director", "Writer"]:
if data[key] != "N/A":
message += key + ": " + data[key] + "\n"
if key == "imdbRating":
message += "IMDB: " + data[key] + "\n"
if data["Plot"] != "N/A":
message += "Plot: " + data["Plot"]
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/stocks", methods=['POST'])
def stocks(dict_response):
resp = twilio.twiml.Response()
query_text = dict_response['_text'].lower()
if query_text.find("stocks ") != -1:
query_text = query_text[7:]
message = ""
y = Share(query_text)
message += "Trading information for " + y.get_name() + " (" + query_text + ") :\n"
message += "Opened: " + y.get_open() + "\n"
message += "Current: " + y.get_price() + "\n"
message += "Earnings share: " + y.get_earnings_share() + "\n"
message += "Short ratio: " + y.get_short_ratio() + "\n"
message += "Previous close: " + y.get_prev_close() + "\n"
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
@app.route("/atm", methods=['POST'])
def atm(dict_response):
resp = twilio.twiml.Response()
query_text = dict_response['_text'].lower()
if query_text.find("atm near ") != -1:
query_text = query_text[9:]
query_result = google_places.nearby_search(location=query_text, keyword='atm', radius=5000, types=[types.TYPE_ATM])
number_of_places = 0
message = ""
for place in query_result.places:
if number_of_places < 5:
number_of_places += 1
message = message + place.name
place_info = place.get_details()
if place.local_phone_number != None:
message = message + " " + place.local_phone_number
message = message + "\n"
else:
break
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/define", methods=['POST'])
def define(dict_response):
resp = twilio.twiml.Response()
query_text = dict_response['_text'].lower()
if query_text.find("define ") != -1:
topic = query_text[7:]
r = requests.get(url='http://api.duckduckgo.com/?q=' + topic + '&format=json&pretty=1')
message = ""
topic_response = json.loads(r.text)
all_definitions = topic_response['RelatedTopics']
if len(all_definitions) > 0:
top_definitions = all_definitions[0]
definition = top_definitions['Text']
message = topic + " is defined as " + definition
else:
message = "Definition not found"
resp.message(message)
# For TESTing -- START
send_sms_to_jitesh(message)
# For TESTing -- END
return resp
@app.route("/sms", methods=['GET', 'POST'])
def sms():
message_body = request.values.get('Body', None)
# Remove annoying text prefix announcing trial version
prefix = "Sent from your Twilio trial account - "
if prefix in message_body:
message_body = message_body[len(prefix):]
response = requests.get(url='https://api.wit.ai/message?v=20161022&q='+message_body,headers={'Authorization': 'Bearer TUDKLORVVMITDT4FCJFMAARQAWB2NLJ2'})
dict_response = json.loads(response.text)
intent = None
confidence = None
entities = None
msg = None
if dict_response['entities']['intent']:
intent = dict_response['entities']['intent'][0]['value']
confidence = dict_response['entities']['intent'][0]['confidence']
entities = dict_response['entities']
if intent is None or confidence < 0.2:
msg = no_intent()
elif intent == "weather":
msg = weather(entities)
elif intent == "navigate":
msg = navigate(entities)
elif intent == "sos":
msg = sos(dict_response)
elif intent == "translate":
msg = translate(entities)
elif intent == "news":
msg = define(entities)
elif intent == "imdb":
msg = imdb(dict_response)
elif intent == "atm":
msg = atm(dict_response)
elif intent == "stocks":
msg = stocks(dict_response)
elif intent == "define":
msg = define(dict_response)
else:
msg = "Feature not supported"
return str(msg)
if __name__ == "__main__":
app.run(debug=True)