]>
jfr.im git - erebus.git/blob - bot.py
3 # Erebus IRC bot - Author: John Runyon
4 # "Bot" and "BotConnection" classes (handling a specific "arm")
6 import socket
, sys
, time
, threading
, os
7 from collections
import deque
9 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
11 def __init__(self
, parent
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
):
15 self
.realname
= realname
17 self
.authname
= authname
18 self
.authpass
= authpass
20 curs
= self
.parent
.db
.cursor()
21 if curs
.execute("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self
.nick
,)):
22 chansres
= curs
.fetchall()
24 self
.chans
= [self
.parent
.newchannel(self
, row
['chname']) for row
in chansres
]
26 self
.conn
= BotConnection(self
, bind
, server
, port
)
28 self
.msgqueue
= deque()
29 self
.slowmsgqueue
= deque()
33 curs
= self
.parent
.db
.cursor()
34 curs
.execute("UPDATE bots SET connected = 0 WHERE nick = %s", (self
.nick
,))
39 if self
.conn
.connect():
40 self
.parent
.newfd(self
, self
.conn
.socket
.fileno())
43 return self
.conn
.read()
45 def parse(self
, line
):
49 zero
= { #things to look for without source
50 'NOTICE': self
._gotregistered
,
51 'PING': self
._gotping
,
52 'ERROR': self
._goterror
,
54 one
= { #things to look for after source
56 'PRIVMSG': self
._gotprivmsg
,
57 '353': self
._got
353, #NAMES
58 '354': self
._got
354, #WHO
59 'JOIN': self
._gotjoin
,
60 'PART': self
._gotpart
,
61 'QUIT': self
._gotquit
,
62 'NICK': self
._gotnick
,
63 'MODE': self
._gotmode
,
66 if self
.parent
.hasnumhook(pieces
[1]):
67 hooks
= self
.parent
.getnumhook(pieces
[1])
68 for callback
in hooks
:
72 self
.__debug
_cbexception
("numhook", line
)
75 zero
[pieces
[0]](pieces
)
76 elif pieces
[1] in one
:
77 one
[pieces
[1]](pieces
)
79 def _gotregistered(self
, pieces
):
80 if not self
.conn
.registered():
82 def _gotping(self
, pieces
):
83 self
.conn
.send("PONG %s" % (pieces
[1]))
84 def _goterror(self
, pieces
): #TODO handle more gracefully
85 curs
= self
.parent
.db
.cursor()
86 curs
.execute("UPDATE bots SET connected = 0")
90 def _got001(self
, pieces
):
91 self
.conn
.registered(True)
93 curs
= self
.parent
.db
.cursor()
94 curs
.execute("UPDATE bots SET connected = 1 WHERE nick = %s", (self
.nick
,))
97 self
.conn
.send("MODE %s +x" % (pieces
[2]))
98 if self
.authname
is not None and self
.authpass
is not None:
99 self
.conn
.send("AUTH %s %s" % (self
.authname
, self
.authpass
))
102 def _gotprivmsg(self
, pieces
):
103 nick
= pieces
[0].split('!')[0][1:]
104 user
= self
.parent
.user(nick
)
106 msg
= ' '.join(pieces
[3:])[1:]
107 self
.parsemsg(user
, target
, msg
)
108 def _got353(self
, pieces
):
109 chan
= self
.parent
.channel(pieces
[4])
111 names
[0] = names
[0][1:] #remove colon
113 user
= self
.parent
.user(n
.lstrip('@+'))
115 chan
.userjoin(user
, 'op')
117 chan
.userjoin(user
, 'voice')
121 def _got354(self
, pieces
):
124 nick
, auth
= pieces
[4:6]
127 chan
, nick
, auth
= pieces
[4:7]
128 chan
= self
.parent
.channel(chan
)
129 user
= self
.parent
.user(nick
)
136 if qt
== 2: # triggered by !auth
139 self
.msg(nick
, "You are now known as #%s (access level: %s)" % (auth
, user
.glevel
))
141 self
.msg(nick
, "You are now known as #%s (not staff)" % (auth
))
143 self
.msg(nick
, "I tried, but you're not authed!")
144 def _gotjoin(self
, pieces
):
145 nick
= pieces
[0].split('!')[0][1:]
146 chan
= self
.parent
.channel(pieces
[2])
148 if nick
== self
.nick
:
149 self
.conn
.send("WHO %s c%%cant,3" % (chan
))
151 user
= self
.parent
.user(nick
, justjoined
=True)
154 def _gotpart(self
, pieces
):
155 nick
= pieces
[0].split('!')[0][1:]
156 chan
= self
.parent
.channel(pieces
[2])
158 if nick
!= self
.nick
:
159 gone
= self
.parent
.user(nick
).part(chan
)
160 chan
.userpart(self
.parent
.user(nick
))
162 self
.parent
.user(nick
).quit()
163 del self
.parent
.users
[nick
.lower()]
164 def _gotquit(self
, pieces
):
165 nick
= pieces
[0].split('!')[0][1:]
166 if nick
!= self
.nick
:
167 for chan
in self
.parent
.user(nick
).chans
:
168 chan
.userpart(self
.parent
.user(nick
))
169 self
.parent
.user(nick
).quit()
170 del self
.parent
.users
[nick
.lower()]
171 def _gotnick(self
, pieces
):
172 oldnick
= pieces
[0].split('!')[0][1:]
173 newnick
= pieces
[2][1:]
174 if newnick
.lower() != oldnick
.lower():
175 self
.parent
.users
[newnick
.lower()] = self
.parent
.users
[oldnick
.lower()]
176 del self
.parent
.users
[oldnick
.lower()]
177 self
.parent
.users
[newnick
.lower()].nickchange(newnick
)
178 def _gotmode(self
, pieces
):
179 source
= pieces
[0].split('!')[0][1:]
180 chan
= self
.parent
.channel(pieces
[2])
192 chan
.userop(self
.parent
.user(args
.pop(0)))
194 chan
.userdeop(self
.parent
.user(args
.pop(0)))
197 chan
.uservoice(self
.parent
.user(args
.pop(0)))
199 chan
.userdevoice(self
.parent
.user(args
.pop(0)))
201 pass # don't care about other modes
203 def __debug_cbexception(self
, source
, *args
, **kwargs
):
204 if int(self
.parent
.cfg
.get('debug', 'cbexc', default
=0)) == 1:
205 self
.conn
.send("PRIVMSG %s :%09.3f ^C4^B!!!^B^C CBEXC %s" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, source
))
206 __import__('traceback').print_exc()
207 print "%09.3f %s [!] CBEXC %s %r %r" % (time
.time() % 100000, self
.nick
, source
, args
, kwargs
)
210 def parsemsg(self
, user
, target
, msg
):
215 triggerused
= msg
[0] == self
.parent
.trigger
216 if triggerused
: msg
= msg
[1:]
219 if target
== self
.nick
:
220 if msg
[0] == "\001": #ctcp
221 msg
= msg
.strip("\001")
223 self
.msg(user
, "\001VERSION Erebus v%d.%d - http://github.com/zonidjan/erebus" % (self
.parent
.APIVERSION
, self
.parent
.RELEASE
))
227 if chanword
[0] == '#':
228 chan
= self
.parent
.channel(chanword
)
229 if chan
is not None: #if chan is still none, there's no bot on "chanword", and chanword is used as a parameter.
232 else: # message was sent to a channel
233 chan
= self
.parent
.channel(target
)
235 if msg
[0] == '*': # message may be addressed to bot by "*BOTNICK" trigger?
236 if pieces
[0][1:].lower() == self
.nick
.lower():
237 pieces
.pop(0) # command actually starts with next word
238 msg
= ' '.join(pieces
) # command actually starts with next word
239 elif not triggerused
:
240 if self
.parent
.haschanhook(target
.lower()):
241 for callback
in self
.parent
.getchanhook(target
.lower()):
243 cbret
= callback(self
, user
, chan
, *pieces
)
244 except NotImplementedError:
245 self
.msg(user
, "Command not implemented.")
247 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
248 self
.__debug
_cbexception
("chanhook", user
=user
, target
=target
, msg
=msg
)
249 return # not to bot, don't process!
251 return # "message" is empty
253 cmd
= pieces
[0].lower()
255 if self
.parent
.hashook(cmd
):
256 for callback
in self
.parent
.gethook(cmd
):
257 if chan
is None and callback
.needchan
:
258 self
.msg(user
, "You need to specify a channel for that command.")
259 elif user
.glevel
>= callback
.reqglevel
and (not callback
.needchan
or chan
.levelof(user
.auth
) >= callback
.reqclevel
):
261 cbret
= callback(self
, user
, chan
, target
, *pieces
[1:])
262 except NotImplementedError:
263 self
.msg(user
, "Command not implemented.")
265 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
266 self
.__debug
_cbexception
("hook", user
=user
, target
=target
, msg
=msg
)
267 except SystemExit as e
:
268 curs
= self
.parent
.db
.cursor()
269 curs
.execute("UPDATE bots SET connected = 0")
273 def __debug_nomsg(self
, target
, msg
):
274 if int(self
.parent
.cfg
.get('debug', 'nomsg', default
=0)) == 1:
275 self
.conn
.send("PRIVMSG %s :%09.3f \ 34\ 2!!!\ 2\ 3 NOMSG %r, %r" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, target
, msg
))
276 print "%09.3f %s [!] %s" % (time
.time() % 100000, self
.nick
, "!!! NOMSG")
277 __import__('traceback').print_stack()
279 def msg(self
, target
, msg
):
280 if target
is None or msg
is None:
281 return self
.__debug
_nomsg
(target
, msg
)
283 self
.msgqueue
.append((target
, msg
))
284 if not self
.msgtimer
.is_alive():
285 self
.msgtimer
.start()
287 def slowmsg(self
, target
, msg
):
288 if target
is None or msg
is None:
289 return self
.__debug
_nomsg
(target
, msg
)
291 self
.slowmsgqueue
.append((target
, msg
))
292 if not self
.msgtimer
.is_alive():
293 self
.msgtimer
.start()
295 def fastmsg(self
, target
, msg
):
296 if target
is None or msg
is None:
297 return self
.__debug
_nomsg
(target
, msg
)
301 if target
[0] == '#': command
= "PRIVMSG %s :%s" % (target
, msg
)
302 else: command
= "NOTICE %s :%s" % (target
, msg
)
304 self
.conn
.send(command
)
310 self
.fastmsg(*self
.msgqueue
.popleft())
311 self
.msgtimer
.start()
314 self
.fastmsg(*self
.slowmsgqueue
.popleft())
315 self
.msgtimer
.start()
319 def makemsgtimer(self
):
320 self
.msgtimer
= threading
.Timer(2, self
._popmsg
)
321 self
.msgtimer
.daemon
= True
323 def join(self
, chan
):
324 self
.conn
.send("JOIN %s" % (chan
))
326 def part(self
, chan
):
327 self
.conn
.send("PART %s" % (chan
))
329 def quit(self
, reason
="Shutdown"):
330 self
.conn
.send("QUIT :%s" % (reason
))
332 def __str__(self
): return self
.nick
333 def __repr__(self
): return "<Bot %r>" % (self
.nick
)
335 class BotConnection(object):
336 def __init__(self
, parent
, bind
, server
, port
):
343 self
.port
= int(port
)
345 self
.state
= 0 # 0=disconnected, 1=registering, 2=connected
348 self
.socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
349 self
.socket
.bind((self
.bind
, 0))
350 self
.socket
.connect((self
.server
, self
.port
))
354 self
.send("NICK %s" % (self
.parent
.nick
))
355 self
.send("USER %s 0 * :%s" % (self
.parent
.user
, self
.parent
.realname
))
359 def registered(self
, done
=False):
360 if done
: self
.state
= 2
361 return self
.state
== 2
363 def send(self
, line
):
364 print "%09.3f %s [O] %s" % (time
.time() % 100000, self
.parent
.nick
, line
)
367 def _write(self
, line
):
368 self
.socket
.sendall(line
+"\r\n")
371 self
.buffer += self
.socket
.recv(8192)
374 while "\r\n" in self
.buffer:
375 pieces
= self
.buffer.split("\r\n", 1)
376 print "%09.3f %s [I] %s" % (time
.time() % 100000, self
.parent
.nick
, pieces
[0])
377 # print (time.time() % 1460000000), self.parent.nick, '[I]', pieces[0]
378 lines
.append(pieces
[0])
379 self
.buffer = pieces
[1]
383 def __str__(self
): return self
.parent
.nick
384 def __repr__(self
): return "<BotConnection %r (%r)>" % (self
.socket
.fileno(), self
.parent
.nick
)