]> jfr.im git - erebus.git/blame - erebus.py
update bot.config.example
[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
2ffef3ff 9import os, sys, select, MySQLdb, MySQLdb.cursors, time, 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)
a4eacae2 217
43b98e4e 218 def bot(self, name): #get Bot() by name (nick)
49a455aa 219 return self.bots[name.lower()]
43b98e4e 220 def fd(self, fileno): #get Bot() by fd/fileno
49a455aa 221 return self.fds[fileno]
8af0407d 222 def randbot(self): #get Bot() randomly
71ef8273 223 return self.bots[random.choice(list(self.bots.keys()))]
49a455aa 224
3d724d3a 225 def user(self, _nick, justjoined=False, create=True):
c695f740 226 nick = _nick.lower()
b2a896c8 227 if nick in self.users:
228 return self.users[nick]
3d724d3a 229 elif create:
c695f740 230 user = self.User(_nick)
b2a896c8 231 self.users[nick] = user
8af0407d 232
233 if justjoined:
d53d073b 234 self.randbot().conn.send("WHO %s n%%ant,1" % (nick))
8af0407d 235
b2a896c8 236 return user
3d724d3a 237 else:
238 return None
5477b368 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
586997a7 245 def newchannel(self, bot, name):
246 chan = self.Channel(name.lower(), bot)
5477b368 247 self.chans[name.lower()] = chan
248 return chan
49a455aa 249
250 def poll(self):
2a44c0cd 251 timeout_seconds = 30
fd96a423 252 if self.potype == "poll":
2a44c0cd
JR
253 pollres = self.po.poll(timeout_seconds * 1000)
254 return [fd for (fd, ev) in pollres]
fd96a423 255 elif self.potype == "select":
2a44c0cd 256 return select.select(self.fdlist, [], [], timeout_seconds)[0]
49a455aa 257
258 def connectall(self):
a28e2ae9 259 for bot in self.bots.values():
49a455aa 260 if bot.conn.state == 0:
261 bot.connect()
262
fadbf980 263 def module(self, name):
264 return ctlmod.modules[name]
265
a8553c45 266 def log(self, source, level, message):
a28e2ae9 267 print("%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message))
a8553c45 268
f560eb44 269 def getuserbyauth(self, auth):
a28e2ae9 270 return [u for u in self.users.values() if u.auth == auth.lower()]
f560eb44 271
bffe0139 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
49a455aa 279 #bind functions
db50981b 280 def hook(self, word, handler):
e4a4c762 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)
db50981b 288 def hashook(self, word):
e4a4c762 289 return word in self.msghandlers and len(self.msghandlers[word]) != 0
db50981b 290 def gethook(self, word):
291 return self.msghandlers[word]
b25d4368 292
e4a4c762 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
2a1a69a6 306 def hookchan(self, chan, handler):
307 try:
9557ee54 308 self.chanhandlers[chan].append(handler)
2a1a69a6 309 except:
9557ee54 310 self.chanhandlers[chan] = [handler]
2a1a69a6 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]
586997a7 318
e8885384
JR
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
586997a7 328
de89db13 329def dbsetup():
4fa1118b 330 main.db = None
bffe0139 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))
2729abc8 334 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor)
586997a7 335
b25d4368 336def setup():
db50981b 337 global cfg, main
338
48479459 339 cfg = config.Config('bot.config')
e64ac4a0 340
dcc5bde3 341 if cfg.getboolean('debug', 'gc'):
2ffef3ff 342 gc.set_debug(gc.DEBUG_LEAK)
343
e64ac4a0 344 pidfile = open(cfg.pidfile, 'w')
345 pidfile.write(str(os.getpid()))
346 pidfile.close()
347
c0eee1b4 348 main = Erebus(cfg)
bffe0139 349 dbsetup()
db50981b 350
351 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
352 for mod in autoloads:
b9c6eb1d 353 ctlmod.load(main, mod)
db50981b 354
2729abc8 355 c = main.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
356 if c:
4fa1118b 357 rows = c.fetchall()
358 c.close()
359 for row in rows:
0af282c6 360 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
a12f7519 361 main.connectall()
b25d4368 362
363def loop():
49a455aa 364 poready = main.poll()
fd96a423 365 for fileno in poready:
d1ea2946 366 for line in main.fd(fileno).getdata():
367 main.fd(fileno).parse(line)
2a44c0cd 368 if main.mustquit is not None:
dc0f891b 369 main.log('*', '!', 'Core exiting due to: %s' % (main.mustquit))
2a44c0cd 370 raise main.mustquit
b25d4368 371
372if __name__ == '__main__':
963f2522 373 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
24b74bb3 374 except: pass
3d724d3a 375 sys.stdout = open('logfile', 'w', 1)
24b74bb3 376 sys.stderr = sys.stdout
b25d4368 377 setup()
49a455aa 378 while True: loop()