-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathtasks.py
2460 lines (1789 loc) · 114 KB
/
tasks.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#----------------------------------------Background worker process----------------------------------------#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
# Important #
# if you have any questions about this code which aren't answered below, check the app.py file in this same
# repository which has more notes.
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
#!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- Imports ---#
# Throughout this program we call the below imports for various actions
# failing to import one of these libraries, or importing the wrong one
# may be one reason for an app just failing mid-process
# All of these libraries need to be reflected in our requirements file
# which we upload as part of our app
import celery
from celery import Celery
app = celery.Celery('example')
import os
from slackclient import SlackClient
from flask import Flask, make_response, request
import gspread
import oauth2client
from datetime import datetime, time, date, timedelta
from oauth2client.service_account import ServiceAccountCredentials
import json
import os.path
import sys
import requests
import re
try:
import apiai
except ImportError:
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import apiai
from collections import Counter
import time
import tasks
import psycopg2
from flask.ext.sqlalchemy import SQLAlchemy
#Thanks to http://blog.y3xz.com/blog/2012/08/16/flask-and-postgresql-on-heroku
import urllib.parse
#Thanks to https://stackoverflow.com/questions/45133831/heroku-cant-launch-python-flask-app-attributeerror-function-object-has-no
#--- End of imports ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#===========================================================================================================================#
#---------------------------------------------------------------------------------------------------------------------------#
#===========================================================================================================================#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- Environment variables ---#
# For everything in this block, make sure you have created
# an environment variable with a name identical to the green
# quoted text (on heroku the REDIS ones will be done for you).
# Instructions for how to create environment variables in Heroku are at (https://devcenter.heroku.com/articles/config-vars)
# Environment variables are a way of protecting important
# pieces of information, particularly if you are sharing
# the code. Rather than writing out a bunch of passwords
# you save them elsewhere and you can refer to them here
# it can be a way of saving important information without
# having to create a database however if someone gets acess
# to your application and knows what they are called they will
# be able to get that information (though if they have got that
# far it's a bit of a problem anyway).
#Slack variables
#
# We set these variables based on information from our Slack bot
client_id = os.environ["SLACK_CLIENT_ID"]
client_secret = os.environ["SLACK_CLIENT_SECRET"]
#
#-#
# Celery variables
# Thanks to (https://devcenter.heroku.com/articles/celery-heroku, for another good resource on celery and flask, but which had to be modified due to clash with database, go to https://blog.miguelgrinberg.com/post/using-celery-with-flask)
app.conf.update(BROKER_URL=os.environ['REDIS_URL'],
CELERY_RESULT_BACKEND=os.environ['REDIS_URL'])
# Authentication for sending message to API.AI
api_bearer = os.environ["API_BEARER"]
# The location of the google sheet (so the link isn't shared with everyone)
google_sheet_url= os.environ["GSHEET_ID"]
#--- End of environment variables ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#===========================================================================================================================#
#---------------------------------------------------------------------------------------------------------------------------#
#===========================================================================================================================#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- w1 add - async task caled by main process, testing call working ---#
@app.task
def add(app_code,location_code,x, y):
print (app_code,location_code,"begun")
print (app_code,location_code,"answer is", x+y)
return x + y
#--- End of test ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
# w2 send_to_api - takes information from Slack message and converts it into a request to API.AI (not a response to an API.AI request)
@app.task
def send_to_api(event_id, user_id, channel, query):
#Process for taking message and sending important info to API.AI
#------------------------------------------------------------#
# Setting location codes, these will be used in print commands
# so we can easily keep track of where things are. The only
# purpose of these is to be included in the print commands
# however if they are removed the app will break at the first
# print
#------------------------------------------------------------#
app_code="async "
location_code="w1 (startup)"
#------------------------------------------------------------#
# End of setting location codes
#------------------------------------------------------------#
#Printing out all the information we have to confirm we've got everything
print (app_code,location_code," activated with 'send_to_api' function")
print (app_code,location_code," received event_id: ", event_id)
print (app_code,location_code," received user: ", user_id)
print (app_code,location_code," received channel: ", channel)
print (app_code,location_code," received query: ", query)
session_id=user_id
print (app_code,location_code," received session_id: ", session_id)
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- w1.1 check to make sure the message we received isn't a duplicate of the last ---#
# Finding out whether the current query is within two minutes of the last one
# (thanks to https://stackoverflow.com/questions/6205442/python-how-to-find-datetime-10-mins-after-current-time
# and https://stackoverflow.com/questions/10048249/how-do-i-determine-if-current-time-is-within-a-specified-range-using-pythons-da
location_code="w1.1 (deduplication)"
open_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database connection open ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
# Checking our database to find the variables we save each time
# the last exact message received, the last action saved for a user_id
# and the last time we received a message from that user
most_recent_query=check_database(app_code,location_code,user_id, 'most_recent_user_query')
most_recent_action=check_database(app_code,location_code,user_id, 'most_recent_action_for_user')
print (app_code,location_code, user_id," most recent query is ", most_recent_query)
# Retrieving the time it is now, then calculating what time
# it would have been one minute ago
now = datetime.now()
print (app_code,location_code," now is ", now)
one_minute_ago=datetime.now()-timedelta(minutes=1)
print (app_code,location_code," one minute ago is: ", one_minute_ago)
# Creating existing_query_list and duplicate_query variables now so that
# program doesn't fall over when we check whether the value is "yes" or
# "no" later. You'll see what these demark further on in the process.
# We could potentially deal with this by instead checking whether the
# variable exists further on but this seems more deliberate.
within_last_query_window="no"
existing_query_list="no"
duplicate_query="no"
if "||" in most_recent_query:
# If there are no strings that contain the delimiters we
# add when we receive a message it is the first message
# so we don't need to worry about deduping
print (app_code,location_code," query list contains ||")
most_recent_query_list=most_recent_query.split("||")
existing_query_list="yes"
print (app_code,location_code," query list split: ", most_recent_query_list)
list_position=0
for x in most_recent_query_list:
# The database will return up to 10 most recent queries
if "--" in x:
print (app_code,location_code," query contains --")
query_pair=x.split("--")
past_query=query_pair[0]
print (app_code,location_code," query checking against is: ", past_query)
print (app_code,location_code," query sent is: ", query)
past_query_time_string=query_pair[1]
print (app_code,location_code," time checking against is: ", past_query_time_string)
print (app_code,location_code," threshold is: ", one_minute_ago)
# converting datestamp string into queryable timestamp thanks to https://stackoverflow.com/questions/12672629/python-how-to-convert-string-into-datetime
past_query_time_stamp=datetime.strptime(past_query_time_string, "%Y-%m-%d %H:%M:%S.%f")
print (app_code,location_code," time converted to timestamp is: ", past_query_time_stamp)
if one_minute_ago < past_query_time_stamp:
# If less than one minute have passed since
# last query it's more likely to be duplicate
print (app_code,location_code," less than one minute since last recorded action")
within_last_query_window='yes'
if query==past_query:
# If the current query is identical to the last query
# then it's a sign that we've had a repeated request
# from Slack
print (app_code,location_code," query is duplicate of last")
duplicate_query="yes"
# Here, regardless of whether the query is duplicate or not, we are updating
# our list of recent queries with the current time, this should mean that duplicate
# queries will always be removed (this is why we can keep the checked time period so short)
# we run the next section to remove the last query and replace it with this most recent one
if list_position==0:
print (app_code,location_code," list position==0")
# If the duplicate item is the first in the list then we replace that item
previous_queries=most_recent_query_list[-15:]
# Joining list elements into string (example here: https://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings)
query_record=query+"--"+str(now)
new_query_list=query_record+"||"+("||".join(previous_queries))
print (app_code,location_code," new query list is: ", new_query_list)
else:
print (app_code,location_code," list position!=0")
# If the duplicate item is more than 0 we split the list to remove that item and
# replace it with the new one
query_record=query+"--"+str(now)
pre_duplicate=list_position-1
post_duplicate=len(most_recent_query_list)-(list_position+1)
print (app_code,location_code," position is ", post_duplicate, "before end of list")
previous_queries_pre=most_recent_query_list[0:pre_duplicate]
print (app_code,location_code," items before are ", previous_queries_pre)
previous_queries_post=most_recent_query_list[-post_duplicate:]
print (app_code,location_code," items after are ", previous_queries_post)
new_query_list=("||".join(previous_queries_pre))+"||"+query_record+"||"+("||".join(previous_queries_post))
print (app_code,location_code," new query list is: ", new_query_list)
# breaking out of for loop (thanks to https://www.tutorialspoint.com/python/python_break_statement.htm)
break
# We're using this to keep track of where we are in the list that we've saved
# if the item matches all of our conditions as above it won't hit this block to
# increase the value of list_position
list_position=list_position+1
else:
# If more than one minute have passed we're
# assuming it's not a repeated send from Slack
# this allows a user to place exactly the same
# order without having to worry about varying
# their wording
print (app_code,location_code," more than one minute since last recorded action")
# We're using this to keep track of where we are in the list that we've saved
# if the item matches all of our conditions as above it won't hit this block to
# increase the value of list_position
list_position=list_position+1
if existing_query_list!='yes':
print (app_code,location_code," query list doesn't contain ||")
print (app_code,location_code,"query is: ", query, " recalled query list is: ", most_recent_query)
query_record=query+"--"+str(now)
new_query_list=query_record+"||"
else:
if within_last_query_window!='yes' or duplicate_query!='yes':
print (app_code,location_code,"not a duplicate query")
# If EITHER there are no duplicate queries or the duplicate queries didn't occur within
# our window then we just drop the earliest item from our list and add the newest query
query_record=query+"--"+str(now)
# Joining list elements into string (example here: https://stackoverflow.com/questions/12453580/concatenate-item-in-list-to-strings)
new_query_list=("||".join(most_recent_query_list[1:15]))+"||"+query_record
print (app_code,location_code," new query list is: ", new_query_list)
if not new_query_list:
print (app_code,location_code,"there is a problem - new_query_list hasn't been defined")
# Using update_columns process to record most recent
# query for future checks
update_columns(app_code,location_code,['most_recent_user_query',new_query_list], user_id)
if within_last_query_window=='yes':
if duplicate_query=="yes":
print (app_code,location_code," replaced duplicate query")
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed within if ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#----- Process ended because repeat message -----#
location_code="w1.2 (genuine message)"
print (app_code,location_code," recorded unique query")
#--- End of w1.1 check to make sure the message we received isn't a duplicate of the last ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- w2 Check database for existing record data ---#
location_code="w2 (check for record)"
# Retrieving any saved user name for the user id that we have been given by the main process
user_name=check_database(app_code,location_code,user_id, "user_name")
print (app_code,location_code,"finished checking for user at ")
# This ignored_value is to allow debugging, when you are testing and asked for your
# username, set it to match this value, then every time you use the application you
# will be asked again
ignored_value="Sean"
# When we create users through the Slack authorisation process (in our main app)
# we save the user token in our database, now we use our check database process
# to retrieve it, allowing us to post to any Slack channel they permiss
user_token=check_database(app_code,location_code,user_id, 'user_token')
bot_token=check_database(app_code,location_code,user_id, "bot_token")
print (app_code,location_code," bot token is: ", bot_token)
#--- End of w2 Check database for existing record data ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.0 start interaction with API.AI ---#
location_code="w3.1 (contact api)"
print (app_code,location_code,"web - user_name is ",user_name)
if user_name!=None and user_name!=ignored_value:
# Setting the information we're sending to API.AI if there IS a name (ignoring our ignored value)
data="{'query':'"+query+"', 'lang':'en', 'contexts':[{ 'name': 'internal', 'parameters':{'moniker': '"+user_name+"'}, 'lifespan': 4}], 'sessionId':'"+session_id+"'}"
else:
# Setting the data we're sending to API.AI if there ISN'T a name
data='{\'lang\':\'en\',\'sessionId\':'+session_id+',\'query\':\''+query+'\',\'originalRequest\':{\'source\':\'slack\',\'data\':{\'event\':{\'channel\':\''+channel+'\',\'user\':\''+user_id+'\'}}}}'
# Activating process for sending query to API.AI (see "synchronous functions" section at bottom)
response=send_query(app_code,location_code,data)
#--- End of W3.0 start interaction with API.AI ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.1 receive response from API.AI ---#
# We actually got the response at the end of the last step, we called for it when we wrote
# "response=" so now we're just pulling out the information
location_code="w3.2 (receive api response)"
print (app_code,location_code,"Successfully posted to API.AI")
# Processing pulling info from closed return response from API.AI
# this closed loop means we don't need to worry so much about messages getting waylaid
# this process only sends to Slack when it has received the correct message from
# API.AI
print (app_code,location_code," response from API.AI: ", response)
print (app_code,location_code," response content: ", response.content)
api_response = response.json()
# Pulling out the portion of the response called "result" which
# contains much of the information we need
api_response_result=api_response.get("result")
print (app_code,location_code," got result")
# In API.Ai you can a response that it will give for certain inputs
# so for example, when someone asks for food, our API.AI setup can
# respond that it'll write that down. In this app we overwrite those
# responses with our own text but if you don't want to you can just
# find "speech" within "fulfillment" in the response (as below)
fulfillment=api_response_result.get("fulfillment")
speech_to_send=fulfillment.get("speech")
print (app_code,location_code," speech to send: ",speech_to_send)
# We set actions in API.AI as a shorthand for what should be done
# in this application if the user is asking for food in the formatted
# "I want food" we set "food" as action, so when we get a message with
# the action "food" we know we need to run through the food process, whereas
# if if we see that we've set the action "name-is" we know we need to run
# through the process of setting a user name
action=api_response_result.get("action")
print (app_code,location_code," action is: ", action)
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.2 action is food ---#
if action=="food":
# If the user says "I want [food]" and isn't within another context we have set
# API.AI will find the [food] value for us, save it in contexts and set the action "food"
# so we know where to look
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.2.1 action is food and we don't have a user name ---#
if user_name==None or user_name==ignored_value:
location_code="w3.2.1 (food no-name)"
# If the user hasn't used the application before we want them to set their username
# as a first step. So if they have asked for food but we don't have a username, instead
# of communicating with the user straight away we go back to API.AI and create an event
# which tells it to expect a user name next, THEN we go back to the user and ask for
# their name
# Sending no-name event to API.AI (thanks to https://api.ai/docs/events#invoking_event_from_webhook)
# this data is of a different format to the text we sent before - if you include an "event" as below
# API.AI doesn't need text.
data='{\'event\':{ \'name\': \'food-no-name\', \'data\': {\'source\': \'slack\'}}, \'lang\':\'en\', \'sessionId\':\''+user_id+'\'}'
# Printing what we're sending for debugging
print (app_code,location_code," data is: ",data)
print (app_code,location_code,"sending message to API.AI")
# Sending second consecutive message to API.AI to prepare it
# for when the user gives their name
# Activating process for sending query to API.AI (see "synchronous functions" section at bottom)
response_2=send_query(app_code,location_code,data)
# Gathering the data from the response the same way that
# we did from the first response
print (app_code,location_code,"response_2: ", response_2)
print (app_code,location_code,"response_2 content: ", response_2.content)
api_response_2 = response_2.json()
# Getting the "result" the same way we did before
api_response_result_2=api_response_2.get("result")
print (app_code,location_code,"w3 - got result")
# Getting fulfillment and API.AI's speech response
# as we did before
fulfillment_2=api_response_result_2.get("fulfillment")
speech_to_send=fulfillment_2.get("speech")
# This time we use the speech that API.AI has sent to us
# we defined this speech in the API.AI platform in the response
# section
print (app_code,location_code,"speech to send",speech_to_send)
# At this point getting the "action" isn't important for the function
# of our program, because it should only ever reach this point if API.AI
# is sending the response to the event we created above, which should
# always be the same, we're getting it and printing it for debugging.
action_2=api_response_result_2.get("action")
print (app_code,location_code,"w speech_to_send - action_2 is ", action_2)
# Sending message to slack which includes the defined speech from API.AI
# The user token is what we got from our database earlier in the process
# and will make Slack accept the messages we're sending.
# This process is from https://api.slack.com/methods/chat.postMessage, there
# is also a form-based message tester available on that page so you can test and debug
params = (
('token', user_token),
('channel', channel),
('text', speech_to_send),
('username', 'vietnambot'),
('icon_emoji', ':rice:'),
('pretty', '1'),
)
requests.get('https://slack.com/api/chat.postMessage', params=params)
print (app_code,location_code,"sent to Slack")
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed WITHIN IF ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#
#
#--- End of W3.2.1 action is food and we don't have a user name ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.2.2 action is food and we DO have a user name ---#
#
#
if user_name!=None and user_name!=ignored_value:
# This is for the eventuality that we have the user name saved
location_code="w3.2.2 (food yes-name)"
print (app_code,location_code,"user_id: ", user_id)
print (app_code,location_code,"user_name: ", user_name)
# The contexts is where API.AI saves the information for us
contexts = api_response_result.get("contexts")
print (app_code,location_code," contexts is: ", contexts)
# Here we are running through all of the "contexts" one by one - essentially information API.AI has stored for us
# 'name' does not mean user name, it means the name of the context we are accessing
# the code means, for every item in the list called contexts, do the following things to that item
for context in contexts:
name=context.get("name")
# Here we COULD access "food.original", this would work if we didn't have to ask for any other information,
# however, we have set API.AI to save the food information in the "food-followup" context so this information is
# there regardless of other information asked, this is basically making the application more robust
if name == "food-followup":
# Accessing the information within the context
parameters=context.get("parameters")
# Finding the food field and naming it
food=parameters.get("food")
print (app_code,location_code,"web - food: ", food, datetime.utcnow())
# This is sending all the information we've gathered to a worker proces which can now update
# our Google sheet and update the user. We're doing this asynchronously because the GSheet api is
# too slow, we need to respond to API.AI in the short term and fortunately we can just send an
# extra update to Slack once that's done. If we were working with speech a platform like Google Home
# or Amazon Alexa this would not be possible
# Getting the speech that has been sent back from API.AI
api_response = response.json()
api_response_result=api_response.get("result")
print (app_code,location_code," got result")
fulfillment=api_response_result.get("fulfillment")
speech_to_send=fulfillment.get("speech")
print (app_code,location_code," speech to send",speech_to_send)
# The team_id is important because if multiple teams were using
# this application, each updating their own order list, we would need
# to calculate who is ordering most differently for each so we use team_id
# to identify this teams top orderer (here called top_nommer)
team_id=check_database(app_code,location_code,user_id, 'team_id')
# Updating our database with the latest order so that it can be called
# at other times
update_columns(app_code,location_code,['most_recent_user_food',food],user_id)
# Look in the synchronous functions section at the bottom of this code
# for what this does
process_food(app_code,location_code,food, channel, user_token, user_name, user_id, session_id, team_id, bot_token)
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed WITHIN IF ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#
#
#--- End of W3.2.2 action is food and we DO have a user name ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#
#
#--- End of W3.2 action is food ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.3 action is food-fallback ---#
#
# This is the case that the user hasn't said "I want [food]" or anything else that
# matches our intents. Fallback is a catch all in API.AI that can have greater or lesser
# scope to deal with statements that fall outside of what we have prepared for. We are assuming,
# based on the narrow use of this app, that if a user just says something it will be the food
# they want to order so we haven't put any necessary input contexts on this.
# More complex applications will need more sophisticated fallback functions involving more contexts
if action=="food-fallback":
# Because this is a fallback intent with no context we can't trust that we've properly interpreted
# the information so we have an instruction in API.AI asking user to give a food request that we're set up
# to interpret (see the top of app.py for how we respond to food-fallback and how we interpret food)
# Sending message to slack which includes the speech_to_send which we got from from API.AI before
# The user token is what we got from our database earlier in the process
# and will make Slack accept the messages we're sending.
# This process is from https://api.slack.com/methods/chat.postMessage, there
# is also a form-based message tester available on that page so you can test and debug
params = (
('token', user_token),
('channel', channel),
('text', speech_to_send),
('username', 'vietnambot'),
('icon_emoji', ':rice:'),
('pretty', '1'),
)
requests.get('https://slack.com/api/chat.postMessage', params=params)
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed WITHIN IF ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#
#
#--- End of W3.3 action is food-fallback ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
print (app_code,location_code,"action isn't food or food-fallback")
if action=="name-is" or action=="name-confirmation":
print (app_code,location_code,"action is defining name")
# As part of the logic in our worker process if we don't already have the user's name, we ask for it
# We have primed API.AI to wait for this name and when it comes, send it with the "name-is" action
# There is also the possibility that users will say something other than their username so we have
# included a fallback intent. That requires different processing so we haven't bundled it here, however
# we HAVE bundled "name-confirmation" which occurs when the user confirms that what they said was their
# username, because the processing is similar.
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.4 action is name-is ---#
#
# This is the case where the user says something like "My name is [name]"
# because we have put API.AI in the context where it's expecting a name
# this is very easy for it to interpret and it saves the name for us in contexts
if action == "name-is":
location_code="w3.4 (name-is)"
print (app_code,location_code," action is name-is ")
# Contexts is where API.AI saves the information for us
contexts = api_response_result.get ("contexts")
# Here we are running through all of the "contexts" one by one - essentially information API.AI has stored for us
# 'name' does not mean user name, it means the name of the context we are accessing
# the code means, for every item in the list called contexts, do the following things to that item
for context in contexts:
name=context.get("name")
# Because the user sent the food they want in their FIRST message, not the one we're
# dealing with at the moment, we just need to check the context that API.AI saved at that point
# and use that value. We could also have saved this value to our database then but that's unecessary
# work as API.AI takes care of this for us.
# As above, we can continue to use the food-followup context because this won't change too quickly
if name == "food-followup":
parameters=context.get("parameters")
food=parameters.get("food")
print (app_code,location_code,"web - food:", food)
# We called the context where we save the name in this instance 'name-is' so that is where
# API.AI has put this information for us
if name == "name-is":
parameters=context.get("parameters")
user_name=parameters.get("user_name")
print (app_code,location_code,"web - name to be set as: ", user_name)
#Updating our database with the new information
update_columns(app_code,location_code,['user_name',user_name,'most_recent_user_channel',channel,'most_recent_user_session_id',user_id,'most_recent_action_for_user','process_food','most_recent_user_food',food],user_id)
#Notice we don't include "return" here - once we hit this point the code skips over "else" and keeps running until it gets to "return"
# this is because we have the same information here regardless of whether it's "name-is" or "name-fallback" so doing it this way
# means we only write the next bit of code once
else:
#--- End of W3.4 action is name-is ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.5 action is name-confirmation ---#
#
if action=="name-confirmation":
location_code="w3.5 (name-confirmation)"
# Contexts is where API.AI saves all our information for us
contexts = api_response_result.get ("contexts")
print (app_code,location_code," contexts are: ", contexts)
for context in contexts:
name=context.get("name")
# Because the user sent the food they want in their FIRST message, not the one we're
# dealing with at the moment, we just need to check the context that API.AI saved at that point
# and use that value. We could also have saved this value to our database then but that's unecessary
# work as API.AI takes care of this for us.
# As above, we can continue to use the food-followup context because this won't change too quickly
if name == "food-followup":
parameters=context.get("parameters")
food=parameters.get("food")
print (app_code,location_code,"food is", food)
# Here, because the user has confirmed that this is their name, we are retrieving the context
# that we set in the name-fallback response (in the if block directly above this). API.AI
# saved that information for us under the name we supplied.
if name == "potential-name":
parameters=context.get("parameters")
user_name=parameters.get("name")
print (app_code,location_code,"name is", user_name)
# Updating our database with the confirmed name
update_columns(app_code,location_code,['user_name',user_name,'most_recent_user_channel',channel,'most_recent_user_session_id',user_id,'most_recent_action_for_user','process_food','most_recent_user_food',food],user_id)
print (app_code,location_code," finished adding user ")
# Notice we don't include "return" here - once we hit this point the code just runs the next few lines it gets to "return"
# this is because we have the same information here regardless of whether it's "name-is" or "name-fallback" so doing it this way
# means we only write the next bit of code once
# The team_id is important because if multiple teams were using
# this application, each updating their own order list, we would need
# to calculate who is ordering most differently for each so we use team_id
# to identify this teams top orderer (here called top_nommer)
print (app_code,location_code,"checking for team_id")
team_id=check_database(app_code,location_code,user_id, 'team_id')
# Starting the process of putting the order into the spreadsheet
# the process_food includes sending messages to Slack so we don't
# need to include any confirmation messages here
print (app_code,location_code," got team_id, starting process_food process")
process_food(app_code,location_code,food, channel, user_token, user_name, user_id, session_id, team_id, bot_token)
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database completely closed =============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
# HERE we include return, which ends our process
return
#--- End of W3.5 action is name-confirmation ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.6 action is name-fallback ---#
#
# This is the case that the user hasn't said "I am [name]" or anything else that
# matches our intents. Because we've just asked for a name it's quite likely that
# they have just said it, however we need to check
if action == "name-fallback":
location_code="w3.6 (name-fallback)"
print (app_code,location_code," action is name-fallback")
# Because this is fallback we can't assume that the string given is
# necessarily the users name so we need to save it to API.AI and check
# with the user whether that is correct (importantly we don't save this
# value to our database at this point because if the user doesn't respond
# that it's incorrect in time the session might end and it would be harder
# to set the proper name)
user_name=api_response_result.get("resolvedQuery")
print (app_code,location_code," potential user name is ", user_name)
data = '[\n {\n "name": "potential-name",\n "lifespan": 1,\n "parameters": {\n "name": "'+user_name+'"\n }\n }\n]'
print (app_code,location_code," user_id is ", user_id, "data is", data)
response_2=send_contexts(app_code,location_code,user_id,data)
print (app_code,location_code," response is: ", response_2)
print (app_code,location_code," response content: ", response_2.content)
speech_to_send="I think you've asked me to create a user name of: "+user_name+" is that right?"
params = (
('token', user_token),
('channel', channel),
('text', speech_to_send),
('username', 'vietnambot'),
('icon_emoji', ':rice:'),
('pretty', '1'),
)
requests.get('https://slack.com/api/chat.postMessage', params=params)
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed WITHIN IF ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#--- End of W3.6 action is name-fallback ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.7 action is name-incorrect ---#
# This is when the user responds to our name-fallback check by expressing in some way that
# we got it wrong. We could have a complex process for managing this but for simplicity here
# we just loop back to when we first asked for the user name. To do this, we use API.AI's contexts.
# We make sure that this only outputs the food-followup and no-name contexts, and use the speech we've
# set in API.AI as our response (see the top of app.py for how we set up API.AI)
if action=="name-incorrect":
location_code="w3.7 (name-incorrect)"
# We use speech_to_send which is a variable we defined near the start of our code based on API.AI's
# initial response
print (app_code,location_code," speech_to_send is: ", speech_to_send)
# We already retrieved the user_token and channel higher up in the process
params = (
('token', user_token),
('channel', channel),
('text', speech_to_send),
('username', 'vietnambot'),
('icon_emoji', ':rice:'),
('pretty', '1'),
)
requests.get('https://slack.com/api/chat.postMessage', params=params)
# Because we've set the name-incorrect intent in API.AI to only output
# the food-followup and no-name contexts, we don't need to change that at all
# now, when the user responds to our message we'll enter the loop just the same
# as when we first sent them the message
close_db_connection(app_code,location_code)
#------------------------------------------------------#
#//////////////////////////////////////////////////////#
#============ Database closed WITHIN IF ==============#
#//////////////////////////////////////////////////////#
#------------------------------------------------------#
return
#--- End of W3.7 action is name-incorrect ---#
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
#|||||||||||||||||||||||||||||||||||||||||||||||||||||||#
#
#--- W3.8 action is give-deets ---#
#
# When we've processed the number of orders we end up with a bunch
# of potentially useful information about who has ordered today, and
# what. However, it is a poor user experience to just dump all of that
# information into a Slack message or spoken response so instead we record
# that information in an API.AI context and give the user to ask for it or not
if action=="give-deets":
location_code="w3.8 (give-deets)"
contexts = api_response_result.get ("contexts")
print (app_code,location_code," contexts are: ", contexts)
for context in contexts:
name=context.get("name")
# Because the user sent the food they want in their FIRST message, not the one we're
# dealing with at the moment, we just need to check the context that API.AI saved at that point