-
Notifications
You must be signed in to change notification settings - Fork 0
/
ubnotu.py
executable file
·341 lines (257 loc) · 10.8 KB
/
ubnotu.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#!/usr/bin/env python2.6
import irclib
import optparse
import sys
import datetime
import time
import binascii
import hashlib
import random
import sqlite3
opt = optparse.OptionParser()
opt.add_option("-s", "--server", dest="server", default="localhost",
help="Server to connect to")
opt.add_option("-p", "--port", dest="port", default="6667",
help="Port to connect to on the server")
opt.add_option("", "--ssl", dest="ssl", action="store_true", default=False,
help="Use SSL or not")
opt.add_option("-n", "--nickname", dest="nick", default="testbot", help="Bot \
nickname")
opt.add_option("-i", "--ident", dest="ident", default="test", help="Bot ident")
opt.add_option("-r", "--realname", dest="rname", default="ubnotu IRC Bot",
help="Bot real name")
opt.add_option("-j", "--nickservpass", dest="npass", default="", help="Bot \
nickserv password")
opt.add_option("-v", "--verbose", dest="verbosity", action="count", default=0)
opt.add_option("", "--channels", dest="channels", default="", help="Comma \
separated list of channels to join")
class ubnotu_ng:
def pprint(self, msg, level=0):
""" Print a message if the specified level is at least the level of
verbosity. Levels of 0 are always printed. """
if(level <= self.options.verbosity):
print datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S") + " " + str(level) + " ",
print msg
def __init__(self, options):
self.options = options
self.fcon = sqlite3.connect("factoid.db")
self.pprint("Starting ubnotu-ng...")
random.seed()
def run(self):
#connect
self.pprint("Connecting to IRC server %s" % self.options.server)
self.irc = irclib.IRC()
self.factchar = '!'
self.cmdchar = '@'
self.rand = open("/dev/urandom", "r")
self.identified = {} # maps nicks to names of users:capability they are identified for
self.builtins = {
"register": self.cmd_register,
"identify": self.cmd_identify,
"seen": self.cmd_seen,
"8ball": self.cmd_8ball,
"fortune": self.cmd_fortune
}
try:
self.c = self.irc.server().connect(server = self.options.server,
port = int(self.options.port), nickname = self.options.nick,
username = self.options.ident, ircname =
self.options.rname, ssl=self.options.ssl)
except irclib.ServerConnectionError, x:
self.pprint(x)
sys.exit(-1)
self.c.add_global_handler("welcome", self.on_connect)
self.c.add_global_handler("privmsg", self.on_privmsg)
self.c.add_global_handler("pubmsg", self.on_pubmsg)
#point of no return
self.pprint("Going into the rabbit hole", level=1)
try:
self.irc.process_forever()
except KeyboardInterrupt:
self.quit("Keyboard Interrupt")
sys.exit(-1)
self.pprint("Shouldn't ever happen.... something is wrong")
def quit(self, msg):
self.c.quit(message=msg)
self.c.close()
#implements rate limiting and such TODO
def msg(self, target, msg):
self.c.privmsg(target, msg)
#Event Handlers
def on_connect(self, c, event):
self.pprint("Connection Successful!")
map(c.join, self.options.channels.split(","))
#messages said in PM
def on_privmsg(self, c, eventlist):
self.on_pubmsg(c, eventlist, ispubmsg=False)
#messages said in a public channel
def on_pubmsg(self, c, eventlist, ispubmsg=True):
arg = eventlist.arguments()[0]
nick = irclib.nm_to_n(eventlist.source())
user = irclib.nm_to_u(eventlist.source())
host = irclib.nm_to_h(eventlist.source())
if arg[0] == self.cmdchar:
cmd = arg[1:].split(' ')[0]
info = {
"nick": nick,
"user": user,
"host": host,
"pubmsg": ispubmsg,
"target": eventlist.target(),
"source": eventlist.source(),
"args": arg[1:].split(' ')[1:]
}
self.builtins.get(cmd, self.dispatch)(info)
elif arg[0] == self.factchar:
info = {
"nick": nick,
"user": user,
"host": host,
"pubmsg": ispubmsg,
"target": eventlist.target(),
"source": eventlist.source(),
"factoid": arg[1:].split(' ')[0],
"args": arg[1:].split(' ')[1:]
}
self.do_factoid_lookup(info)
#update the seen database
seen = open("Seen.db", "r")
lines = []
updated = False
for line in seen.read().split('\n'):
parsed = line.split(',')
if parsed[0] == eventlist.target():
if parsed[1] == nick:
t = datetime.datetime.now()
nline = eventlist.target() + "," + nick + "," + \
str(time.mktime(t.timetuple()) + 1e-6*t.microsecond) + "," + "<" \
+ nick + "> " + arg
updated = True
lines.append(nline)
break
lines.append(line)
if updated is False:
#add a new line
t = datetime.datetime.now()
nline = eventlist.target() + "," + nick + "," + str(time.mktime(t.timetuple()) +
1e-6*t.microsecond) + "," + "<" + nick + "> " + arg
lines.append(nline)
seen.close()
#Yes this is not the most efficient way to do this by far, but
#everything is in memory so I defy someone to come up with a way that
#is significantly faster in practice
seen = open("Seen.db", "w")
for line in lines:
seen.write(line + "\n")
seen.close()
def cmd_register(self, info):
passwd = open("passwd", "rw+")
if info['pubmsg'] is True:
self.msg(info['target'], "Registration only works in PM.")
return
self.pprint("Registering a new user.", level=1)
#check that the username doesn't already exist
for line in passwd.read().split('\n'):
if info['args'][0] == line.split(':')[0]:
self.pprint(info['nick'] + " is trying to register username " \
+ info['args'][0] + ", but it already exists.")
self.msg(info['nick'], "Username already exists.")
return
#create our salt
salt = self.rand.read(16)
hash = hashlib.sha256(salt + info['args'][1]).hexdigest()
outstring = info['args'][0] + ":" + binascii.hexlify(salt) + "|" + hash \
+ "/" + "USER"
passwd.write(outstring + "\n")
self.msg(info['nick'], "Registration successful!")
self.pprint(info['nick'] + " registered new user " + info['args'][0])
passwd.close()
def cmd_identify(self, info):
passwd = open("passwd", "rw+")
if info['pubmsg'] is True:
self.msg(info['target'], "Identifying only works in PM.")
return
self.pprint("Identifying a user.", level=1)
#check for the username
for line in passwd.read().split('\n'):
if info['args'][0] == line.split(':')[0]:
rest = line.split(':')[1].split('|')
salt = binascii.unhexlify(rest[0])
hash = rest[1].split('/')[0]
cap = rest[1].split('/')[1]
hashed = hashlib.sha256(salt + info['args'][1]).hexdigest()
if hashed == hash:
self.msg(info['nick'], "Identification OK")
self.pprint(info['nick'] + " successfully identified for \
user " + info['args'][0])
#mark nick as identified for user
self.identified.setdefault(info['nick'])
self.identified[info['nick']] = info['args'][0] + ":" + cap
else:
self.msg(info['nick'], "Identification FAILED")
self.pprint(info['nick'] + " FAILED to identify for user "
+ info['args'][0])
passwd.close()
def cmd_8ball(self, info):
self.fortune(info, "8ball.txt")
def cmd_fortune(self, info):
self.fortune(info, "fortune.txt")
def fortune(self, info, file):
f = open(file, "r")
replies = []
for line in f:
replies.append(line)
self.msg(info['target'], random.choice(replies))
f.close()
def cmd_seen(self, info):
#supybot format Seen.db
seen = open("Seen.db", "r")
found = False
#take different arguments if it is sent to a channel or in PM
if info['target'][0] == '#':
try:
if info['args'][0] == "-channel":
chan = info['args'][1]
nick = info['args'][2]
else:
chan = info['target']
nick = info['args'][0]
except IndexError:
self.msg(info['target'], "Syntax Error")
return
for line in seen.read().split('\n'):
parsed = line.split(',')
if parsed[0] == chan:
if parsed[1] == nick:
#calculate the time
a = datetime.datetime.fromtimestamp(float(parsed[2]))
diff = datetime.datetime.now() - a
self.msg(info['target'], info['nick'] + ": " + \
nick + " was last seen in " + \
chan + " " + str(diff) + " ago: " + parsed[-1])
found = True
if found is False:
self.msg(info['target'], info['nick'] + ": I have not seen " +
nick)
seen.close()
def do_factoid_lookup(self, info):
c = self.fcon.cursor()
output = ""
self.pprint("Looking up factoid %s" % info['factoid'], 1)
c.execute("select * from facts where name = \"%s\"" % info['factoid'])
res = c.fetchone()
if res == None:
self.msg(info['target'], "Factoid %s not found." % info['factoid'])
return
#for compatibility with old-style factoids
if "<reply>" in res[4]:
output = res[4][7:]
else:
output = res[4]
self.msg(info['target'], output)
def dispatch(self, info):
self.pprint("Not builtin command, dispatching to plugins.", level=1)
if __name__ == "__main__":
opts, args = opt.parse_args()
bot = ubnotu_ng(opts)
bot.run()