-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRepBot.py
executable file
·264 lines (226 loc) · 8.46 KB
/
RepBot.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/python
import yaml
import time
import re
from twisted.words.protocols import irc
from twisted.internet import protocol, reactor, ssl
from twisted.internet.task import LoopingCall
from repsys import ReputationSystem
from repcmds import get_rep_change
import admin
def canonical_name(user):
return re.split(r"[\|`:]", user)[0].lower()
def ident_to_name(name):
return name.split("!", 1)[0]
def normalize_config(cfgFilename):
# Default settings
ret = {
"reps": "data/reps.txt",
"ignore": [],
"admins": [],
"replimit": 5,
"timelimit": 5.0 * 60.0,
"privonly": False,
"autorespond": False,
"nick": "RepBot",
"realname": "Reputation Bot",
"servname": "Reputation Bot",
"channels": [],
"server": "",
"port": 6667,
"ssl": False,
"spy": False,
"report": {
"channels": [],
"delay": 60*60
},
"savespeed": 3*60*60,
"topprivate": True
}
# Add the new stuff
ret.update(yaml.safe_load(open(cfgFilename)))
# Write the full config file, so they have a full listing
with open(cfgFilename,'w') as of:
yaml.dump(ret, of, default_flow_style=False)
# Fix set information
ret["ignore"] = sorted(set(ret["ignore"]))
ret["admins"] = sorted(set(ret["admins"]))
ret["report"]["channels"] = sorted(set(ret["report"]["channels"]))
ret["nick"] = ret["nick"].decode('ascii')
def cleanup(item):
if isinstance(item, dict):
return {name:cleanup(val) for name, val in item.items()}
elif isinstance(item, list):
return [cleanup(x) for x in item]
elif isinstance(item, basestring):
return str(item)
else:
return item
return cleanup(ret)
class RepBot(irc.IRCClient):
def __init__(self, cfg):
self.version = "0.12.0"
self.cfg = cfg
self.users = {}
self.reps = ReputationSystem(cfg["reps"])
self.loops = {}
# Instance variables for irc.IRCClient
self.nickname = cfg["nick"]
self.realname = cfg["realname"]
self.sourceURL = "http://github.com/msoucy/RepBot"
self.versionName = "RepBot"
self.versionNum = self.version
self.rebuild_wildcards()
self.changed = False
self.saver = LoopingCall(self.save)
self.saver.start(self.cfg["savespeed"])
def signedOn(self):
print "Signed on as {0}.".format(self.cfg["nick"])
for chan in self.cfg["channels"]:
self.join(chan)
def irc_unknown(self, prefix, command, params):
if command == "INVITE":
self.log("Invite to {1} from {0}".format(prefix, params[1]))
self.join(params[1])
def joined(self, channel):
print "Joined {0}.".format(channel)
def log(self, msg):
print time.asctime(), msg
def save(self):
if not self.changed: return
self.changed = False
self.reps.dump()
with open("data/settings.txt", "w") as fi:
yaml.dump(cfg, fi, default_flow_style=False)
self.log("Saved data")
def rebuild_wildcards(self):
def wildcard_regex(w):
return w.replace('.','\\.').replace('?','.').replace('*','.*?')
def regex_list(l):
return [re.compile(wildcard_regex(x)) for x in l]
self.adminList = regex_list(self.cfg["admins"])
self.ignoreList = regex_list(self.cfg["admins"])
def hasadmin(self, user):
for adm in self.adminList:
if adm.match(user):
return True
return False
def ignores(self, user):
for ig in self.ignoreList:
if ig.match(user):
return True
return False
def handleChange(self, user, changer):
name = changer.getUser()
if name == canonical_name(user):
self.msg(user, "Cannot change own rep")
return
currtime = time.time()
# Filter old uses
self.users[user] = [val
for val in self.users.get(user, [])
if (currtime - val) < self.cfg["timelimit"]]
if len(self.users[user]) < self.cfg["replimit"]:
self.reps.apply(changer)
self.users[user].append(currtime)
self.changed = True
else:
self.msg(user, "You have reached your rep limit. You can give more rep in {0} seconds"
.format(int(self.cfg["timelimit"] - (currtime - self.users[user][-1]))))
def report(self, chan):
admin.admin(self, chan, "report force")
def repcmd(self, user, channel, msg):
# Respond to private messages privately
if channel == self.cfg["nick"]:
channel = user
args = msg.split()
cmd = args[0] if args else ""
args = args[1:] if args else []
changer = get_rep_change(msg)
if changer != None:
self.handleChange(user, changer)
elif cmd in ("rep",):
self.msg(channel, self.reps.tell(canonical_name(args[0] if args else user)))
elif cmd in ("top", "report"):
self.msg(user if self.cfg["topprivate"] else channel, self.reps.report(True))
elif cmd in ("ver", "version", "about"):
self.msg(channel, 'I am RepBot version {0}'.format(self.version))
elif cmd in ("help",):
self.msg(
channel,
'Message me with "!rep <name>" to get the reputation of <name>')
self.msg(
channel,
'Use prefix or postfix ++/-- to change someone\'s rep. You are not able to change your own rep.')
self.msg(
channel,
'Message me with "!version" to see my version number')
elif self.cfg["autorespond"] and channel == user:
# It's not a valid command, so let them know
# Only respond privately
self.msg(
user,
'Invalid command. MSG me with !help for information')
def privmsg(self, ident, channel, msg):
if not ident:
return
try:
msg = msg.decode("utf-8")
except UnicodeDecodeError as ue:
self.log("Received non-unicode message")
return
isAdmin = False
if msg.startswith('!'):
# It's a command to RepBot itself
msg = msg[1:]
elif channel != self.cfg["nick"] and msg.startswith(self.cfg["nick"] + ":"):
# It's a command to RepBot itself
msg = msg[len(self.cfg["nick"]) + 1:].strip()
elif self.hasadmin(ident) and channel == self.cfg["nick"]:
# They have admin access, check for commands
if msg.startswith("admin"):
msg = msg.replace("admin", "", 1)
elif msg.startswith("@"):
msg = msg[1:]
else:
return
isAdmin = True
elif get_rep_change(msg) == None:
# It doesn't match a rep change
return
user = ident_to_name(ident)
if self.ignores(ident) and not self.hasadmin(ident):
self.msg(
user,
"You have been blocked from utilizing my functionality.")
if self.cfg["spy"]:
self.log("[{1}]\t{0}:\t{2}".format(ident, channel, msg))
if isAdmin:
admin.admin(self, user, msg)
elif channel == self.cfg["nick"] or not self.cfg["privonly"]:
# I'm just picking up a regular chat
# And we aren't limited to private messages only
self.repcmd(user, channel, msg)
class RepBotFactory(protocol.ClientFactory):
def __init__(self, cfg):
self.cfg = cfg
def buildProtocol(self, addr):
return RepBot(self.cfg)
def clientConnectionLost(self, connector, reason):
print "Lost connection (%s), reconnecting." % (reason,)
connector.connect()
def clientConnectionFailed(self, connector, reason):
print "Could not connect: %s" % (reason,)
if __name__ == "__main__":
cfg = normalize_config("data/settings.txt")
server = cfg["server"]
port = cfg["port"]
factory = RepBotFactory(cfg)
print "Connecting to {0}:{1}".format(server, port)
if cfg["ssl"]:
print "Using SSL"
reactor.connectSSL(server, port, factory, ssl.ClientContextFactory())
else:
print "Not using SSL"
reactor.connectTCP(server, port, factory)
reactor.run()