]> jfr.im git - erebus.git/blob - erebus.py
fix sql norecurse
[erebus.git] / erebus.py
1 #!/usr/bin/python
2
3 # Erebus IRC bot - Author: John Runyon
4 # main startup code
5
6 import os, sys, select, MySQLdb, MySQLdb.cursors, time, random, gc
7 import bot, config, ctlmod
8
9 class Erebus(object): #singleton to pass around
10 APIVERSION = 2
11 RELEASE = 0
12
13 bots = {}
14 fds = {}
15 numhandlers = {}
16 msghandlers = {}
17 chanhandlers = {}
18 users = {}
19 chans = {}
20
21 class User(object):
22 def __init__(self, nick, auth=None):
23 self.nick = nick
24 self.auth = auth
25 self.checklevel()
26
27 self.chans = []
28
29 def msg(self, *args, **kwargs):
30 main.randbot().msg(self, *args, **kwargs)
31 def slowmsg(self, *args, **kwargs):
32 main.randbot().slowmsg(self, *args, **kwargs)
33 def fastmsg(self, *args, **kwargs):
34 main.randbot().fastmsg(self, *args, **kwargs)
35
36 def isauthed(self):
37 return self.auth is not None
38
39 def authed(self, auth):
40 if auth == '0': self.auth = None
41 else: self.auth = auth.lower()
42 self.checklevel()
43
44 def checklevel(self):
45 if self.auth is None:
46 self.glevel = -1
47 else:
48 c = main.db.cursor()
49 if c.execute("SELECT level FROM users WHERE auth = %s", (self.auth,)):
50 row = c.fetchone()
51 if row is not None:
52 self.glevel = row['level']
53 else:
54 self.glevel = 0
55 else:
56 self.glevel = 0
57 return self.glevel
58
59 def join(self, chan):
60 if chan not in self.chans: self.chans.append(chan)
61 def part(self, chan):
62 try:
63 self.chans.remove(chan)
64 except: pass
65 return len(self.chans) == 0
66 def quit(self):
67 pass
68 def nickchange(self, newnick):
69 self.nick = newnick
70
71 def __str__(self): return self.nick
72 def __repr__(self): return "<User %r (%d)>" % (self.nick,self.glevel)
73
74 class Channel(object):
75 def __init__(self, name, bot):
76 self.name = name
77 self.bot = bot
78 self.levels = {}
79
80 self.users = []
81 self.voices = []
82 self.ops = []
83
84 c = main.db.cursor()
85 if c.execute("SELECT user, level FROM chusers WHERE chan = %s", (self.name,)):
86 row = c.fetchone()
87 while row is not None:
88 self.levels[row['user']] = row['level']
89 row = c.fetchone()
90
91
92 def msg(self, *args, **kwargs):
93 self.bot.msg(self, *args, **kwargs)
94 def slowmsg(self, *args, **kwargs):
95 self.bot.slowmsg(self, *args, **kwargs)
96 def fastmsg(self, *args, **kwargs):
97 self.bot.fastmsg(self, *args, **kwargs)
98
99 def levelof(self, auth):
100 if auth is None:
101 return 0
102 auth = auth.lower()
103 if auth in self.levels:
104 return self.levels[auth]
105 else:
106 return 0
107
108 def setlevel(self, auth, level, savetodb=True):
109 auth = auth.lower()
110 if savetodb:
111 c = main.db.cursor()
112 if c.execute("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self.name, auth, level)):
113 self.levels[auth] = level
114 return True
115 else:
116 return False
117
118 def userjoin(self, user, level=None):
119 if user not in self.users: self.users.append(user)
120 if level == 'op' and user not in self.ops: self.ops.append(user)
121 if level == 'voice' and user not in self.voices: self.voices.append(user)
122 def userpart(self, user):
123 if user in self.ops: self.ops.remove(user)
124 if user in self.voices: self.voices.remove(user)
125 if user in self.users: self.users.remove(user)
126
127 def userop(self, user):
128 if user in self.users and user not in self.ops: self.ops.append(user)
129 def uservoice(self, user):
130 if user in self.users and user not in self.voices: self.voices.append(user)
131 def userdeop(self, user):
132 if user in self.ops: self.ops.remove(user)
133 def userdevoice(self, user):
134 if user in self.voices: self.voices.remove(user)
135
136 def __str__(self): return self.name
137 def __repr__(self): return "<Channel %r>" % (self.name)
138
139 def __init__(self, cfg):
140 self.cfg = cfg
141 self.trigger = cfg.trigger
142 if os.name == "posix":
143 self.potype = "poll"
144 self.po = select.poll()
145 else: # f.e. os.name == "nt" (Windows)
146 self.potype = "select"
147 self.fdlist = []
148
149 def newbot(self, nick, user, bind, authname, authpass, server, port, realname):
150 if bind is None: bind = ''
151 obj = bot.Bot(self, nick, user, bind, authname, authpass, server, port, realname)
152 self.bots[nick.lower()] = obj
153
154 def newfd(self, obj, fileno):
155 self.fds[fileno] = obj
156 if self.potype == "poll":
157 self.po.register(fileno, select.POLLIN)
158 elif self.potype == "select":
159 self.fdlist.append(fileno)
160
161 def bot(self, name): #get Bot() by name (nick)
162 return self.bots[name.lower()]
163 def fd(self, fileno): #get Bot() by fd/fileno
164 return self.fds[fileno]
165 def randbot(self): #get Bot() randomly
166 return self.bots[random.choice(self.bots.keys())]
167
168 def user(self, _nick, justjoined=False, create=True):
169 nick = _nick.lower()
170 if nick in self.users:
171 return self.users[nick]
172 elif create:
173 user = self.User(_nick)
174 self.users[nick] = user
175
176 if justjoined:
177 self.randbot().conn.send("WHO %s n%%ant,1" % (nick))
178
179 return user
180 else:
181 return None
182 def channel(self, name): #get Channel() by name
183 if name.lower() in self.chans:
184 return self.chans[name.lower()]
185 else:
186 return None
187
188 def newchannel(self, bot, name):
189 chan = self.Channel(name.lower(), bot)
190 self.chans[name.lower()] = chan
191 return chan
192
193 def poll(self):
194 if self.potype == "poll":
195 return [fd for (fd, ev) in self.po.poll()]
196 elif self.potype == "select":
197 return select.select(self.fdlist, [], [])[0]
198
199 def connectall(self):
200 for bot in self.bots.itervalues():
201 if bot.conn.state == 0:
202 bot.connect()
203
204 def module(self, name):
205 return ctlmod.modules[name]
206
207 def log(self, source, level, message):
208 print "%09.3f %s [%s] %s" % (time.time() % 100000, source, level, message)
209
210 def getuserbyauth(self, auth):
211 return [u for u in self.users.itervalues() if u.auth == auth.lower()]
212
213 #bind functions
214 def hook(self, word, handler):
215 try:
216 self.msghandlers[word].append(handler)
217 except:
218 self.msghandlers[word] = [handler]
219 def unhook(self, word, handler):
220 if word in self.msghandlers and handler in self.msghandlers[word]:
221 self.msghandlers[word].remove(handler)
222 def hashook(self, word):
223 return word in self.msghandlers and len(self.msghandlers[word]) != 0
224 def gethook(self, word):
225 return self.msghandlers[word]
226
227 def hooknum(self, word, handler):
228 try:
229 self.numhandlers[word].append(handler)
230 except:
231 self.numhandlers[word] = [handler]
232 def unhooknum(self, word, handler):
233 if word in self.numhandlers and handler in self.numhandlers[word]:
234 self.numhandlers[word].remove(handler)
235 def hasnumhook(self, word):
236 return word in self.numhandlers and len(self.numhandlers[word]) != 0
237 def getnumhook(self, word):
238 return self.numhandlers[word]
239
240 def hookchan(self, chan, handler):
241 try:
242 self.chanhandlers[chan].append(handler)
243 except:
244 self.chanhandlers[chan] = [handler]
245 def unhookchan(self, chan, handler):
246 if chan in self.chanhandlers and handler in self.chanhandlers[chan]:
247 self.chanhandlers[chan].remove(handler)
248 def haschanhook(self, chan):
249 return chan in self.chanhandlers and len(self.chanhandlers[chan]) != 0
250 def getchanhook(self, chan):
251 return self.chanhandlers[chan]
252
253
254 class MyCursor(MySQLdb.cursors.DictCursor):
255 def execute(self, *args, **kwargs):
256 if 'norecurse' in kwargs:
257 norecurse = kwargs['norecurse']
258 del kwargs['norecurse']
259 else:
260 norecurse = False
261 main.log("[SQL]", "?", "MyCursor.execute(self, %s, %s)" % (', '.join([repr(i) for i in args]), ', '.join([str(key)+"="+repr(kwargs[key]) for key in kwargs])))
262 # print "%09.3f [SQL] [#] MyCursor.execute(self, %s, %s)" % (time.time() % 100000, ', '.join([repr(i) for i in args]), ', '.join([str(key)+"="+repr(kwargs[key]) for key in kwargs]))
263 try:
264 return super(self.__class__, self).execute(*args, **kwargs)
265 except MySQLdb.MySQLError as e:
266 main.log("[SQL]", "!", "MySQL error! %r" % (e))
267 # print "%09.3f [SQL] [!] MySQL error! %r" % (time.time() % 100000, e)
268 if not norecurse:
269 dbsetup()
270 return self.execute(norecurse=True, *args, **kwargs)
271 return False
272 return True
273
274
275 def dbsetup():
276 main.db = None
277 main.db = MySQLdb.connect(host=cfg.dbhost, user=cfg.dbuser, passwd=cfg.dbpass, db=cfg.dbname, cursorclass=MyCursor)
278
279 def setup():
280 global cfg, main
281
282 cfg = config.setup('bot.config')
283
284 if int(cfg.get('debug', 'gc', default=0)) == 1:
285 gc.set_debug(gc.DEBUG_LEAK)
286
287 pidfile = open(cfg.pidfile, 'w')
288 pidfile.write(str(os.getpid()))
289 pidfile.close()
290
291 main = Erebus(cfg)
292
293 autoloads = [mod for mod, yes in cfg.items('autoloads') if int(yes) == 1]
294 for mod in autoloads:
295 ctlmod.load(main, mod)
296
297 dbsetup()
298 c = main.db.cursor()
299 if c.execute("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1"):
300 rows = c.fetchall()
301 c.close()
302 for row in rows:
303 main.newbot(row['nick'], row['user'], row['bind'], row['authname'], row['authpass'], cfg.host, cfg.port, cfg.realname)
304 main.connectall()
305
306 def loop():
307 poready = main.poll()
308 for fileno in poready:
309 for line in main.fd(fileno).getdata():
310 main.fd(fileno).parse(line)
311
312 if __name__ == '__main__':
313 try: os.rename('logfile', 'oldlogs/%s' % (time.time()))
314 except: pass
315 sys.stdout = open('logfile', 'w', 1)
316 sys.stderr = sys.stdout
317 setup()
318 while True: loop()