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