-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
95 lines (72 loc) · 2.83 KB
/
bot.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
from data_collection.data_collection import COLLECTORS
from actions.actions import ACTIONS
class Bot:
def __init__(self, core, name='<no name>', language='en', id='00000000-000-0000-0000-000000000000'):
self.name = name
self.core = core
self.id = id
self.language = language
self.actions = [{
'action': a(settings={
"bot_name": name
}),
'active': False,
} for a in ACTIONS]
def _find_action_by_name(self, action_name):
return next(a for a in self.actions if a['action'].name == action_name)
def find_action_by_intent(self, intent):
return next((
a for a in self.actions
if a['active'] is not False and intent in a['active']['intents']), None)
def update_actions(self):
for action in self.actions:
action['action'].update()
def add_action(self, intent, action):
result = self._find_action_by_name(action.name)
if result['active'] is not False:
result['active']['intents'].append(intent)
else:
result['active'] = {'intents': [intent]}
def delete_action(self, intent):
result = self._find_action_by_name(action.name)
if result['active'] is not False:
if intent in result['active']['intents']:
result['active']['intents'].remove(intent)
if len(result['active']['intents']) == 0:
result['active'] = False
def explain(self, query):
explanation = {'query': query}
result = self.core.intent_of(query)
explanation = {**explanation, **result}
intent = result['intent']
if intent is None:
return explanation
action = self.find_action_by_intent(intent)['action']
if action is not None:
explanation['action'] = {
'name': action.name,
'description': action.description,
'settings': action.settings,
'data_collection': self.__data_collection(query),
}
return explanation
def __data_collection(self, query):
collected = {}
for c in COLLECTORS:
collected.update(c.extract(query))
return collected
def handle(self, query):
result = self.core.intent_of(query)
intent = result['intent']
if intent is None:
raise Exception('No intent detected')
action = self.find_action_by_intent(intent)['action']
if action is None:
raise Exception('No action found')
data_collection = self.__data_collection(query)
extra = {
'data_collection': data_collection,
'language': self.language,
'core': self.core
}
return action.execute(query, intent=intent, extra=extra)