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