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