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