summaryrefslogtreecommitdiff
path: root/fortune.py
blob: 64f9dd908344e84a0d200e66db7130212b02b491 (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
import random
import sys


class FortuneCookie():
    """"Holds a cookie"""

    def __init__(self, msg):
        self.msg = msg


class FortuneFile():
    """Contains methods for querying a cookie file"""

    def __init__(self, filename):
        self.filename = filename

    def fortunes(self):
        try:
            with open(self.filename) as f:
                current = ""
                for line in f:
                    if line != "%\n":
                        current += line
                    else:
                        cookie = FortuneCookie(current)
                        current = ""
                        yield cookie
                if current != "":
                    yield FortuneCookie(current)

        except FileNotFoundError:
            print("[*] Can't find the file " + self.filename)
        except IOError:
            print("[*] Error opening the file.")

    def get_random_cookie(self):
        for i, v in enumerate(self.fortunes()):
            rand = random.randint(0, i)
            if rand == 0:
                ret = v

        return ret


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: {} <fortune filename>".format(sys.argv[0]))
        sys.exit(1)

    ff = FortuneFile(sys.argv[1])
    cookie = ff.get_random_cookie()

    sys.stdout.write(cookie.msg)
nihil fit ex nihilo