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 if self
.conn
.registered():
73 self
.conn
.send("PING :%s" % (time
.time()))
75 watchdogtimer
= MyTimer(int(self
.parent
.cfg
.get('watchdog', 'interval', default
=30)), self
.watchdog
)
78 def log(self
, *args
, **kwargs
):
79 self
.parent
.log(self
.nick
, *args
, **kwargs
)
82 self
.log('!', "Connecting")
83 if self
.conn
.connect():
84 self
.parent
.newfd(self
, self
.conn
.socket
.fileno())
88 recvd
= self
.conn
.read()
89 self
.lastreceived
= time
.time()
92 return ":%s ERROR :%s%r" % (self
.nick
, e
.__class
__.__name
__, e
.args
)
94 def _checknick(self
): # check if we're using the right nick, try changing
95 if self
.nick
!= self
.permnick
and self
.conn
.registered():
96 self
.conn
.send("NICK %s" % (self
.permnick
))
98 def parse(self
, line
):
99 if self
.parent
.cfg
.getboolean('debug', 'io'):
101 pieces
= line
.split()
103 if pieces
[0][0] == ":":
110 'NOTICE': self
._gotconnected
,
113 '376': self
._gotRegistered
,
114 '422': self
._gotRegistered
,
115 'PRIVMSG': self
._gotprivmsg
,
116 '353': self
._got
353, #NAMES
117 '354': self
._got
354, #WHO
118 '396': self
._gotHiddenHost
, # hidden host has been set
119 '433': self
._got
433, #nick in use
120 'JOIN': self
._gotjoin
,
121 'PART': self
._gotpart
,
122 'KICK': self
._gotkick
,
123 'QUIT': self
._gotquit
,
124 'NICK': self
._gotnick
,
125 'MODE': self
._gotmode
,
126 'PING': self
._gotping
,
127 'ERROR': self
._goterror
,
130 if self
.parent
.hasnumhook(numeric
):
131 hooks
= self
.parent
.getnumhook(numeric
)
132 for callback
in hooks
:
136 self
.__debug
_cbexception
("numhook", line
)
138 if numeric
in dispatch
:
139 dispatch
[numeric
](pieces
)
141 def _gotconnected(self
, pieces
):
142 if not self
.conn
.registered():
144 def _gotping(self
, pieces
):
145 self
.conn
.send("PONG %s" % (pieces
[1]))
147 def _goterror(self
, pieces
):
148 # TODO: better handling, just reconnect that single bot
149 error
= ' '.join(pieces
)
151 raise Exception(error
)
152 except Exception as e
:
153 self
.parent
.mustquit
= e
155 self
.quit("Error detected: %s" % (error
))
158 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
161 self
.log('!', 'Bot exiting due to: %s' % (error
))
162 def _got001(self
, pieces
):
163 # We wait until the end of MOTD instead to consider ourselves registered, but consider uptime as of 001
164 self
.connecttime
= time
.time()
165 def _got004(self
, pieces
):
166 self
.servername
= pieces
[3]
167 def _gotRegistered(self
, pieces
):
168 self
.conn
.registered(True)
170 curs
= self
.parent
.query("UPDATE bots SET connected = 1 WHERE nick = %s", (self
.permnick
,))
171 if curs
: curs
.close()
173 self
.conn
.send("MODE %s +x" % (pieces
[2]))
174 if self
.authname
is not None and self
.authpass
is not None:
175 self
.conn
.send(self
.parent
.cfg
.get('erebus', 'auth_command', "AUTH %s %s") % (self
.authname
, self
.authpass
))
176 if not self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
179 self
.joined_chans
= True
180 def _gotHiddenHost(self
, pieces
):
181 if not self
.joined_chans
and self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
184 self
.joined_chans
= True
185 def _gotprivmsg(self
, pieces
):
186 nick
= pieces
[0].split('!')[0][1:]
187 user
= self
.parent
.user(nick
)
189 msg
= ' '.join(pieces
[3:])[1:]
190 self
.parsemsg(user
, target
, msg
)
191 def _got353(self
, pieces
):
192 prefixes
= {'@': 'op', '+': 'voice'}
193 chan
= self
.parent
.channel(pieces
[4])
195 names
[0] = names
[0][1:] #remove colon
198 user
= self
.parent
.user(n
[1:])
199 chan
.userjoin(user
, prefixes
[n
[0]])
201 user
= self
.parent
.user(n
)
204 def _got354(self
, pieces
):
207 nick
, auth
= pieces
[4:6]
210 chan
, nick
, auth
= pieces
[4:7]
211 chan
= self
.parent
.channel(chan
)
212 user
= self
.parent
.user(nick
)
219 if qt
== 2: # triggered by !auth
222 self
.msg(nick
, "You are now known as #%s (access level: %s)" % (auth
, user
.glevel
))
224 self
.msg(nick
, "You are now known as #%s (not staff)" % (auth
))
226 self
.msg(nick
, "I tried, but you're not authed!")
227 def _got433(self
, pieces
):
228 if not self
.conn
.registered(): #we're trying to connect
229 newnick
= "%s%d" % (self
.nick
, random
.randint(111, 999))
230 self
.conn
.send("NICK %s" % (newnick
))
232 def _gotjoin(self
, pieces
):
233 nick
= pieces
[0].split('!')[0][1:]
234 chan
= self
.parent
.channel(pieces
[2])
236 if nick
== self
.nick
:
237 self
.conn
.send("WHO %s c%%cant,3" % (chan
))
239 user
= self
.parent
.user(nick
, justjoined
=True)
242 def _clientLeft(self
, nick
, chan
):
243 if nick
!= self
.nick
:
244 gone
= self
.parent
.user(nick
).part(chan
)
245 chan
.userpart(self
.parent
.user(nick
))
247 self
.parent
.user(nick
).quit()
248 del self
.parent
.users
[nick
.lower()]
249 def _gotpart(self
, pieces
):
250 nick
= pieces
[0].split('!')[0][1:]
251 chan
= self
.parent
.channel(pieces
[2])
252 self
._clientLeft
(nick
, chan
)
253 def _gotkick(self
, pieces
):
255 chan
= self
.parent
.channel(pieces
[2])
256 self
._clientLeft
(nick
, chan
)
257 def _gotquit(self
, pieces
):
258 nick
= pieces
[0].split('!')[0][1:]
259 if nick
!= self
.nick
:
260 for chan
in self
.parent
.user(nick
).chans
:
261 chan
.userpart(self
.parent
.user(nick
))
262 self
.parent
.user(nick
).quit()
263 del self
.parent
.users
[nick
.lower()]
264 def _gotnick(self
, pieces
):
265 oldnick
= pieces
[0].split('!')[0][1:]
266 newnick
= pieces
[2][1:]
267 if oldnick
== self
.nick
:
270 if newnick
.lower() != oldnick
.lower():
271 self
.parent
.users
[newnick
.lower()] = self
.parent
.users
[oldnick
.lower()]
272 del self
.parent
.users
[oldnick
.lower()]
273 self
.parent
.users
[newnick
.lower()].nickchange(newnick
)
274 def _gotmode(self
, pieces
):
275 source
= pieces
[0].split('!')[0][1:]
277 if not chan
.startswith("#"): return
278 chan
= self
.parent
.channel(pieces
[2])
290 chan
.userop(self
.parent
.user(args
.pop(0)))
292 chan
.userdeop(self
.parent
.user(args
.pop(0)))
295 chan
.uservoice(self
.parent
.user(args
.pop(0)))
297 chan
.userdevoice(self
.parent
.user(args
.pop(0)))
299 pass # don't care about other modes
301 def __debug_cbexception(self
, source
, *args
, **kwargs
):
302 if self
.parent
.cfg
.getboolean('debug', 'cbexc'):
303 self
.conn
.send("PRIVMSG %s :%09.3f \ 34\1f!!! CBEXC\1f\ 3 %s" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, source
))
304 __import__('traceback').print_exc()
305 self
.log('!', "CBEXC %s %r %r" % (source
, args
, kwargs
))
306 # print "%09.3f %s [!] CBEXC %s %r %r" % (time.time() % 100000, self.nick, source, args, kwargs)
309 def parsemsg(self
, user
, target
, msg
):
310 if user
.glevel
<= -2: return # short circuit if user is IGNORED
312 chanparam
= None # was the channel specified as part of the command?
316 if target
== self
.nick
:
317 if msg
.startswith("\001"): #ctcp
318 msg
= msg
.strip("\001")
320 self
.msg(user
, "\001VERSION Erebus v%d.%d - http://jfr.im/git/erebus.git" % (self
.parent
.APIVERSION
, self
.parent
.RELEASE
))
323 triggerused
= msg
.startswith(self
.parent
.trigger
)
324 if triggerused
: msg
= msg
[len(self
.parent
.trigger
):]
330 if target
!= self
.nick
: # message was sent to a channel
332 if pieces
[0][:-1].lower() == self
.nick
.lower() and (pieces
[0][-1] == ":" or pieces
[0][-1] == ","):
333 pieces
.pop(0) # command actually starts with next word
334 if len(pieces
) == 0: # is there still anything left?
336 msg
= ' '.join(pieces
)
339 return # "message" is empty
343 if chanword
.startswith('#'):
344 chanparam
= self
.parent
.channel(chanword
)
346 if target
!= self
.nick
: # message was sent to a channel
347 chan
= self
.parent
.channel(target
)
349 if self
.parent
.haschanhook(target
.lower()):
350 for callback
in self
.parent
.getchanhook(target
.lower()):
352 cbret
= callback(self
, user
, chan
, *pieces
)
353 if isinstance(cbret
, stringbase
):
354 self
.reply(target
, user
, cbret
)
356 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
357 self
.__debug
_cbexception
("chanhook", user
=user
, target
=target
, msg
=msg
)
358 return # not to bot, don't process!
360 cmd
= pieces
[0].lower()
362 if self
.parent
.hashook(cmd
):
363 for callback
in self
.parent
.gethook(cmd
):
364 if chanparam
is not None and (callback
.needchan
or callback
.wantchan
):
367 if chan
is None and callback
.needchan
:
369 self
.msg(user
, "You need to specify a channel for that command.")
370 elif user
.glevel
>= callback
.reqglevel
and (not callback
.needchan
or chan
.levelof(user
.auth
) >= callback
.reqclevel
):
373 cbret
= callback(self
, user
, chan
, target
, *pieces
[1:])
374 if isinstance(cbret
, stringbase
):
375 self
.reply(target
, user
, cbret
)
377 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
378 self
.__debug
_cbexception
("hook", user
=user
, target
=target
, msg
=msg
)
379 except SystemExit as e
:
380 self
.parent
.mustquit
= e
382 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
388 self
.msg(user
, "I don't know that command.")
390 self
.msg(user
, "You don't have enough access to run that command.")
392 def __debug_nomsg(self
, target
, msg
):
393 if self
.parent
.cfg
.getboolean('debug', 'nomsg'):
394 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
))
395 self
.log('!', "!!! NOMSG")
396 # print "%09.3f %s [!] %s" % (time.time() % 100000, self.nick, "!!! NOMSG")
397 __import__('traceback').print_stack()
400 def reply(self
, chan
, user
, msg
):
401 if chan
is not None and (isinstance(chan
, self
.parent
.Channel
) or (isinstance(chan
, stringbase
) and chan
[0] == "#")):
402 self
.msg(chan
, "%s: %s" % (user
, msg
))
407 Does the work for msg/slowmsg/fastmsg. Uses the append_callback to append to the correct queue.
409 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.
411 def _msg(self
, target
, msg
, truncate
, append_callback
, msgtype
):
412 if self
.parent
.cfg
.getboolean('erebus', 'nofakelag'): append_callback
= self
.conn
.send
414 cmd
= self
._formatmsg
(target
, msg
, msgtype
)
415 # The max length is much shorter than recvq (510) because of the length the server adds on about the source (us).
416 # If you know your hostmask, you can of course figure the exact length, but it's very difficult to reliably know your hostmask.
419 - 63 # max hostname len
421 - 3 # the symbols in :nick!user@host
424 if len(cmd
) > maxlen
:
430 if self
.conn
.exceeded
or self
.conn
.bytessent
+len(cmd
) >= self
.conn
.recvq
:
435 self
.conn
.exceeded
= True
438 def msg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
439 """msgtype must be a valid IRC command, i.e. NOTICE or PRIVMSG; or leave as None to use default"""
440 return self
._msg
(target
, msg
, truncate
, self
.msgqueue
.append
, msgtype
)
442 def slowmsg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
443 return self
._msg
(target
, msg
, truncate
, self
.slowmsgqueue
.append
, msgtype
)
445 def fastmsg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
446 return self
._msg
(target
, msg
, truncate
, self
.conn
.send
, msgtype
)
448 def _formatmsg(self
, target
, msg
, msgtype
):
449 if target
is None or msg
is None:
450 return self
.__debug
_nomsg
(target
, msg
)
454 if msgtype
is not None: command
= "%s %s :%s" % (msgtype
, target
, msg
)
455 elif target
.startswith('#'): command
= "PRIVMSG %s :%s" % (target
, msg
)
456 else: command
= "NOTICE %s :%s" % (target
, msg
)
462 self
.conn
.bytessent
-= self
.conn
.recvq
/3
463 if self
.conn
.bytessent
< 0: self
.conn
.bytessent
= 0
464 self
.conn
.exceeded
= True
468 cmd
= self
.msgqueue
.popleft()
471 cmd
= self
.slowmsgqueue
.popleft()
476 if self
.conn
.bytessent
+len(cmd
) > self
.conn
.recvq
: # If it's too long
477 if len(cmd
) > self
.conn
.recvq
: # Is the command itself somehow over max length???
478 self
._msgtimer
.start()
479 raise ValueError('Somehow a command that was too long made it into the message queue. Uhoh!', cmd
)
480 # Discard the message.
481 self
.msgqueue
.appendleft(cmd
) # Phew, we've just sent too much recently. Put it (back) on the (primary) queue.
485 self
._msgtimer
.start()
487 def _makemsgtimer(self
):
488 self
._msgtimer
= MyTimer(3, self
._popmsg
)
490 def join(self
, chan
):
491 self
.conn
.send("JOIN %s" % (chan
))
493 def part(self
, chan
):
494 self
.conn
.send("PART %s" % (chan
))
496 def quit(self
, reason
="Shutdown"):
497 self
.conn
.send("QUIT :%s" % (reason
))
499 def __str__(self
): return self
.nick
500 def __repr__(self
): return "<Bot %r>" % (self
.nick
)
502 class BotConnection(object):
503 def __init__(self
, parent
, bind
, server
, port
):
505 self
.buffer = bytearray()
510 self
.port
= int(port
)
512 self
.state
= 0 # 0=disconnected, 1=registering, 2=connected
516 self
.exceeded
= False
517 self
._nowrite
= False
520 if self
.parent
.parent
.cfg
.getboolean('erebus', 'tls'):
522 undersocket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
523 context
= ssl
.create_default_context()
524 self
.socket
= context
.wrap_socket(undersocket
, server_hostname
=self
.server
)
526 self
.socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
527 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.
528 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_LINGER
, struct
.pack('ii', 0, 0))
529 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_KEEPALIVE
, 1)
530 self
.socket
.bind((self
.bind
, 0))
531 self
.socket
.connect((self
.server
, self
.port
))
535 self
.send("NICK %s" % (self
.parent
.nick
))
536 self
.send("USER %s 0 * :%s" % (self
.parent
.user
, self
.parent
.realname
))
540 def registered(self
, done
=False):
541 if done
: self
.state
= 2
542 return self
.state
== 2
544 def send(self
, line
):
545 if not self
._nowrite
:
546 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
547 self
.parent
.log('O', line
)
548 self
.bytessent
+= len(line
)
551 except socket
.error
as e
:
553 self
.parent
._goterror
(repr(e
))
555 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
556 self
.parent
.log('X', line
)
558 def _write(self
, line
):
559 self
.socket
.sendall(line
.encode('utf-8', 'backslashreplace')+b
"\r\n")
562 recvd
= self
.socket
.recv(8192)
564 raise EOFError("socket.recv in %s returned empty" % (self
.parent
.nick
))
568 while b
"\r\n" in self
.buffer:
569 pieces
= self
.buffer.split(b
"\r\n", 1)
570 lines
.append(pieces
[0].decode('utf-8', 'backslashreplace'))
571 self
.buffer = pieces
[1]
575 def __str__(self
): return self
.parent
.nick
576 def __repr__(self
): return "<BotConnection %r (%r)>" % (self
.socket
.fileno(), self
.parent
.nick
)