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