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