]> jfr.im git - erebus.git/blame - erebus.py
some socket fixes
[erebus.git] / erebus.py
CommitLineData
b25d4368 1#!/usr/bin/python
4477123d 2# vim: fileencoding=utf-8
b25d4368 3
931c88a4 4# Erebus IRC bot - Author: John Runyon
5# main startup code
6
a28e2ae9 7from __future__ import print_function
8
9d44d267 9import os, sys, select, MySQLdb, MySQLdb.cursors, time, traceback, random, gc
db50981b 10import bot, config, ctlmod
b25d4368 11
a8553c45 12class Erebus(object): #singleton to pass around
134c1193 13 APIVERSION = 0
a76c4bd8 14 RELEASE = 0
15
49a455aa 16 bots = {}
17 fds = {}
e4a4c762 18 numhandlers = {}
49a455aa 19 msghandlers = {}
9557ee54 20 chanhandlers = {}
e8885384 21 exceptionhandlers = [] # list of (Exception_class, handler_function) tuples
b2a896c8 22 users = {}
23 chans = {}
49a455aa 24
25 class User(object):
49a455aa 26 def __init__(self, nick, auth=None):
27 self.nick = nick
25bf8fc5
JR
28 if auth is None:
29 self.auth = None
30 else:
31 self.auth = auth.lower()
676b2a85 32 self.checklevel()
a4eacae2 33
5477b368 34 self.chans = []
35
e80bf7de 36 def msg(self, *args, **kwargs):
e64ac4a0 37 main.randbot().msg(self, *args, **kwargs)
2bb267e0 38 def slowmsg(self, *args, **kwargs):
39 main.randbot().slowmsg(self, *args, **kwargs)
e64ac4a0 40 def fastmsg(self, *args, **kwargs):
41 main.randbot().fastmsg(self, *args, **kwargs)
e80bf7de 42
b2a896c8 43 def isauthed(self):
44 return self.auth is not None
45
49a455aa 46 def authed(self, auth):
de89db13 47 if auth == '0': self.auth = None
48 else: self.auth = auth.lower()
49a455aa 49 self.checklevel()
a4eacae2 50
676b2a85 51 def checklevel(self):
52 if self.auth is None:
839d2b35 53 self.glevel = -1
676b2a85 54 else:
2729abc8 55 c = main.query("SELECT level FROM users WHERE auth = %s", (self.auth,))
56 if c:
4fa1118b 57 row = c.fetchone()
58 if row is not None:
59 self.glevel = row['level']
60 else:
61 self.glevel = 0
676b2a85 62 else:
839d2b35 63 self.glevel = 0
64 return self.glevel
43b98e4e 65
25bf8fc5
JR
66 def setlevel(self, level, savetodb=True):
67 if savetodb:
68 if level != 0:
69 c = main.query("REPLACE INTO users (auth, level) VALUES (%s, %s)", (self.auth, level))
70 else:
71 c = main.query("DELETE FROM users WHERE auth = %s", (self.auth,))
72 if c == 0: # no rows affected
73 c = True # is fine
74 if c:
75 self.glevel = level
76 return True
77 else:
78 return False
79 else:
80 self.glevel = level
81 return True
82
5477b368 83 def join(self, chan):
84b7c247 84 if chan not in self.chans: self.chans.append(chan)
5477b368 85 def part(self, chan):
3d724d3a 86 try:
87 self.chans.remove(chan)
88 except: pass
d53d073b 89 return len(self.chans) == 0
c695f740 90 def quit(self):
d53d073b 91 pass
124f114c 92 def nickchange(self, newnick):
e80bf7de 93 self.nick = newnick
5477b368 94
49a455aa 95 def __str__(self): return self.nick
71ef8273 96 def __repr__(self): return "<User %r (%d)>" % (self.nick, self.glevel)
43b98e4e 97
49a455aa 98 class Channel(object):
586997a7 99 def __init__(self, name, bot):
49a455aa 100 self.name = name
5477b368 101 self.bot = bot
586997a7 102 self.levels = {}
5477b368 103
104 self.users = []
105 self.voices = []
106 self.ops = []
a4eacae2 107
2729abc8 108 c = main.query("SELECT user, level FROM chusers WHERE chan = %s", (self.name,))
109 if c:
586997a7 110 row = c.fetchone()
4fa1118b 111 while row is not None:
112 self.levels[row['user']] = row['level']
113 row = c.fetchone()
586997a7 114
115
fd52fb16 116 def msg(self, *args, **kwargs):
e64ac4a0 117 self.bot.msg(self, *args, **kwargs)
2bb267e0 118 def slowmsg(self, *args, **kwargs):
119 self.bot.slowmsg(self, *args, **kwargs)
e64ac4a0 120 def fastmsg(self, *args, **kwargs):
121 self.bot.fastmsg(self, *args, **kwargs)
fd52fb16 122
586997a7 123 def levelof(self, auth):
a9ce8d6a 124 if auth is None:
125 return 0
586997a7 126 auth = auth.lower()
127 if auth in self.levels:
128 return self.levels[auth]
129 else:
130 return 0
131
132 def setlevel(self, auth, level, savetodb=True):
133 auth = auth.lower()
134 if savetodb:
2729abc8 135 c = main.query("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self.name, auth, level))
136 if c:
4fa1118b 137 self.levels[auth] = level
138 return True
139 else:
140 return False
25bf8fc5
JR
141 else:
142 self.levels[auth] = level
143 return True
586997a7 144
49a455aa 145 def userjoin(self, user, level=None):
146 if user not in self.users: self.users.append(user)
147 if level == 'op' and user not in self.ops: self.ops.append(user)
148 if level == 'voice' and user not in self.voices: self.voices.append(user)
149 def userpart(self, user):
150 if user in self.ops: self.ops.remove(user)
151 if user in self.voices: self.voices.remove(user)
152 if user in self.users: self.users.remove(user)
a4eacae2 153
49a455aa 154 def userop(self, user):
155 if user in self.users and user not in self.ops: self.ops.append(user)
156 def uservoice(self, user):
157 if user in self.users and user not in self.voices: self.voices.append(user)
158 def userdeop(self, user):
159 if user in self.ops: self.ops.remove(user)
160 def userdevoice(self, user):
161 if user in self.voices: self.voices.remove(user)
162
163 def __str__(self): return self.name
164 def __repr__(self): return "<Channel %r>" % (self.name)
165
c0eee1b4 166 def __init__(self, cfg):
2a44c0cd 167 self.mustquit = None
fc16e064 168 self.starttime = time.time()
c0eee1b4 169 self.cfg = cfg
170 self.trigger = cfg.trigger
fd96a423 171 if os.name == "posix":
172 self.potype = "poll"
173 self.po = select.poll()
174 else: # f.e. os.name == "nt" (Windows)
175 self.potype = "select"
176 self.fdlist = []
49a455aa 177
2729abc8 178 def query(self, *args, **kwargs):
c728e51c 179 if 'noretry' in kwargs:
180 noretry = kwargs['noretry']
181 del kwargs['noretry']
2729abc8 182 else:
c728e51c 183 noretry = False
2729abc8 184
185 self.log("[SQL]", "?", "query(%s, %s)" % (', '.join([repr(i) for i in args]), ', '.join([str(key)+"="+repr(kwargs[key]) for key in kwargs])))
186 try:
187 curs = self.db.cursor()
188 res = curs.execute(*args, **kwargs)
189 if res:
190 return curs
191 else:
192 return res
193 except MySQLdb.MySQLError as e:
194 self.log("[SQL]", "!", "MySQL error! %r" % (e))
c728e51c 195 if not noretry:
2729abc8 196 dbsetup()
c728e51c 197 return self.query(*args, noretry=True, **kwargs)
2729abc8 198 else:
199 raise e
200
c728e51c 201 def querycb(self, cb, *args, **kwargs):
202 def run_query():
203 cb(self.query(*args, **kwargs))
204 threading.Thread(target=run_query).start()
205
0af282c6 206 def newbot(self, nick, user, bind, authname, authpass, server, port, realname):
49a455aa 207 if bind is None: bind = ''
0af282c6 208 obj = bot.Bot(self, nick, user, bind, authname, authpass, server, port, realname)
49a455aa 209 self.bots[nick.lower()] = obj
a4eacae2 210
49a455aa 211 def newfd(self, obj, fileno):
49a455aa 212 self.fds[fileno] = obj
fd96a423 213 if self.potype == "poll":
214 self.po.register(fileno, select.POLLIN)
215 elif self.potype == "select":
216 self.fdlist.append(fileno)
9d44d267
JR
217 def delfd(self, fileno):
218 del self.fds[fileno]
219 if self.potype == "poll":
220 self.po.unregister(fileno)
221 elif self.potype == "select":
222 self.fdlist.remove(fileno)
a4eacae2 223
43b98e4e 224 def bot(self, name): #get Bot() by name (nick)
49a455aa 225 return self.bots[name.lower()]
43b98e4e 226 def fd(self, fileno): #get Bot() by fd/fileno
49a455aa 227 return self.fds[fileno]
8af0407d 228 def randbot(self): #get Bot() randomly
71ef8273 229 return self.bots[random.choice(list(self.bots.keys()))]
49a455aa 230
f6386fa7 231 def user(self, _nick, send_who=False, create=True):
c695f740 232 nick = _nick.lower()
f6386fa7
JR
233
234 if send_who and (nick not in self.users or not self.users[nick].isauthed()):
235 self.randbot().conn.send("WHO %s n%%ant,1" % (nick))
236
b2a896c8 237 if nick in self.users:
238 return self.users[nick]
3d724d3a 239 elif create:
c695f740 240 user = self.User(_nick)
b2a896c8 241 self.users[nick] = user
242 return user
3d724d3a 243 else:
244 return None
5477b368 245 def channel(self, name): #get Channel() by name
246 if name.lower() in self.chans:
247 return self.chans[name.lower()]
248 else:
249 return None
250
586997a7 251 def newchannel(self, bot, name):
252 chan = self.Channel(name.lower(), bot)
5477b368 253 self.chans[name.lower()] = chan
254 return chan
49a455aa 255
256 def poll(self):
2a44c0cd 257 timeout_seconds = 30
fd96a423 258 if self.potype == "poll":
2a44c0cd
JR
259 pollres = self.po.poll(timeout_seconds * 1000)
260 return [fd for (fd, ev) in pollres]
fd96a423 261 elif self.potype == "select":
2a44c0cd 262 return select.select(self.fdlist, [], [], timeout_seconds)[0]
49a455aa 263
264 def connectall(self):
a28e2ae9 265 for bot in self.bots.values():
49a455aa 266 if bot.conn.state == 0:
267 bot.connect()
268
fadbf980 269 def module(self, name):
270 return ctlmod.modules[name]
271
a8553c45 272 def log(self, source, level, message):
a28e2ae9 273 print("%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message))
a8553c45 274
f560eb44 275 def getuserbyauth(self, auth):
a28e2ae9 276 return [u for u in self.users.values() if u.auth == auth.lower()]
f560eb44 277
bffe0139 278 def getdb(self):
279 """Get a DB object. The object must be returned to the pool after us, using returndb()."""
280 return self.dbs.pop()
281
282 def returndb(self, db):
283 self.dbs.append(db)
284
49a455aa 285 #bind functions
db50981b 286 def hook(self, word, handler):
e4a4c762 287 try:
288 self.msghandlers[word].append(handler)
289 except:
290 self.msghandlers[word] = [handler]
291 def unhook(self, word, handler):
292 if word in self.msghandlers and handler in self.msghandlers[word]:
293 self.msghandlers[word].remove(handler)
db50981b 294 def hashook(self, word):
e4a4c762 295 return word in self.msghandlers and len(self.msghandlers[word]) != 0
db50981b 296 def gethook(self, word):
297 return self.msghandlers[word]
b25d4368 298
e4a4c762 299 def hooknum(self, word, handler):
300 try:
301 self.numhandlers[word].append(handler)
302 except:
303 self.numhandlers[word] = [handler]
304 def unhooknum(self, word, handler):
305 if word in self.numhandlers and handler in self.numhandlers[word]:
306 self.numhandlers[word].remove(handler)
307 def hasnumhook(self, word):
308 return word in self.numhandlers and len(self.numhandlers[word]) != 0
309 def getnumhook(self, word):
310 return self.numhandlers[word]
311
2a1a69a6 312 def hookchan(self, chan, handler):
313 try:
9557ee54 314 self.chanhandlers[chan].append(handler)
2a1a69a6 315 except:
9557ee54 316 self.chanhandlers[chan] = [handler]
2a1a69a6 317 def unhookchan(self, chan, handler):
318 if chan in self.chanhandlers and handler in self.chanhandlers[chan]:
319 self.chanhandlers[chan].remove(handler)
320 def haschanhook(self, chan):
321 return chan in self.chanhandlers and len(self.chanhandlers[chan]) != 0
322 def getchanhook(self, chan):
323 return self.chanhandlers[chan]
586997a7 324
e8885384
JR
325 def hookexception(self, exc, handler):
326 self.exceptionhandlers.append((exc, handler))
327 def unhookexception(self, exc, handler):
328 self.exceptionhandlers.remove((exc, handler))
329 def hasexceptionhook(self, exc):
330 return any((True for x,h in self.exceptionhandlers if isinstance(exc, x)))
331 def getexceptionhook(self, exc):
332 return (h for x,h in self.exceptionhandlers if isinstance(exc, x))
333
586997a7 334
de89db13 335def dbsetup():
4fa1118b 336 main.db = None
bffe0139 337 main.dbs = []
338 for i in range(cfg.get('erebus', 'num_db_connections', 2)-1):
339 main.dbs.append(MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor))
2729abc8 340 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor)
586997a7 341
b25d4368 342def setup():
db50981b 343 global cfg, main
344
48479459 345 cfg = config.Config('bot.config')
e64ac4a0 346
dcc5bde3 347 if cfg.getboolean('debug', 'gc'):
2ffef3ff 348 gc.set_debug(gc.DEBUG_LEAK)
349
e64ac4a0 350 pidfile = open(cfg.pidfile, 'w')
351 pidfile.write(str(os.getpid()))
352 pidfile.close()
353
c0eee1b4 354 main = Erebus(cfg)
bffe0139 355 dbsetup()
db50981b 356
357 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
358 for mod in autoloads:
b9c6eb1d 359 ctlmod.load(main, mod)
db50981b 360
2729abc8 361 c = main.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
362 if c:
4fa1118b 363 rows = c.fetchall()
364 c.close()
365 for row in rows:
0af282c6 366 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
a12f7519 367 main.connectall()
b25d4368 368
369def loop():
49a455aa 370 poready = main.poll()
fd96a423 371 for fileno in poready:
9d44d267
JR
372 try:
373 data = main.fd(fileno).getdata()
374 except:
375 main.log('*', '!', 'Super-mega-emergency: getdata raised exception for socket %d' % (fileno))
376 traceback.print_exc()
377 data = None
378 if data is None:
379 main.fd(fileno).close()
380 else:
381 for line in data:
382 try:
383 main.fd(fileno).parse(line)
384 except:
385 main.log('*', '!', 'Super-mega-emergency: parse raised exception for socket %d data %r' % (fileno, line))
386 traceback.print_exc()
2a44c0cd 387 if main.mustquit is not None:
dc0f891b 388 main.log('*', '!', 'Core exiting due to: %s' % (main.mustquit))
2a44c0cd 389 raise main.mustquit
b25d4368 390
391if __name__ == '__main__':
963f2522 392 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
24b74bb3 393 except: pass
3d724d3a 394 sys.stdout = open('logfile', 'w', 1)
24b74bb3 395 sys.stderr = sys.stdout
b25d4368 396 setup()
49a455aa 397 while True: loop()