]> jfr.im git - erebus.git/blob - erebus.py
exception_hook module
[erebus.git] / erebus.py
1 #!/usr/bin/python
2 # vim: fileencoding=utf-8
3
4 # Erebus IRC bot - Author: John Runyon
5 # main startup code
6
7 from __future__ import print_function
8
9 import os, sys, select, MySQLdb, MySQLdb.cursors, time, random, gc
10 import bot, config, ctlmod
11
12 class Erebus(object): #singleton to pass around
13 APIVERSION = 0
14 RELEASE = 0
15
16 bots = {}
17 fds = {}
18 numhandlers = {}
19 msghandlers = {}
20 chanhandlers = {}
21 exceptionhandlers = [] # list of (Exception_class, handler_function) tuples
22 users = {}
23 chans = {}
24
25 class User(object):
26 def __init__(self, nick, auth=None):
27 self.nick = nick
28 if auth is None:
29 self.auth = None
30 else:
31 self.auth = auth.lower()
32 self.checklevel()
33
34 self.chans = []
35
36 def msg(self, *args, **kwargs):
37 main.randbot().msg(self, *args, **kwargs)
38 def slowmsg(self, *args, **kwargs):
39 main.randbot().slowmsg(self, *args, **kwargs)
40 def fastmsg(self, *args, **kwargs):
41 main.randbot().fastmsg(self, *args, **kwargs)
42
43 def isauthed(self):
44 return self.auth is not None
45
46 def authed(self, auth):
47 if auth == '0': self.auth = None
48 else: self.auth = auth.lower()
49 self.checklevel()
50
51 def checklevel(self):
52 if self.auth is None:
53 self.glevel = -1
54 else:
55 c = main.query("SELECT level FROM users WHERE auth = %s", (self.auth,))
56 if c:
57 row = c.fetchone()
58 if row is not None:
59 self.glevel = row['level']
60 else:
61 self.glevel = 0
62 else:
63 self.glevel = 0
64 return self.glevel
65
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
83 def join(self, chan):
84 if chan not in self.chans: self.chans.append(chan)
85 def part(self, chan):
86 try:
87 self.chans.remove(chan)
88 except: pass
89 return len(self.chans) == 0
90 def quit(self):
91 pass
92 def nickchange(self, newnick):
93 self.nick = newnick
94
95 def __str__(self): return self.nick
96 def __repr__(self): return "<User %r (%d)>" % (self.nick, self.glevel)
97
98 class Channel(object):
99 def __init__(self, name, bot):
100 self.name = name
101 self.bot = bot
102 self.levels = {}
103
104 self.users = []
105 self.voices = []
106 self.ops = []
107
108 c = main.query("SELECT user, level FROM chusers WHERE chan = %s", (self.name,))
109 if c:
110 row = c.fetchone()
111 while row is not None:
112 self.levels[row['user']] = row['level']
113 row = c.fetchone()
114
115
116 def msg(self, *args, **kwargs):
117 self.bot.msg(self, *args, **kwargs)
118 def slowmsg(self, *args, **kwargs):
119 self.bot.slowmsg(self, *args, **kwargs)
120 def fastmsg(self, *args, **kwargs):
121 self.bot.fastmsg(self, *args, **kwargs)
122
123 def levelof(self, auth):
124 if auth is None:
125 return 0
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:
135 c = main.query("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self.name, auth, level))
136 if c:
137 self.levels[auth] = level
138 return True
139 else:
140 return False
141 else:
142 self.levels[auth] = level
143 return True
144
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)
153
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
166 def __init__(self, cfg):
167 self.mustquit = None
168 self.starttime = time.time()
169 self.cfg = cfg
170 self.trigger = cfg.trigger
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 = []
177
178 def query(self, *args, **kwargs):
179 if 'noretry' in kwargs:
180 noretry = kwargs['noretry']
181 del kwargs['noretry']
182 else:
183 noretry = False
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))
195 if not noretry:
196 dbsetup()
197 return self.query(*args, noretry=True, **kwargs)
198 else:
199 raise e
200
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
206 def newbot(self, nick, user, bind, authname, authpass, server, port, realname):
207 if bind is None: bind = ''
208 obj = bot.Bot(self, nick, user, bind, authname, authpass, server, port, realname)
209 self.bots[nick.lower()] = obj
210
211 def newfd(self, obj, fileno):
212 self.fds[fileno] = obj
213 if self.potype == "poll":
214 self.po.register(fileno, select.POLLIN)
215 elif self.potype == "select":
216 self.fdlist.append(fileno)
217
218 def bot(self, name): #get Bot() by name (nick)
219 return self.bots[name.lower()]
220 def fd(self, fileno): #get Bot() by fd/fileno
221 return self.fds[fileno]
222 def randbot(self): #get Bot() randomly
223 return self.bots[random.choice(list(self.bots.keys()))]
224
225 def user(self, _nick, justjoined=False, create=True):
226 nick = _nick.lower()
227 if nick in self.users:
228 return self.users[nick]
229 elif create:
230 user = self.User(_nick)
231 self.users[nick] = user
232
233 if justjoined:
234 self.randbot().conn.send("WHO %s n%%ant,1" % (nick))
235
236 return user
237 else:
238 return None
239 def channel(self, name): #get Channel() by name
240 if name.lower() in self.chans:
241 return self.chans[name.lower()]
242 else:
243 return None
244
245 def newchannel(self, bot, name):
246 chan = self.Channel(name.lower(), bot)
247 self.chans[name.lower()] = chan
248 return chan
249
250 def poll(self):
251 timeout_seconds = 30
252 if self.potype == "poll":
253 pollres = self.po.poll(timeout_seconds * 1000)
254 return [fd for (fd, ev) in pollres]
255 elif self.potype == "select":
256 return select.select(self.fdlist, [], [], timeout_seconds)[0]
257
258 def connectall(self):
259 for bot in self.bots.values():
260 if bot.conn.state == 0:
261 bot.connect()
262
263 def module(self, name):
264 return ctlmod.modules[name]
265
266 def log(self, source, level, message):
267 print("%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message))
268
269 def getuserbyauth(self, auth):
270 return [u for u in self.users.values() if u.auth == auth.lower()]
271
272 def getdb(self):
273 """Get a DB object. The object must be returned to the pool after us, using returndb()."""
274 return self.dbs.pop()
275
276 def returndb(self, db):
277 self.dbs.append(db)
278
279 #bind functions
280 def hook(self, word, handler):
281 try:
282 self.msghandlers[word].append(handler)
283 except:
284 self.msghandlers[word] = [handler]
285 def unhook(self, word, handler):
286 if word in self.msghandlers and handler in self.msghandlers[word]:
287 self.msghandlers[word].remove(handler)
288 def hashook(self, word):
289 return word in self.msghandlers and len(self.msghandlers[word]) != 0
290 def gethook(self, word):
291 return self.msghandlers[word]
292
293 def hooknum(self, word, handler):
294 try:
295 self.numhandlers[word].append(handler)
296 except:
297 self.numhandlers[word] = [handler]
298 def unhooknum(self, word, handler):
299 if word in self.numhandlers and handler in self.numhandlers[word]:
300 self.numhandlers[word].remove(handler)
301 def hasnumhook(self, word):
302 return word in self.numhandlers and len(self.numhandlers[word]) != 0
303 def getnumhook(self, word):
304 return self.numhandlers[word]
305
306 def hookchan(self, chan, handler):
307 try:
308 self.chanhandlers[chan].append(handler)
309 except:
310 self.chanhandlers[chan] = [handler]
311 def unhookchan(self, chan, handler):
312 if chan in self.chanhandlers and handler in self.chanhandlers[chan]:
313 self.chanhandlers[chan].remove(handler)
314 def haschanhook(self, chan):
315 return chan in self.chanhandlers and len(self.chanhandlers[chan]) != 0
316 def getchanhook(self, chan):
317 return self.chanhandlers[chan]
318
319 def hookexception(self, exc, handler):
320 self.exceptionhandlers.append((exc, handler))
321 def unhookexception(self, exc, handler):
322 self.exceptionhandlers.remove((exc, handler))
323 def hasexceptionhook(self, exc):
324 return any((True for x,h in self.exceptionhandlers if isinstance(exc, x)))
325 def getexceptionhook(self, exc):
326 return (h for x,h in self.exceptionhandlers if isinstance(exc, x))
327
328
329 def dbsetup():
330 main.db = None
331 main.dbs = []
332 for i in range(cfg.get('erebus', 'num_db_connections', 2)-1):
333 main.dbs.append(MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor))
334 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor)
335
336 def setup():
337 global cfg, main
338
339 cfg = config.Config('bot.config')
340
341 if cfg.getboolean('debug', 'gc'):
342 gc.set_debug(gc.DEBUG_LEAK)
343
344 pidfile = open(cfg.pidfile, 'w')
345 pidfile.write(str(os.getpid()))
346 pidfile.close()
347
348 main = Erebus(cfg)
349 dbsetup()
350
351 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
352 for mod in autoloads:
353 ctlmod.load(main, mod)
354
355 c = main.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
356 if c:
357 rows = c.fetchall()
358 c.close()
359 for row in rows:
360 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
361 main.connectall()
362
363 def loop():
364 poready = main.poll()
365 for fileno in poready:
366 for line in main.fd(fileno).getdata():
367 main.fd(fileno).parse(line)
368 if main.mustquit is not None:
369 main.log('*', '!', 'Core exiting due to: %s' % (main.mustquit))
370 raise main.mustquit
371
372 if __name__ == '__main__':
373 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
374 except: pass
375 sys.stdout = open('logfile', 'w', 1)
376 sys.stderr = sys.stdout
377 setup()
378 while True: loop()