-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiai.py
92 lines (69 loc) · 3.31 KB
/
apiai.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
from errbot import BotPlugin, cmdfilter
import json
import apiai
import credentials
from datetime import datetime as dt
class ApiAiPlugin(BotPlugin):
def __init__(self, *args, **kwargs):
super(ApiAiPlugin, self).__init__(*args, **kwargs)
self.apikey = credentials.apikey
self.apiai = apiai.ApiAI(self.apikey)
@cmdfilter(catch_unprocessed=True)
def apiai_filter(self, msg, cmd, args, dry_run, emptycmd=False):
if not emptycmd:
return msg, cmd, args
matched_prefix = False
prefixes = self.bot_config.BOT_ALT_PREFIXES + (self._bot.bot_config.BOT_PREFIX,)
for prefix in prefixes:
if msg.body.startswith(prefix):
matched_prefix = True
if not matched_prefix:
return msg, cmd, args
request = self.apiai.text_request()
request.session_id = msg.frm.person[:36]
request.query = msg.body
for prefix in prefixes:
if request.query.startswith(prefix):
request.query = request.query.replace(prefix, '', 1).strip()
break
separators = self._bot.bot_config.BOT_ALT_PREFIX_SEPARATORS
for sep in separators:
if request.query.startswith(sep):
request.query = request.query.replace(sep, '', 1)
self.log.debug("API.ai was sent: {}".format(request.query))
response = request.getresponse().read()
decoded_response = json.loads(response.decode('utf-8'))
self.log.debug("API.ai returned: {}".format(decoded_response))
if decoded_response['status']['errorType'] == 'success':
speech = decoded_response['result']['fulfillment']['speech']
if len(speech):
return speech
elif decoded_response['result']['action'] == 'notifications.add':
params = decoded_response['result']['parameters']
summary = params['summary'] if 'summary' in params else None
parseddate = params['date'] if 'date' in params else None
parsedtime = params['time'] if 'time' in params else None
if not parseddate and not parsedtime:
return "I can't set a reminder for that time."
if parseddate:
targetdate = dt.strptime(parseddate, '%Y-%d-%m').date()
else:
targetdate = dt.utcnow().date()
if parsedtime:
targettime = dt.strptime(parsedtime, '%H:%M:%S').time()
else:
targettime = dt.utcnow().time()
when = dt.combine(targetdate, targettime)
secondsuntil = (when - dt.utcnow()).seconds
self.start_poller(secondsuntil,
self.notification_callback,
args=(summary, secondsuntil, msg))
return "Setting reminder for: {}".format(when)
return
def notification_callback(self, summary, secondsuntil, msg):
self.stop_poller(self.notification_callback,
args=(summary, secondsuntil, msg))
self.log.debug('Notification: {}'.format(summary))
self.send(msg.frm,
groupchat_nick_reply=True,
text='Notification: {}'.format(summary))