summaryrefslogtreecommitdiffstats
path: root/RemindBot.py
blob: 9e117d05e32a85bcad7b3abea4c8c6ba9c93bc09 (plain)
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
import logging
from errbot import BotPlugin, botcmd, re_botcmd
import parsedatetime, datetime, re

l = logging.getLogger(__name__)

class RemindBot(BotPlugin):
    """RemindBot reminds you of reminders."""

    def activate(self):
        super(RemindBot, self).activate()

        r = r"(of|to)?\s*(?P<reminder>.*)\b(on|at|when it\s*['i]s|in|the|\s)+\b\s+(?P<time>.*)"
        self.re = re.compile(r)
        self.cal = parsedatetime.Calendar()

        reminders = self.setdefault("reminders", [])

        now = datetime.datetime.now()
        self["reminders"].sort(key=lambda x: x[0])
        for reminder in self["reminders"]:
            if (reminder[0] < now):
                self["reminders"].remove(reminder)
            else:
                break

        self.start_next_reminder()

    def start_next_reminder(self):
        try:
            self.stop_poller(self.reminding)
        except ValueError:
            pass

        if (len(self["reminders"]) > 0):
            self["reminders"].sort(key=lambda x: x[0])
            now = datetime.datetime.now()
            td = self["reminders"][0][0] - now

            self.start_poller(td.total_seconds(), self.reminding)

    def reminding(self):
        self.stop_poller(self.reminding)

        (time, msg, txt) = self["reminders"].pop(0)
        self.send(msg.frm, txt, message_type=msg.type)

        self.start_next_reminder()

    @botcmd
    def remind_me(self, msg, args):
        m = self.re.match(args)
        if (m is not None):
            time, flag = self.cal.parseDT(m.group("time"))
            if (flag == 0):
                return "Sorry, I don't understand '{}'".format(m.group("time"))
            else:
                self["reminders"].append((time, msg, m.group("reminder")))
                self.start_next_reminder()
                return "I will remind you at {} of '{}'".format(time, m.group("reminder"))
        else:
            return "I don't understand... Sorry :("