2 # vim: fileencoding=utf-8
4 # Erebus IRC bot - Author: John Runyon
5 # "Bot" and "BotConnection" classes (handling a specific "arm")
7 import socket
, sys
, time
, threading
, os
, random
, struct
8 from collections
import deque
10 if sys
.version_info
.major
< 3:
11 timerbase
= threading
._Timer
12 stringbase
= basestring
14 timerbase
= threading
.Timer
17 class MyTimer(timerbase
):
18 def __init__(self
, *args
, **kwargs
):
19 timerbase
.__init
__(self
, *args
, **kwargs
)
22 if sys
.version_info
.major
< 3:
23 stringbase
= basestring
27 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
29 def __init__(self
, parent
, nick
, user
, bind
, authname
, authpass
, server
, port
, realname
):
34 self
.realname
= realname
36 self
.authname
= authname
37 self
.authpass
= authpass
39 self
.connecttime
= 0 # time at which we received numeric 001
40 self
.server
= server
# the address we try to (re-)connect to
42 self
.servername
= server
# the name of the server we got connected to
44 curs
= self
.parent
.query("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self
.permnick
,))
46 chansres
= curs
.fetchall()
48 self
.chans
= [self
.parent
.newchannel(self
, row
['chname']) for row
in chansres
]
52 self
.conn
= BotConnection(self
, bind
, server
, port
)
54 self
.lastreceived
= time
.time() #time we last received a line from the server
57 self
.msgqueue
= deque()
58 self
.slowmsgqueue
= deque()
60 self
._msgtimer
.start()
61 self
.joined_chans
= False
65 curs
= self
.parent
.query("UPDATE bots SET connected = 0 WHERE nick = %s", (self
.permnick
,))
70 if time
.time() > int(self
.parent
.cfg
.get('watchdog', 'maxtime', default
=300))+self
.lastreceived
:
71 self
.parse("ERROR :Fake-error from watchdog timer.")
72 self
.watchdogtimer
= MyTimer(int(self
.parent
.cfg
.get('watchdog', 'interval', default
=30)), self
.watchdog
)
74 def log(self
, *args
, **kwargs
):
75 self
.parent
.log(self
.nick
, *args
, **kwargs
)
78 self
.log('!', "Connecting")
79 if self
.conn
.connect():
80 self
.parent
.newfd(self
, self
.conn
.socket
.fileno())
83 self
.lastreceived
= time
.time()
84 return self
.conn
.read()
86 def _checknick(self
): # check if we're using the right nick, try changing
87 if self
.nick
!= self
.permnick
and self
.conn
.registered():
88 self
.conn
.send("NICK %s" % (self
.permnick
))
90 def parse(self
, line
):
91 if self
.parent
.cfg
.getboolean('debug', 'io'):
96 zero
= { #things to look for without source
97 'NOTICE': self
._gotconnected
,
98 'PING': self
._gotping
,
99 'ERROR': self
._goterror
,
101 one
= { #things to look for after source
102 'NOTICE': self
._gotconnected
,
105 '376': self
._gotRegistered
,
106 '422': self
._gotRegistered
,
107 'PRIVMSG': self
._gotprivmsg
,
108 '353': self
._got
353, #NAMES
109 '354': self
._got
354, #WHO
110 '396': self
._gotHiddenHost
, # hidden host has been set
111 '433': self
._got
433, #nick in use
112 'JOIN': self
._gotjoin
,
113 'PART': self
._gotpart
,
114 'KICK': self
._gotkick
,
115 'QUIT': self
._gotquit
,
116 'NICK': self
._gotnick
,
117 'MODE': self
._gotmode
,
120 if self
.parent
.hasnumhook(pieces
[1]):
121 hooks
= self
.parent
.getnumhook(pieces
[1])
122 for callback
in hooks
:
126 self
.__debug
_cbexception
("numhook", line
)
128 if pieces
[0] in zero
:
129 zero
[pieces
[0]](pieces
)
130 elif pieces
[1] in one
:
131 one
[pieces
[1]](pieces
)
133 def _gotconnected(self
, pieces
):
134 if not self
.conn
.registered():
136 def _gotping(self
, pieces
):
137 self
.conn
.send("PONG %s" % (pieces
[1]))
139 def _goterror(self
, pieces
):
140 # TODO: better handling, just reconnect that single bot
142 self
.quit("Error detected: %s" % ' '.join(pieces
))
145 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
150 def _got001(self
, pieces
):
151 # We wait until the end of MOTD instead to consider ourselves registered, but consider uptime as of 001
152 self
.connecttime
= time
.time()
153 def _got004(self
, pieces
):
154 self
.servername
= pieces
[3]
155 def _gotRegistered(self
, pieces
):
156 self
.conn
.registered(True)
158 curs
= self
.parent
.query("UPDATE bots SET connected = 1 WHERE nick = %s", (self
.permnick
,))
159 if curs
: curs
.close()
161 self
.conn
.send("MODE %s +x" % (pieces
[2]))
162 if self
.authname
is not None and self
.authpass
is not None:
163 self
.conn
.send(self
.parent
.cfg
.get('erebus', 'auth_command', "AUTH %s %s") % (self
.authname
, self
.authpass
))
164 if not self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
167 self
.joined_chans
= True
168 def _gotHiddenHost(self
, pieces
):
169 if not self
.joined_chans
and self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
172 self
.joined_chans
= True
173 def _gotprivmsg(self
, pieces
):
174 nick
= pieces
[0].split('!')[0][1:]
175 user
= self
.parent
.user(nick
)
177 msg
= ' '.join(pieces
[3:])[1:]
178 self
.parsemsg(user
, target
, msg
)
179 def _got353(self
, pieces
):
180 prefixes
= {'@': 'op', '+': 'voice'}
181 chan
= self
.parent
.channel(pieces
[4])
183 names
[0] = names
[0][1:] #remove colon
186 user
= self
.parent
.user(n
[1:])
187 chan
.userjoin(user
, prefixes
[n
[0]])
189 user
= self
.parent
.user(n
)
192 def _got354(self
, pieces
):
195 nick
, auth
= pieces
[4:6]
198 chan
, nick
, auth
= pieces
[4:7]
199 chan
= self
.parent
.channel(chan
)
200 user
= self
.parent
.user(nick
)
207 if qt
== 2: # triggered by !auth
210 self
.msg(nick
, "You are now known as #%s (access level: %s)" % (auth
, user
.glevel
))
212 self
.msg(nick
, "You are now known as #%s (not staff)" % (auth
))
214 self
.msg(nick
, "I tried, but you're not authed!")
215 def _got433(self
, pieces
):
216 if not self
.conn
.registered(): #we're trying to connect
217 newnick
= "%s%d" % (self
.nick
, random
.randint(111, 999))
218 self
.conn
.send("NICK %s" % (newnick
))
220 def _gotjoin(self
, pieces
):
221 nick
= pieces
[0].split('!')[0][1:]
222 chan
= self
.parent
.channel(pieces
[2])
224 if nick
== self
.nick
:
225 self
.conn
.send("WHO %s c%%cant,3" % (chan
))
227 user
= self
.parent
.user(nick
, justjoined
=True)
230 def _clientLeft(self
, nick
, chan
):
231 if nick
!= self
.nick
:
232 gone
= self
.parent
.user(nick
).part(chan
)
233 chan
.userpart(self
.parent
.user(nick
))
235 self
.parent
.user(nick
).quit()
236 del self
.parent
.users
[nick
.lower()]
237 def _gotpart(self
, pieces
):
238 nick
= pieces
[0].split('!')[0][1:]
239 chan
= self
.parent
.channel(pieces
[2])
240 self
._clientLeft
(nick
, chan
)
241 def _gotkick(self
, pieces
):
243 chan
= self
.parent
.channel(pieces
[2])
244 self
._clientLeft
(nick
, chan
)
245 def _gotquit(self
, pieces
):
246 nick
= pieces
[0].split('!')[0][1:]
247 if nick
!= self
.nick
:
248 for chan
in self
.parent
.user(nick
).chans
:
249 chan
.userpart(self
.parent
.user(nick
))
250 self
.parent
.user(nick
).quit()
251 del self
.parent
.users
[nick
.lower()]
252 def _gotnick(self
, pieces
):
253 oldnick
= pieces
[0].split('!')[0][1:]
254 newnick
= pieces
[2][1:]
255 if oldnick
== self
.nick
:
258 if newnick
.lower() != oldnick
.lower():
259 self
.parent
.users
[newnick
.lower()] = self
.parent
.users
[oldnick
.lower()]
260 del self
.parent
.users
[oldnick
.lower()]
261 self
.parent
.users
[newnick
.lower()].nickchange(newnick
)
262 def _gotmode(self
, pieces
):
263 source
= pieces
[0].split('!')[0][1:]
265 if not chan
.startswith("#"): return
266 chan
= self
.parent
.channel(pieces
[2])
278 chan
.userop(self
.parent
.user(args
.pop(0)))
280 chan
.userdeop(self
.parent
.user(args
.pop(0)))
283 chan
.uservoice(self
.parent
.user(args
.pop(0)))
285 chan
.userdevoice(self
.parent
.user(args
.pop(0)))
287 pass # don't care about other modes
289 def __debug_cbexception(self
, source
, *args
, **kwargs
):
290 if self
.parent
.cfg
.getboolean('debug', 'cbexc'):
291 self
.conn
.send("PRIVMSG %s :%09.3f \ 34\1f!!! CBEXC\1f\ 3 %s" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, source
))
292 __import__('traceback').print_exc()
293 self
.log('!', "CBEXC %s %r %r" % (source
, args
, kwargs
))
294 # print "%09.3f %s [!] CBEXC %s %r %r" % (time.time() % 100000, self.nick, source, args, kwargs)
297 def parsemsg(self
, user
, target
, msg
):
298 if user
.glevel
<= -2: return # short circuit if user is IGNORED
300 chanparam
= None # was the channel specified as part of the command?
304 if target
== self
.nick
:
305 if msg
.startswith("\001"): #ctcp
306 msg
= msg
.strip("\001")
308 self
.msg(user
, "\001VERSION Erebus v%d.%d - http://github.com/zonidjan/erebus" % (self
.parent
.APIVERSION
, self
.parent
.RELEASE
))
311 triggerused
= msg
.startswith(self
.parent
.trigger
)
312 if triggerused
: msg
= msg
[len(self
.parent
.trigger
):]
318 if target
!= self
.nick
: # message was sent to a channel
320 if pieces
[0][:-1].lower() == self
.nick
.lower() and (pieces
[0][-1] == ":" or pieces
[0][-1] == ","):
321 pieces
.pop(0) # command actually starts with next word
322 if len(pieces
) == 0: # is there still anything left?
324 msg
= ' '.join(pieces
)
327 return # "message" is empty
331 if chanword
.startswith('#'):
332 chanparam
= self
.parent
.channel(chanword
)
334 if target
!= self
.nick
: # message was sent to a channel
335 chan
= self
.parent
.channel(target
)
337 if self
.parent
.haschanhook(target
.lower()):
338 for callback
in self
.parent
.getchanhook(target
.lower()):
340 cbret
= callback(self
, user
, chan
, *pieces
)
341 if isinstance(cbret
, stringbase
):
342 self
.reply(target
, user
, cbret
)
344 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
345 self
.__debug
_cbexception
("chanhook", user
=user
, target
=target
, msg
=msg
)
346 return # not to bot, don't process!
348 cmd
= pieces
[0].lower()
350 if self
.parent
.hashook(cmd
):
351 for callback
in self
.parent
.gethook(cmd
):
352 if chanparam
is not None and (callback
.needchan
or callback
.wantchan
):
355 if chan
is None and callback
.needchan
:
357 self
.msg(user
, "You need to specify a channel for that command.")
358 elif user
.glevel
>= callback
.reqglevel
and (not callback
.needchan
or chan
.levelof(user
.auth
) >= callback
.reqclevel
):
361 cbret
= callback(self
, user
, chan
, target
, *pieces
[1:])
362 if isinstance(cbret
, stringbase
):
363 self
.reply(target
, user
, cbret
)
365 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
366 self
.__debug
_cbexception
("hook", user
=user
, target
=target
, msg
=msg
)
367 except SystemExit as e
:
369 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
375 self
.msg(user
, "I don't know that command.")
377 self
.msg(user
, "You don't have enough access to run that command.")
379 def __debug_nomsg(self
, target
, msg
):
380 if self
.parent
.cfg
.getboolean('debug', 'nomsg'):
381 self
.conn
.send("PRIVMSG %s :%09.3f \ 34\1f!!! NOMSG\1f\ 3 %r, %r" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, target
, msg
))
382 self
.log('!', "!!! NOMSG")
383 # print "%09.3f %s [!] %s" % (time.time() % 100000, self.nick, "!!! NOMSG")
384 __import__('traceback').print_stack()
387 def reply(self
, chan
, user
, msg
):
388 if chan
is not None and (isinstance(chan
, self
.parent
.Channel
) or (isinstance(chan
, stringbase
) and chan
[0] == "#")):
389 self
.msg(chan
, "%s: %s" % (user
, msg
))
394 Does the work for msg/slowmsg/fastmsg. Uses the append_callback to append to the correct queue.
396 In the case of fastmsg, self.conn.exceeded may be True, however, in this case append_callback=self.conn.send, so it will still be sent immediately.
398 def _msg(self
, target
, msg
, truncate
, append_callback
):
399 if self
.parent
.cfg
.getboolean('erebus', 'nofakelag'): return self
.fastmsg(target
, msg
)
401 cmd
= self
._formatmsg
(target
, msg
)
402 # The max length is much shorter than recvq (510) because of the length the server adds on about the source (us).
403 # If you know your hostmask, you can of course figure the exact length, but it's very difficult to reliably know your hostmask.
406 - 63 # max hostname len
408 - 3 # the symbols in :nick!user@host
411 if len(cmd
) > maxlen
:
417 if self
.conn
.exceeded
or self
.conn
.bytessent
+len(cmd
) >= self
.conn
.recvq
:
422 self
.conn
.exceeded
= True
425 def msg(self
, target
, msg
, truncate
=False):
426 return self
._msg
(target
, msg
, truncate
, self
.msgqueue
.append
)
428 def slowmsg(self
, target
, msg
, truncate
=False):
429 return self
._msg
(target
, msg
, truncate
, self
.slowmsgqueue
.append
)
431 def fastmsg(self
, target
, msg
, truncate
=False):
432 return self
._msg
(target
, msg
, truncate
, self
.conn
.send
)
434 def _formatmsg(self
, target
, msg
):
435 if target
is None or msg
is None:
436 return self
.__debug
_nomsg
(target
, msg
)
440 if target
.startswith('#'): command
= "PRIVMSG %s :%s" % (target
, msg
)
441 else: command
= "NOTICE %s :%s" % (target
, msg
)
447 self
.conn
.bytessent
-= self
.conn
.recvq
/3
448 if self
.conn
.bytessent
< 0: self
.conn
.bytessent
= 0
449 self
.conn
.exceeded
= True
453 cmd
= self
.msgqueue
.popleft()
456 cmd
= self
.slowmsgqueue
.popleft()
461 if self
.conn
.bytessent
+len(cmd
) > self
.conn
.recvq
: # If it's too long
462 if len(cmd
) > self
.conn
.recvq
: # Is the command itself somehow over max length???
463 self
._msgtimer
.start()
464 raise ValueError('Somehow a command that was too long made it into the message queue. Uhoh!', cmd
)
465 # Discard the message.
466 self
.msgqueue
.appendleft(cmd
) # Phew, we've just sent too much recently. Put it (back) on the (primary) queue.
470 self
._msgtimer
.start()
472 def _makemsgtimer(self
):
473 self
._msgtimer
= MyTimer(3, self
._popmsg
)
475 def join(self
, chan
):
476 self
.conn
.send("JOIN %s" % (chan
))
478 def part(self
, chan
):
479 self
.conn
.send("PART %s" % (chan
))
481 def quit(self
, reason
="Shutdown"):
482 self
.conn
.send("QUIT :%s" % (reason
))
484 def __str__(self
): return self
.nick
485 def __repr__(self
): return "<Bot %r>" % (self
.nick
)
487 class BotConnection(object):
488 def __init__(self
, parent
, bind
, server
, port
):
490 self
.buffer = bytearray()
495 self
.port
= int(port
)
497 self
.state
= 0 # 0=disconnected, 1=registering, 2=connected
501 self
.exceeded
= False
502 self
._nowrite
= False
505 if self
.parent
.parent
.cfg
.getboolean('erebus', 'tls'):
507 undersocket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
508 context
= ssl
.create_default_context()
509 self
.socket
= context
.wrap_socket(undersocket
, server_hostname
=self
.server
)
511 self
.socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
512 self
.socket
.setsockopt(socket
.SOL_TCP
, socket
.TCP_NODELAY
, 1) # Does Python make SOL_TCP portable? Who knows, it's not documented, and it appears to come from the _socket C lib.
513 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_LINGER
, struct
.pack('ii', 0, 0))
514 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_KEEPALIVE
, 1)
515 self
.socket
.bind((self
.bind
, 0))
516 self
.socket
.connect((self
.server
, self
.port
))
520 self
.send("NICK %s" % (self
.parent
.nick
))
521 self
.send("USER %s 0 * :%s" % (self
.parent
.user
, self
.parent
.realname
))
525 def registered(self
, done
=False):
526 if done
: self
.state
= 2
527 return self
.state
== 2
529 def send(self
, line
):
530 if not self
._nowrite
:
531 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
532 self
.parent
.log('O', line
)
533 self
.bytessent
+= len(line
)
536 except socket
.error
as e
:
538 self
.parent
._goterror
(repr(e
))
540 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
541 self
.parent
.log('X', line
)
543 def _write(self
, line
):
544 self
.socket
.sendall(line
.encode('utf-8', 'backslashreplace')+b
"\r\n")
547 self
.buffer += self
.socket
.recv(8192)
550 while b
"\r\n" in self
.buffer:
551 pieces
= self
.buffer.split(b
"\r\n", 1)
552 lines
.append(pieces
[0].decode('utf-8', 'backslashreplace'))
553 self
.buffer = pieces
[1]
557 def __str__(self
): return self
.parent
.nick
558 def __repr__(self
): return "<BotConnection %r (%r)>" % (self
.socket
.fileno(), self
.parent
.nick
)