about summary refs log tree commit diff
path: root/tracer.py
blob: e634fcd0eb381a105405404479cc8912d1c26ac4 (plain) (blame)
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3

from random import randint, choice
from tracery.modifiers import base_english
import configparser
import glob
import irctokens
import json
import os
import random
import re
import socket
import subprocess
import sys
import time
import traceback
import tracery

DB = {}
config = configparser.ConfigParser(
    converters={"list": lambda x: [i.strip() for i in x.split(",")]}
)
config.read("config.ini")
bot = config["irc"]

# read account info if it exists
if os.path.isfile("account.ini"):
    account = configparser.ConfigParser()
    account.read("account.ini")
    account = account["nickserv"]


def grammar(rules):
    try:
        res = tracery.Grammar(rules)
        res.add_modifiers(base_english)
        return res
    except Exception as e:
        print(e)


def load_rules(path):
    try:
        with open(path) as f:
            return json.loads(f.read())
    except Exception as e:
        print(e)


def populate():
    global DB
    DB = {}
    for p in glob.glob("/home/*/.tracery/*"):
        name, ext = os.path.splitext(p)
        name = os.path.basename(name)
        if name.startswith(".") or ext not in (".json", ""):
            continue
        if p in DB:
            DB[name].append(grammar(load_rules(p)))
        else:
            DB[name] = [grammar(load_rules(p))]


populate()


def generate(rule):
    populate()
    if rule in DB:
        g = random.choice(DB[rule])
        return g.flatten("#origin#")


def listify(col):
    if type(col) == type([]):
        return col
    else:
        return [col]


def shuffle(col):
    a = random.choice(list(col))
    b = random.choice(list(col))
    if "origin" in [a, b]:
        return col
    col[a], col[b] = col[b], col[a]
    return col


def fuse(argv):
    populate()
    raw = {}
    for gk in argv:
        if gk in DB:
            g = random.choice(DB[gk]).raw
            for k in g:
                if k in raw:
                    raw[k] = listify(raw[k]) + listify(g[k])
                else:
                    raw[k] = g[k]
    for i in range(20):
        raw = shuffle(raw)
    return grammar(raw).flatten("#origin#")


def _send(line):
    print(f"> {line.format()}")
    e.push(line)
    while e.pending():
        e.pop(s.send(e.pending()))


def send(chan, msg):
    _send(irctokens.format("PRIVMSG", [chan, msg]))


def think(line):
    chan = line.params.pop(0)
    words = line.params[0].split(" ")

    if len(words) > 0 and line.hostmask.nickname != bot["nick"]:
        if words[0] == "!!list":
            res = ""
            for k in DB:
                res += k + " "
            send(chan, res[:475])
        elif words[0] == "!!fuse":
            if "|" in words:
                res = fuse(words[1 : words.index("|")])
                if res:
                    send(chan, " ".join(words[words.index("|") + 1 :]) + " " + res)
            else:
                res = fuse(words[1:])
                if res:
                    send(chan, res[0:475])
        elif words[0] == "!!source":
            send(chan, "https://tildegit.org/ben/tracer")
        elif words[0] == "!botlist" or words[0] == "!!help":
            send(
                chan,
                "helo i'm a tracery bot that makes cool things from tracery grammars in your ~/.tracery. see http://tracery.io for more info",
            )
        elif words[0][0:2] == "!!":
            print(words)
            res = generate(words[0][2:])
            if res:
                if len(words) >= 3:
                    if words[1] == "|":
                        send(chan, " ".join(words[2:]) + " " + res)
                    else:
                        send(chan, res)
                else:
                    send(chan, res)


if __name__ == "__main__":
    d = irctokens.StatefulDecoder()
    e = irctokens.StatefulEncoder()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((bot["server"], int(bot["port"])))

    _send(irctokens.format("USER", [bot["nick"], "0", "*", "tracery bot"]))
    _send(irctokens.format("NICK", [bot["nick"]]))

    while True:
        lines = d.push(s.recv(1024))

        if lines == None:
            print("! disconnected")
            break

        for line in lines:
            print(f"< {line.format()}")

            if line.command == "PING":
                _send(irctokens.format("PONG", [line.params[0]]))

            elif line.command == "001":
                _send(irctokens.format("MODE", [bot["nick"], "+B"]))
                if account is not None:
                    _send(
                        irctokens.format(
                            "SQUERY",
                            [
                                "NickServ",
                                "IDENTIFY",
                                account["username"],
                                account["password"],
                            ],
                        )
                    )
                _send(irctokens.format("JOIN", bot.getlist("channels")))

            elif line.command == "INVITE":
                _send(irctokens.format("JOIN", [line.params[0]]))

            elif line.command == "PRIVMSG":
                try:
                    think(line)
                except Exception as e:
                    print("ERROR", line)
                    print(e)
                    traceback.print_exc()