-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathactions.py
305 lines (211 loc) · 10.7 KB
/
actions.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
#!/usr/bin/python3
from typing import Any, Text, Dict, List
#import the rasa dependencies
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
#import the fetchable dependencies
from fetchable import FetchableClient
from fetchable import configuration
"""
Initialise a FetchableClient object to talk to the fetchable API.
Configure it to use the latest version of the Fetchable API.a
Surround it with try/except to catch the exception raised if
the API keys can't be read from the authentication file.
"""
try:
client = FetchableClient(api_version=configuration.api_version.latest)
except:
print("something went wrong initialising the Fetchable client")
"""
Class to handle the joke action
"""
class ActionFetchJoke(Action):
# return the name of the action
def name(self) -> Text:
return "action_fetch_joke"
# code to be executed when the action is called by rasa core
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# use the client object to fetch a random joke from Fetchable
response = client.fetch_joke()
# check for a successful response
if response['status_code']==200:
# concatenate the setup and the punchline of the joke and return
# it to the user
# e.g. "What's blue and not very heavy? Light blue"
dispatcher.utter_message(response['setup']+" "+response['punchline'])
# we'd like to check if the API can't be reached because of a connection error
# so the user can reconnect the chatbot
elif response['status_code']==1001:
dispatcher.utter_message("Unfortunately, I cant connect to the internet right now")
# catch all other errors and give a generic message back
else:
dispatcher.utter_message("Unfortunately, something went wrong")
return []
"""
Class to handle the quote action
"""
class ActionFetchQuote(Action):
# return the name of the action
def name(self) -> Text:
return "action_fetch_quote"
# code to be executed when the action is called by rasa core
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# use the client object to fetch an inspirational quote from Fetchable
quote_response = client.fetch_quote()
# check for a successful response
if quote_response['status_code']==200:
# return a message in the form of <quote> by <author>
# e.g. "Do, or do not. There is no try." by Yoda
dispatcher.utter_message("{} by {}".format(quote_response['quote'], quote_response['author']))
# we'd like to check if the API can't be reached because of a connection error
# so the user can reconnect the chatbot
elif quote_response['status_code']==1001:
dispatcher.utter_message("Can't connect to the internet right now...")
# catch all other errors and give a generic message back
else:
dispatcher.utter_message("Unfortunately, something went wrong")
return []
"""
Class to handle the fun fact action
"""
class ActionFetchFunFact(Action):
# return the name of the action
def name(self) -> Text:
return "action_fetch_fun_fact"
# code to be executed when the action is called by rasa core
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# use the client object to fetch a random fun fact from Fetchable
fun_fact_response = client.fetch_fun_fact()
# check for a successful response
if fun_fact_response['status_code']==200:
# just return the text of the fun fact
# e.g. "It is physically impossible for you to lick your elbow."
dispatcher.utter_message(fun_fact_response['fun_fact'])
# we'd like to check if the API can't be reached because of a connection error
# so the user can reconnect the chatbot
elif fun_fact_response['status_code']==1001:
dispatcher.utter_message("Can't connect to the internet right now...")
# catch all other errors and give a generic message back
else:
dispatcher.utter_message("Unfortunately, something went wrong")
return []
"""
Class to handle the dictionary / word definition action
"""
class ActionFetchWordDefinition(Action):
# return the name of the action
def name(self) -> Text:
return "action_fetch_word_definition"
# code to be executed when the action is called by rasa core
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# get all the entities extracted by rasa
entities = tracker.latest_message['entities']
# cycle through them and extract the relavant one for us
word = None
for e in entities:
if e['entity'] == "word":
word = e['value']
# sanity check to ensure it was filled by rasa
if word:
# use the client object to fetch the definition from Fetchable
response = client.fetch_word_definition(word)
# check for a successful response
if response['status_code']==200:
# words can have multiple meanings so check the length here
# if there is only one meaning for the word
if(len(response['meanings'])==1):
# even if there is only one meaning for the word, it still arrives in an array
# so extract the first element and give it back
dispatcher.utter_message("The definition of {} is {}.".format(word, response['meanings'][0]))
# if there are multiple meanings
else:
# say how many meanings the word has
user_response = "{} has {} meanings. ".format(word, len(response['meanings']))
# cycle through every meaning and append the meanings onto the
# text that will be given back to the user
for i, meaning in enumerate(response['meanings']):
# this is in the form "1. <meaning>"
user_response += str(i+1)+", "+meaning+" "
#strip the trailing space and return to the user
# e.g. "ameliorate has 2 meanings. 1, To make better; to improve; to meliorate.
# 2, To grow better; to meliorate; as, wine ameliorates by age."
dispatcher.utter_message(user_response.strip())
# handle the case that Fetchable doesn't know that word,
# hopefully won't happen that often (;
elif response['status_code']==404:
dispatcher.utter_message("I'm afraid I don't know that")
# we'd like to check if the API can't be reached because of a connection error
# so the user can reconnect the chatbot
elif response['status_code']==1001:
dispatcher.utter_message("Unfortunately, I cant connect to the internet right now")
# catch all other errors and give a generic message back
else:
dispatcher.utter_message("Unfortunately, something went wrong")
# if the word entity was not filled properly by rasa, then give a generic message back
else:
dispatcher.utter_message("I'm afraid I don't know what you mean")
return []
"""
Class to handle the entity-attribute action
"""
class ActionFetchTrivia(Action):
# return the name of the action
def name(self) -> Text:
return "action_fetch_trivia"
# code to be executed when the action is called by rasa core
def run(self, dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
# get all the entities extracted by rasa
entities = tracker.latest_message['entities']
# cycle through them and extract the relavant one for us
entity = None
attribute = None
for e in entities:
if e['entity'] == "entity":
entity = e['value']
elif e['entity'] == "attribute":
attribute = e['value']
# sanity check to ensure they were filled by rasa
if entity and attribute:
# use the client object to fetch the data from Fetchable
response = client.fetch_entity_attribute(entity, attribute)
# check for a successful response
if response['status_code']==200:
# some attributes have units, e.g. 'length' has the unit of 'miles' or 'kilometers'
# and some attributes do not have units, e.g. a countries government cannot be a unit.
# check if this attribute has units or not
if response['unit'] == "N/A":
# this attribute does not have units so return the text in the form:
# the <attribute> of <entity> is <value>
# e.g the goverment of Ireland is a democracy.
dispatcher.utter_message("The {} of {} is {}.".format(attribute, entity, response['value']))
else:
# this attribute has units so return the text in the form:
# the <attribute> of <entity> is <value> <units>
# e.g the length of the amazon is 6400 kms
dispatcher.utter_message("The {} of {} is {} {}.".format(attribute, entity, response['value'], response['unit']))
# handle the case that Fetchable doesn't know that piece of trivia,
# hopefully won't happen that often (;
elif response['status_code']==404:
dispatcher.utter_message("I'm afraid I don't know that")
# we'd like to check if the API can't be reached because of a connection error
# so the user can reconnect the chatbot
elif response['status_code']==1001:
dispatcher.utter_message("Unfortunately, I cant connect to the internet right now")
# catch all other errors and give a generic message back
else:
dispatcher.utter_message("Unfortunately, something went wrong")
# if the entity and attributes entities were not filled properly by rasa,
# then give a generic message back
else:
dispatcher.utter_message("I'm afraid I don't know what you mean")
return []