]> jfr.im git - erebus.git/blob - erebus.py
add admin_channel
[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, traceback, 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 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)
223
224 def bot(self, name): #get Bot() by name (nick)
225 return self.bots[name.lower()]
226 def fd(self, fileno): #get Bot() by fd/fileno
227 return self.fds[fileno]
228 def randbot(self): #get Bot() randomly
229 return self.bots[random.choice(list(self.bots.keys()))]
230
231 def user(self, _nick, send_who=False, create=True):
232 nick = _nick.lower()
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
237 if nick in self.users:
238 return self.users[nick]
239 elif create:
240 user = self.User(_nick)
241 self.users[nick] = user
242 return user
243 else:
244 return None
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
251 def newchannel(self, bot, name):
252 chan = self.Channel(name.lower(), bot)
253 self.chans[name.lower()] = chan
254 return chan
255
256 def poll(self):
257 timeout_seconds = 30
258 if self.potype == "poll":
259 pollres = self.po.poll(timeout_seconds * 1000)
260 return [fd for (fd, ev) in pollres]
261 elif self.potype == "select":
262 return select.select(self.fdlist, [], [], timeout_seconds)[0]
263
264 def connectall(self):
265 for bot in self.bots.values():
266 if bot.conn.state == 0:
267 bot.connect()
268
269 def module(self, name):
270 return ctlmod.modules[name]
271
272 def log(self, source, level, message):
273 print("%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message))
274
275 def getuserbyauth(self, auth):
276 return [u for u in self.users.values() if u.auth == auth.lower()]
277
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
285 #bind functions
286 def hook(self, word, handler):
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)
294 def hashook(self, word):
295 return word in self.msghandlers and len(self.msghandlers[word]) != 0
296 def gethook(self, word):
297 return self.msghandlers[word]
298
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
312 def hookchan(self, chan, handler):
313 try:
314 self.chanhandlers[chan].append(handler)
315 except:
316 self.chanhandlers[chan] = [handler]
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]
324
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
334
335 def dbsetup():
336 main.db = None
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))
340 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor)
341
342 def setup():
343 global cfg, main
344
345 cfg = config.Config('bot.config')
346
347 if cfg.getboolean('debug', 'gc'):
348 gc.set_debug(gc.DEBUG_LEAK)
349
350 pidfile = open(cfg.pidfile, 'w')
351 pidfile.write(str(os.getpid()))
352 pidfile.close()
353
354 main = Erebus(cfg)
355 dbsetup()
356
357 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
358 for mod in autoloads:
359 ctlmod.load(main, mod)
360
361 c = main.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
362 if c:
363 rows = c.fetchall()
364 c.close()
365 for row in rows:
366 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
367 main.connectall()
368
369 def loop():
370 poready = main.poll()
371 for fileno in poready:
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()
387 if main.mustquit is not None:
388 main.log('*', '!', 'Core exiting due to: %s' % (main.mustquit))
389 raise main.mustquit
390
391 if __name__ == '__main__':
392 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
393 except: pass
394 sys.stdout = open('logfile', 'w', 1)
395 sys.stderr = sys.stdout
396 setup()
397 while True: loop()