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