]> jfr.im git - erebus.git/blob - erebus.py
remove __module__ from urls because it breaks on some things i love you python its...
[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 users = {}
22 chans = {}
23
24 class User(object):
25 def __init__(self, nick, auth=None):
26 self.nick = nick
27 if auth is None:
28 self.auth = None
29 else:
30 self.auth = auth.lower()
31 self.checklevel()
32
33 self.chans = []
34
35 def msg(self, *args, **kwargs):
36 main.randbot().msg(self, *args, **kwargs)
37 def slowmsg(self, *args, **kwargs):
38 main.randbot().slowmsg(self, *args, **kwargs)
39 def fastmsg(self, *args, **kwargs):
40 main.randbot().fastmsg(self, *args, **kwargs)
41
42 def isauthed(self):
43 return self.auth is not None
44
45 def authed(self, auth):
46 if auth == '0': self.auth = None
47 else: self.auth = auth.lower()
48 self.checklevel()
49
50 def checklevel(self):
51 if self.auth is None:
52 self.glevel = -1
53 else:
54 c = main.query("SELECT level FROM users WHERE auth = %s", (self.auth,))
55 if c:
56 row = c.fetchone()
57 if row is not None:
58 self.glevel = row['level']
59 else:
60 self.glevel = 0
61 else:
62 self.glevel = 0
63 return self.glevel
64
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
82 def join(self, chan):
83 if chan not in self.chans: self.chans.append(chan)
84 def part(self, chan):
85 try:
86 self.chans.remove(chan)
87 except: pass
88 return len(self.chans) == 0
89 def quit(self):
90 pass
91 def nickchange(self, newnick):
92 self.nick = newnick
93
94 def __str__(self): return self.nick
95 def __repr__(self): return "<User %r (%d)>" % (self.nick, self.glevel)
96
97 class Channel(object):
98 def __init__(self, name, bot):
99 self.name = name
100 self.bot = bot
101 self.levels = {}
102
103 self.users = []
104 self.voices = []
105 self.ops = []
106
107 c = main.query("SELECT user, level FROM chusers WHERE chan = %s", (self.name,))
108 if c:
109 row = c.fetchone()
110 while row is not None:
111 self.levels[row['user']] = row['level']
112 row = c.fetchone()
113
114
115 def msg(self, *args, **kwargs):
116 self.bot.msg(self, *args, **kwargs)
117 def slowmsg(self, *args, **kwargs):
118 self.bot.slowmsg(self, *args, **kwargs)
119 def fastmsg(self, *args, **kwargs):
120 self.bot.fastmsg(self, *args, **kwargs)
121
122 def levelof(self, auth):
123 if auth is None:
124 return 0
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:
134 c = main.query("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self.name, auth, level))
135 if c:
136 self.levels[auth] = level
137 return True
138 else:
139 return False
140 else:
141 self.levels[auth] = level
142 return True
143
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)
152
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
165 def __init__(self, cfg):
166 self.mustquit = None
167 self.starttime = time.time()
168 self.cfg = cfg
169 self.trigger = cfg.trigger
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 = []
176
177 def query(self, *args, **kwargs):
178 if 'noretry' in kwargs:
179 noretry = kwargs['noretry']
180 del kwargs['noretry']
181 else:
182 noretry = False
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))
194 if not noretry:
195 dbsetup()
196 return self.query(*args, noretry=True, **kwargs)
197 else:
198 raise e
199
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
205 def newbot(self, nick, user, bind, authname, authpass, server, port, realname):
206 if bind is None: bind = ''
207 obj = bot.Bot(self, nick, user, bind, authname, authpass, server, port, realname)
208 self.bots[nick.lower()] = obj
209
210 def newfd(self, obj, fileno):
211 self.fds[fileno] = obj
212 if self.potype == "poll":
213 self.po.register(fileno, select.POLLIN)
214 elif self.potype == "select":
215 self.fdlist.append(fileno)
216
217 def bot(self, name): #get Bot() by name (nick)
218 return self.bots[name.lower()]
219 def fd(self, fileno): #get Bot() by fd/fileno
220 return self.fds[fileno]
221 def randbot(self): #get Bot() randomly
222 return self.bots[random.choice(list(self.bots.keys()))]
223
224 def user(self, _nick, justjoined=False, create=True):
225 nick = _nick.lower()
226 if nick in self.users:
227 return self.users[nick]
228 elif create:
229 user = self.User(_nick)
230 self.users[nick] = user
231
232 if justjoined:
233 self.randbot().conn.send("WHO %s n%%ant,1" % (nick))
234
235 return user
236 else:
237 return None
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
244 def newchannel(self, bot, name):
245 chan = self.Channel(name.lower(), bot)
246 self.chans[name.lower()] = chan
247 return chan
248
249 def poll(self):
250 timeout_seconds = 30
251 if self.potype == "poll":
252 pollres = self.po.poll(timeout_seconds * 1000)
253 return [fd for (fd, ev) in pollres]
254 elif self.potype == "select":
255 return select.select(self.fdlist, [], [], timeout_seconds)[0]
256
257 def connectall(self):
258 for bot in self.bots.values():
259 if bot.conn.state == 0:
260 bot.connect()
261
262 def module(self, name):
263 return ctlmod.modules[name]
264
265 def log(self, source, level, message):
266 print("%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message))
267
268 def getuserbyauth(self, auth):
269 return [u for u in self.users.values() if u.auth == auth.lower()]
270
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
278 #bind functions
279 def hook(self, word, handler):
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)
287 def hashook(self, word):
288 return word in self.msghandlers and len(self.msghandlers[word]) != 0
289 def gethook(self, word):
290 return self.msghandlers[word]
291
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
305 def hookchan(self, chan, handler):
306 try:
307 self.chanhandlers[chan].append(handler)
308 except:
309 self.chanhandlers[chan] = [handler]
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]
317
318
319 def dbsetup():
320 main.db = None
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))
324 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MySQLdb.cursors.DictCursor)
325
326 def setup():
327 global cfg, main
328
329 cfg = config.Config('bot.config')
330
331 if cfg.getboolean('debug', 'gc'):
332 gc.set_debug(gc.DEBUG_LEAK)
333
334 pidfile = open(cfg.pidfile, 'w')
335 pidfile.write(str(os.getpid()))
336 pidfile.close()
337
338 main = Erebus(cfg)
339 dbsetup()
340
341 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
342 for mod in autoloads:
343 ctlmod.load(main, mod)
344
345 c = main.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
346 if c:
347 rows = c.fetchall()
348 c.close()
349 for row in rows:
350 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
351 main.connectall()
352
353 def loop():
354 poready = main.poll()
355 for fileno in poready:
356 for line in main.fd(fileno).getdata():
357 main.fd(fileno).parse(line)
358 if main.mustquit is not None:
359 main.log('*', '!', 'Core exiting due to: %s' % (main.mustquit))
360 raise main.mustquit
361
362 if __name__ == '__main__':
363 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
364 except: pass
365 sys.stdout = open('logfile', 'w', 1)
366 sys.stderr = sys.stdout
367 setup()
368 while True: loop()