]>
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):
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
):
143 self
.starttime
= time
.time()
145 self
.trigger
= cfg
.trigger
146 if os
.name
== "posix":
148 self
.po
= select
.poll()
149 else: # f.e. os.name == "nt" (Windows)
150 self
.potype
= "select"
153 def query(self
, *args
, **kwargs
):
154 if 'noretry' in kwargs
:
155 noretry
= kwargs
['noretry']
156 del kwargs
['noretry']
160 self
.log("[SQL]", "?", "query(%s, %s)" % (', '.join([repr(i
) for i
in args
]), ', '.join([str(key
)+"="+repr(kwargs
[key
]) for key
in kwargs
])))
162 curs
= self
.db
.cursor()
163 res
= curs
.execute(*args
, **kwargs
)
168 except MySQLdb
.MySQLError
as e
:
169 self
.log("[SQL]", "!", "MySQL error! %r" % (e
))
172 return self
.query(*args
, noretry
=True, **kwargs
)
176 def querycb(self
, cb
, *args
, **kwargs
):
178 cb(self
.query(*args
, **kwargs
))
179 threading
.Thread(target
=run_query
).start()
181 def newbot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
):
182 if bind
is None: bind
= ''
183 obj
= bot
.Bot(self
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
)
184 self
.bots
[nick
.lower()] = obj
186 def newfd(self
, obj
, fileno
):
187 self
.fds
[fileno
] = obj
188 if self
.potype
== "poll":
189 self
.po
.register(fileno
, select
.POLLIN
)
190 elif self
.potype
== "select":
191 self
.fdlist
.append(fileno
)
193 def bot(self
, name
): #get Bot() by name (nick)
194 return self
.bots
[name
.lower()]
195 def fd(self
, fileno
): #get Bot() by fd/fileno
196 return self
.fds
[fileno
]
197 def randbot(self
): #get Bot() randomly
198 return self
.bots
[random
.choice(list(self
.bots
.keys()))]
200 def user(self
, _nick
, justjoined
=False, create
=True):
202 if nick
in self
.users
:
203 return self
.users
[nick
]
205 user
= self
.User(_nick
)
206 self
.users
[nick
] = user
209 self
.randbot().conn
.send("WHO %s n%%ant,1" % (nick
))
214 def channel(self
, name
): #get Channel() by name
215 if name
.lower() in self
.chans
:
216 return self
.chans
[name
.lower()]
220 def newchannel(self
, bot
, name
):
221 chan
= self
.Channel(name
.lower(), bot
)
222 self
.chans
[name
.lower()] = chan
226 if self
.potype
== "poll":
227 return [fd
for (fd
, ev
) in self
.po
.poll()]
228 elif self
.potype
== "select":
229 return select
.select(self
.fdlist
, [], [])[0]
231 def connectall(self
):
232 for bot
in self
.bots
.values():
233 if bot
.conn
.state
== 0:
236 def module(self
, name
):
237 return ctlmod
.modules
[name
]
239 def log(self
, source
, level
, message
):
240 print("%09.3f %s [%s] %s" % (time
.time() % 100000, source
, level
, message
))
242 def getuserbyauth(self
, auth
):
243 return [u
for u
in self
.users
.values() if u
.auth
== auth
.lower()]
246 """Get a DB object. The object must be returned to the pool after us, using returndb()."""
247 return self
.dbs
.pop()
249 def returndb(self
, db
):
253 def hook(self
, word
, handler
):
255 self
.msghandlers
[word
].append(handler
)
257 self
.msghandlers
[word
] = [handler
]
258 def unhook(self
, word
, handler
):
259 if word
in self
.msghandlers
and handler
in self
.msghandlers
[word
]:
260 self
.msghandlers
[word
].remove(handler
)
261 def hashook(self
, word
):
262 return word
in self
.msghandlers
and len(self
.msghandlers
[word
]) != 0
263 def gethook(self
, word
):
264 return self
.msghandlers
[word
]
266 def hooknum(self
, word
, handler
):
268 self
.numhandlers
[word
].append(handler
)
270 self
.numhandlers
[word
] = [handler
]
271 def unhooknum(self
, word
, handler
):
272 if word
in self
.numhandlers
and handler
in self
.numhandlers
[word
]:
273 self
.numhandlers
[word
].remove(handler
)
274 def hasnumhook(self
, word
):
275 return word
in self
.numhandlers
and len(self
.numhandlers
[word
]) != 0
276 def getnumhook(self
, word
):
277 return self
.numhandlers
[word
]
279 def hookchan(self
, chan
, handler
):
281 self
.chanhandlers
[chan
].append(handler
)
283 self
.chanhandlers
[chan
] = [handler
]
284 def unhookchan(self
, chan
, handler
):
285 if chan
in self
.chanhandlers
and handler
in self
.chanhandlers
[chan
]:
286 self
.chanhandlers
[chan
].remove(handler
)
287 def haschanhook(self
, chan
):
288 return chan
in self
.chanhandlers
and len(self
.chanhandlers
[chan
]) != 0
289 def getchanhook(self
, chan
):
290 return self
.chanhandlers
[chan
]
296 for i
in range(cfg
.get('erebus', 'num_db_connections', 2)-1):
297 main
.dbs
.append(MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
))
298 main
.db
= MySQLdb
.connect(host
=cfg
.dbhost
, user
=cfg
.dbuser
, passwd
=cfg
.dbpass
, db
=cfg
.dbname
, cursorclass
=MySQLdb
.cursors
.DictCursor
)
303 cfg
= config
.Config('bot.config')
305 if cfg
.getboolean('debug', 'gc'):
306 gc
.set_debug(gc
.DEBUG_LEAK
)
308 pidfile
= open(cfg
.pidfile
, 'w')
309 pidfile
.write(str(os
.getpid()))
315 autoloads
= [mod
for mod
, yes
in cfg
.items('autoloads') if int(yes
) == 1]
316 for mod
in autoloads
:
317 ctlmod
.load(main
, mod
)
319 c
= main
.query("SELECT nick, user, bind, authname, authpass FROM bots WHERE active = 1")
324 main
.newbot(row
['nick'], row
['user'], row
['bind'], row
['authname'], row
['authpass'], cfg
.host
, cfg
.port
, cfg
.realname
)
328 poready
= main
.poll()
329 for fileno
in poready
:
330 for line
in main
.fd(fileno
).getdata():
331 main
.fd(fileno
).parse(line
)
333 if __name__
== '__main__':
334 try: os
.rename('logfile', 'oldlogs/%s' % (time
.time()))
336 sys
.stdout
= open('logfile', 'w', 1)
337 sys
.stderr
= sys
.stdout