]>
jfr.im git - erebus.git/blob - erebus.py
2 # vim: fileencoding=utf-8
4 # Erebus IRC bot - Author: John Runyon
7 from __future__
import print_function
9 import os
, sys
, select
, MySQLdb
, MySQLdb
.cursors
, time
, random
, gc
10 import bot
, config
, ctlmod
12 class Erebus(object): #singleton to pass around
25 def __init__(self
, nick
, auth
=None):
30 self
.auth
= auth
.lower()
35 def msg(self
, *args
, **kwargs
):
36 main
.randbot().msg(self
, *args
, **kwargs
)
37 def slowmsg(self
, *args
, **kwargs
):
38 main
.randbot().slowmsg(self
, *args
, **kwargs
)
39 def fastmsg(self
, *args
, **kwargs
):
40 main
.randbot().fastmsg(self
, *args
, **kwargs
)
43 return self
.auth
is not None
45 def authed(self
, auth
):
46 if auth
== '0': self
.auth
= None
47 else: self
.auth
= auth
.lower()
54 c
= main
.query("SELECT level FROM users WHERE auth = %s", (self
.auth
,))
58 self
.glevel
= row
['level']
65 def setlevel(self
, level
, savetodb
=True):
68 c
= main
.query("REPLACE INTO users (auth, level) VALUES (%s, %s)", (self
.auth
, level
))
70 c
= main
.query("DELETE FROM users WHERE auth = %s", (self
.auth
,))
71 if c
== 0: # no rows affected
83 if chan
not in self
.chans
: self
.chans
.append(chan
)
86 self
.chans
.remove(chan
)
88 return len(self
.chans
) == 0
91 def nickchange(self
, newnick
):
94 def __str__(self
): return self
.nick
95 def __repr__(self
): return "<User %r (%d)>" % (self
.nick
, self
.glevel
)
97 class Channel(object):
98 def __init__(self
, name
, bot
):
107 c
= main
.query("SELECT user, level FROM chusers WHERE chan = %s", (self
.name
,))
110 while row
is not None:
111 self
.levels
[row
['user']] = row
['level']
115 def msg(self
, *args
, **kwargs
):
116 self
.bot
.msg(self
, *args
, **kwargs
)
117 def slowmsg(self
, *args
, **kwargs
):
118 self
.bot
.slowmsg(self
, *args
, **kwargs
)
119 def fastmsg(self
, *args
, **kwargs
):
120 self
.bot
.fastmsg(self
, *args
, **kwargs
)
122 def levelof(self
, auth
):
126 if auth
in self
.levels
:
127 return self
.levels
[auth
]
131 def setlevel(self
, auth
, level
, savetodb
=True):
134 c
= main
.query("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self
.name
, auth
, level
))
136 self
.levels
[auth
] = level
141 self
.levels
[auth
] = level
144 def userjoin(self
, user
, level
=None):
145 if user
not in self
.users
: self
.users
.append(user
)
146 if level
== 'op' and user
not in self
.ops
: self
.ops
.append(user
)
147 if level
== 'voice' and user
not in self
.voices
: self
.voices
.append(user
)
148 def userpart(self
, user
):
149 if user
in self
.ops
: self
.ops
.remove(user
)
150 if user
in self
.voices
: self
.voices
.remove(user
)
151 if user
in self
.users
: self
.users
.remove(user
)
153 def userop(self
, user
):
154 if user
in self
.users
and user
not in self
.ops
: self
.ops
.append(user
)
155 def uservoice(self
, user
):
156 if user
in self
.users
and user
not in self
.voices
: self
.voices
.append(user
)
157 def userdeop(self
, user
):
158 if user
in self
.ops
: self
.ops
.remove(user
)
159 def userdevoice(self
, user
):
160 if user
in self
.voices
: self
.voices
.remove(user
)
162 def __str__(self
): return self
.name
163 def __repr__(self
): return "<Channel %r>" % (self
.name
)
165 def __init__(self
, cfg
):
167 self
.starttime
= time
.time()
169 self
.trigger
= cfg
.trigger
170 if os
.name
== "posix":
172 self
.po
= select
.poll()
173 else: # f.e. os.name == "nt" (Windows)
174 self
.potype
= "select"
177 def query(self
, *args
, **kwargs
):
178 if 'noretry' in kwargs
:
179 noretry
= kwargs
['noretry']
180 del kwargs
['noretry']
184 self
.log("[SQL]", "?", "query(%s, %s)" % (', '.join([repr(i
) for i
in args
]), ', '.join([str(key
)+"="+repr(kwargs
[key
]) for key
in kwargs
])))
186 curs
= self
.db
.cursor()
187 res
= curs
.execute(*args
, **kwargs
)
192 except MySQLdb
.MySQLError
as e
:
193 self
.log("[SQL]", "!", "MySQL error! %r" % (e
))
196 return self
.query(*args
, noretry
=True, **kwargs
)
200 def querycb(self
, cb
, *args
, **kwargs
):
202 cb(self
.query(*args
, **kwargs
))
203 threading
.Thread(target
=run_query
).start()
205 def newbot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
):
206 if bind
is None: bind
= ''
207 obj
= bot
.Bot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
)
208 self
.bots
[nick
.lower()] = obj
210 def newfd(self
, obj
, fileno
):
211 self
.fds
[fileno
] = obj
212 if self
.potype
== "poll":
213 self
.po
.register(fileno
, select
.POLLIN
)
214 elif self
.potype
== "select":
215 self
.fdlist
.append(fileno
)
217 def bot(self
, name
): #get Bot() by name (nick)
218 return self
.bots
[name
.lower()]
219 def fd(self
, fileno
): #get Bot() by fd/fileno
220 return self
.fds
[fileno
]
221 def randbot(self
): #get Bot() randomly
222 return self
.bots
[random
.choice(list(self
.bots
.keys()))]
224 def user(self
, _nick
, justjoined
=False, create
=True):
226 if nick
in self
.users
:
227 return self
.users
[nick
]
229 user
= self
.User(_nick
)
230 self
.users
[nick
] = user
233 self
.randbot().conn
.send("WHO %s n%%ant,1" % (nick
))
238 def channel(self
, name
): #get Channel() by name
239 if name
.lower() in self
.chans
:
240 return self
.chans
[name
.lower()]
244 def newchannel(self
, bot
, name
):
245 chan
= self
.Channel(name
.lower(), bot
)
246 self
.chans
[name
.lower()] = chan
251 if self
.potype
== "poll":
252 pollres
= self
.po
.poll(timeout_seconds
* 1000)
253 return [fd
for (fd
, ev
) in pollres
]
254 elif self
.potype
== "select":
255 return select
.select(self
.fdlist
, [], [], timeout_seconds
)[0]
257 def connectall(self
):
258 for bot
in self
.bots
.values():
259 if bot
.conn
.state
== 0:
262 def module(self
, name
):
263 return ctlmod
.modules
[name
]
265 def log(self
, source
, level
, message
):
266 print("%09.3f %s [%s] %s" % (time
.time() % 100000, source
, level
, message
))
268 def getuserbyauth(self
, auth
):
269 return [u
for u
in self
.users
.values() if u
.auth
== auth
.lower()]
272 """Get a DB object. The object must be returned to the pool after us, using returndb()."""
273 return self
.dbs
.pop()
275 def returndb(self
, db
):
279 def hook(self
, word
, handler
):
281 self
.msghandlers
[word
].append(handler
)
283 self
.msghandlers
[word
] = [handler
]
284 def unhook(self
, word
, handler
):
285 if word
in self
.msghandlers
and handler
in self
.msghandlers
[word
]:
286 self
.msghandlers
[word
].remove(handler
)
287 def hashook(self
, word
):
288 return word
in self
.msghandlers
and len(self
.msghandlers
[word
]) != 0
289 def gethook(self
, word
):
290 return self
.msghandlers
[word
]
292 def hooknum(self
, word
, handler
):
294 self
.numhandlers
[word
].append(handler
)
296 self
.numhandlers
[word
] = [handler
]
297 def unhooknum(self
, word
, handler
):
298 if word
in self
.numhandlers
and handler
in self
.numhandlers
[word
]:
299 self
.numhandlers
[word
].remove(handler
)
300 def hasnumhook(self
, word
):
301 return word
in self
.numhandlers
and len(self
.numhandlers
[word
]) != 0
302 def getnumhook(self
, word
):
303 return self
.numhandlers
[word
]
305 def hookchan(self
, chan
, handler
):
307 self
.chanhandlers
[chan
].append(handler
)
309 self
.chanhandlers
[chan
] = [handler
]
310 def unhookchan(self
, chan
, handler
):
311 if chan
in self
.chanhandlers
and handler
in self
.chanhandlers
[chan
]:
312 self
.chanhandlers
[chan
].remove(handler
)
313 def haschanhook(self
, chan
):
314 return chan
in self
.chanhandlers
and len(self
.chanhandlers
[chan
]) != 0
315 def getchanhook(self
, chan
):
316 return self
.chanhandlers
[chan
]
322 for i
in range(cfg
.get('erebus', 'num_db_connections', 2)-1):
323 main
.dbs
.append(MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
))
324 main
.db
= MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
)
329 cfg
= config
.Config('bot.config')
331 if cfg
.getboolean('debug', 'gc'):
332 gc
.set_debug(gc
.DEBUG_LEAK
)
334 pidfile
= open(cfg
.pidfile
, 'w')
335 pidfile
.write(str(os
.getpid()))
341 autoloads
= [mod
for mod
, yes
in cfg
.items('autoloads') if int(yes
) == 1]
342 for mod
in autoloads
:
343 ctlmod
.load(main
, mod
)
345 c
= main
.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
350 main
.newbot(row
['nick'], row
['user'], row
['bind'], row
['authname'], row
['authpass'], cfg
.host
, cfg
.port
, cfg
.realname
)
354 poready
= main
.poll()
355 for fileno
in poready
:
356 for line
in main
.fd(fileno
).getdata():
357 main
.fd(fileno
).parse(line
)
358 if main
.mustquit
is not None:
359 main
.log('*', '!', 'Core exiting due to: %s' % (main
.mustquit
))
362 if __name__
== '__main__':
363 try: os
.rename('logfile', 'oldlogs/%s' % (time
.time()))
365 sys
.stdout
= open('logfile', 'w', 1)
366 sys
.stderr
= sys
.stdout