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