summaryrefslogtreecommitdiff
path: root/quote.py
blob: ee186602d81efd8f3c3cb6642a481254f2291282 (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
import os
import random
import re
import codecs


class quote(object):

    def __init__(self, quotefile="quotes.txt", encoding="utf8"):
        self.quotefile = quotefile
        self.encoding = encoding
        if os.path.isfile(quotefile):
            with codecs.open(quotefile, encoding=encoding) as f:
                self.quotes = [line for line in f]
        else:
            self.quotes = []

    def onChanMsg(self, IRC, user, channel, targetprefix, msg):
        matches = re.findall(
            r"^!quote(?:\s+(--add|--rem|--flush))?(?:\s+(.+?)\s*)?$", msg)
        if matches:
            cmd, msg = matches[0]
            if cmd == "" and msg == "":
                if self.quotes:
                    channel.msg(random.choice(self.quotes))
                else:
                    channel.msg("%s: There are no quotes!" % user.nick)
            elif cmd == "--add":
                if msg:
                    if msg not in self.quotes:
                        self.quotes.append(msg)
                        channel.msg("%s: Quote added." % user.nick)
                    else:
                        channel.msg("%s: Quote already exists." % user.nick)
                else:
                    channel.msg("%s: What am I adding?" % user.nick)
            elif cmd == "--rem":
                if msg:
                    if msg in self.quotes:
                        self.quotes.remove(msg)
                        channel.msg("%s: Quote removed." % user.nick)
                    else:
                        channel.msg("%s: Quote does not exist." % user.nick)
                else:
                    channel.msg("%s: What am I removing?" % user.nick)
            elif cmd == "--flush":
                with codecs.open(self.quotefile, "w", encoding=self.encoding) as f:
                    for line in self.quotes:
                        print >>f, line
            else:
                channel.msg(
                    "I am sorry, %s, but I cannot do that." % user.nick)

    def onSendChanMsg(self, IRC, channel, targetprefix, msg, origin):
        self.onChanMsg(IRC, IRC.identity, channel, targetprefix, msg)