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