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