]>
jfr.im git - erebus.git/blob - erebus.py
4b33231725bdafa149c7bf4e034a12e9c542f24b
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):
32 def msg(self
, *args
, **kwargs
):
33 main
.randbot().msg(self
, *args
, **kwargs
)
34 def slowmsg(self
, *args
, **kwargs
):
35 main
.randbot().slowmsg(self
, *args
, **kwargs
)
36 def fastmsg(self
, *args
, **kwargs
):
37 main
.randbot().fastmsg(self
, *args
, **kwargs
)
40 return self
.auth
is not None
42 def authed(self
, auth
):
43 if auth
== '0': self
.auth
= None
44 else: self
.auth
= auth
.lower()
51 c
= main
.query("SELECT level FROM users WHERE auth = %s", (self
.auth
,))
55 self
.glevel
= row
['level']
63 if chan
not in self
.chans
: self
.chans
.append(chan
)
66 self
.chans
.remove(chan
)
68 return len(self
.chans
) == 0
71 def nickchange(self
, newnick
):
74 def __str__(self
): return self
.nick
75 def __repr__(self
): return "<User %r (%d)>" % (self
.nick
, self
.glevel
)
77 class Channel(object):
78 def __init__(self
, name
, bot
):
87 c
= main
.query("SELECT user, level FROM chusers WHERE chan = %s", (self
.name
,))
90 while row
is not None:
91 self
.levels
[row
['user']] = row
['level']
95 def msg(self
, *args
, **kwargs
):
96 self
.bot
.msg(self
, *args
, **kwargs
)
97 def slowmsg(self
, *args
, **kwargs
):
98 self
.bot
.slowmsg(self
, *args
, **kwargs
)
99 def fastmsg(self
, *args
, **kwargs
):
100 self
.bot
.fastmsg(self
, *args
, **kwargs
)
102 def levelof(self
, auth
):
106 if auth
in self
.levels
:
107 return self
.levels
[auth
]
111 def setlevel(self
, auth
, level
, savetodb
=True):
114 c
= main
.query("REPLACE INTO chusers (chan, user, level) VALUES (%s, %s, %s)", (self
.name
, auth
, level
))
116 self
.levels
[auth
] = level
121 def userjoin(self
, user
, level
=None):
122 if user
not in self
.users
: self
.users
.append(user
)
123 if level
== 'op' and user
not in self
.ops
: self
.ops
.append(user
)
124 if level
== 'voice' and user
not in self
.voices
: self
.voices
.append(user
)
125 def userpart(self
, user
):
126 if user
in self
.ops
: self
.ops
.remove(user
)
127 if user
in self
.voices
: self
.voices
.remove(user
)
128 if user
in self
.users
: self
.users
.remove(user
)
130 def userop(self
, user
):
131 if user
in self
.users
and user
not in self
.ops
: self
.ops
.append(user
)
132 def uservoice(self
, user
):
133 if user
in self
.users
and user
not in self
.voices
: self
.voices
.append(user
)
134 def userdeop(self
, user
):
135 if user
in self
.ops
: self
.ops
.remove(user
)
136 def userdevoice(self
, user
):
137 if user
in self
.voices
: self
.voices
.remove(user
)
139 def __str__(self
): return self
.name
140 def __repr__(self
): return "<Channel %r>" % (self
.name
)
142 def __init__(self
, cfg
):
144 self
.starttime
= time
.time()
146 self
.trigger
= cfg
.trigger
147 if os
.name
== "posix":
149 self
.po
= select
.poll()
150 else: # f.e. os.name == "nt" (Windows)
151 self
.potype
= "select"
154 def query(self
, *args
, **kwargs
):
155 if 'noretry' in kwargs
:
156 noretry
= kwargs
['noretry']
157 del kwargs
['noretry']
161 self
.log("[SQL]", "?", "query(%s, %s)" % (', '.join([repr(i
) for i
in args
]), ', '.join([str(key
)+"="+repr(kwargs
[key
]) for key
in kwargs
])))
163 curs
= self
.db
.cursor()
164 res
= curs
.execute(*args
, **kwargs
)
169 except MySQLdb
.MySQLError
as e
:
170 self
.log("[SQL]", "!", "MySQL error! %r" % (e
))
173 return self
.query(*args
, noretry
=True, **kwargs
)
177 def querycb(self
, cb
, *args
, **kwargs
):
179 cb(self
.query(*args
, **kwargs
))
180 threading
.Thread(target
=run_query
).start()
182 def newbot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
):
183 if bind
is None: bind
= ''
184 obj
= bot
.Bot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
)
185 self
.bots
[nick
.lower()] = obj
187 def newfd(self
, obj
, fileno
):
188 self
.fds
[fileno
] = obj
189 if self
.potype
== "poll":
190 self
.po
.register(fileno
, select
.POLLIN
)
191 elif self
.potype
== "select":
192 self
.fdlist
.append(fileno
)
194 def bot(self
, name
): #get Bot() by name (nick)
195 return self
.bots
[name
.lower()]
196 def fd(self
, fileno
): #get Bot() by fd/fileno
197 return self
.fds
[fileno
]
198 def randbot(self
): #get Bot() randomly
199 return self
.bots
[random
.choice(list(self
.bots
.keys()))]
201 def user(self
, _nick
, justjoined
=False, create
=True):
203 if nick
in self
.users
:
204 return self
.users
[nick
]
206 user
= self
.User(_nick
)
207 self
.users
[nick
] = user
210 self
.randbot().conn
.send("WHO %s n%%ant,1" % (nick
))
215 def channel(self
, name
): #get Channel() by name
216 if name
.lower() in self
.chans
:
217 return self
.chans
[name
.lower()]
221 def newchannel(self
, bot
, name
):
222 chan
= self
.Channel(name
.lower(), bot
)
223 self
.chans
[name
.lower()] = chan
228 if self
.potype
== "poll":
229 pollres
= self
.po
.poll(timeout_seconds
* 1000)
230 return [fd
for (fd
, ev
) in pollres
]
231 elif self
.potype
== "select":
232 return select
.select(self
.fdlist
, [], [], timeout_seconds
)[0]
234 def connectall(self
):
235 for bot
in self
.bots
.values():
236 if bot
.conn
.state
== 0:
239 def module(self
, name
):
240 return ctlmod
.modules
[name
]
242 def log(self
, source
, level
, message
):
243 print("%09.3f %s [%s] %s" % (time
.time() % 100000, source
, level
, message
))
245 def getuserbyauth(self
, auth
):
246 return [u
for u
in self
.users
.values() if u
.auth
== auth
.lower()]
249 """Get a DB object. The object must be returned to the pool after us, using returndb()."""
250 return self
.dbs
.pop()
252 def returndb(self
, db
):
256 def hook(self
, word
, handler
):
258 self
.msghandlers
[word
].append(handler
)
260 self
.msghandlers
[word
] = [handler
]
261 def unhook(self
, word
, handler
):
262 if word
in self
.msghandlers
and handler
in self
.msghandlers
[word
]:
263 self
.msghandlers
[word
].remove(handler
)
264 def hashook(self
, word
):
265 return word
in self
.msghandlers
and len(self
.msghandlers
[word
]) != 0
266 def gethook(self
, word
):
267 return self
.msghandlers
[word
]
269 def hooknum(self
, word
, handler
):
271 self
.numhandlers
[word
].append(handler
)
273 self
.numhandlers
[word
] = [handler
]
274 def unhooknum(self
, word
, handler
):
275 if word
in self
.numhandlers
and handler
in self
.numhandlers
[word
]:
276 self
.numhandlers
[word
].remove(handler
)
277 def hasnumhook(self
, word
):
278 return word
in self
.numhandlers
and len(self
.numhandlers
[word
]) != 0
279 def getnumhook(self
, word
):
280 return self
.numhandlers
[word
]
282 def hookchan(self
, chan
, handler
):
284 self
.chanhandlers
[chan
].append(handler
)
286 self
.chanhandlers
[chan
] = [handler
]
287 def unhookchan(self
, chan
, handler
):
288 if chan
in self
.chanhandlers
and handler
in self
.chanhandlers
[chan
]:
289 self
.chanhandlers
[chan
].remove(handler
)
290 def haschanhook(self
, chan
):
291 return chan
in self
.chanhandlers
and len(self
.chanhandlers
[chan
]) != 0
292 def getchanhook(self
, chan
):
293 return self
.chanhandlers
[chan
]
299 for i
in range(cfg
.get('erebus', 'num_db_connections', 2)-1):
300 main
.dbs
.append(MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
))
301 main
.db
= MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
)
306 cfg
= config
.Config('bot.config')
308 if cfg
.getboolean('debug', 'gc'):
309 gc
.set_debug(gc
.DEBUG_LEAK
)
311 pidfile
= open(cfg
.pidfile
, 'w')
312 pidfile
.write(str(os
.getpid()))
318 autoloads
= [mod
for mod
, yes
in cfg
.items('autoloads') if int(yes
) == 1]
319 for mod
in autoloads
:
320 ctlmod
.load(main
, mod
)
322 c
= main
.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
327 main
.newbot(row
['nick'], row
['user'], row
['bind'], row
['authname'], row
['authpass'], cfg
.host
, cfg
.port
, cfg
.realname
)
331 poready
= main
.poll()
332 for fileno
in poready
:
333 for line
in main
.fd(fileno
).getdata():
334 main
.fd(fileno
).parse(line
)
335 if main
.mustquit
is not None:
338 if __name__
== '__main__':
339 try: os
.rename('logfile', 'oldlogs/%s' % (time
.time()))
341 sys
.stdout
= open('logfile', 'w', 1)
342 sys
.stderr
= sys
.stdout