2 # vim: fileencoding=utf-8
4 # Erebus IRC bot - Author: John Runyon
5 # "Bot" and "BotConnection" classes (handling a specific "arm")
7 import os
, random
, socket
, struct
, sys
, threading
, time
, traceback
, fcntl
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
):
36 self
.realname
= realname
38 self
.authname
= authname
39 self
.authpass
= authpass
41 self
.connecttime
= 0 # time at which we received numeric 001
42 self
.server
= server
# the address we try to (re-)connect to
44 self
.servername
= server
# the name of the server we got connected to
46 curs
= self
.parent
.query("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self
.permnick
,))
48 chansres
= curs
.fetchall()
50 self
.chans
= [self
.parent
.newchannel(self
, row
['chname']) for row
in chansres
]
54 self
.conn
= BotConnection(self
, bind
, server
, port
)
56 self
.lastreceived
= time
.time() #time we last received a line from the server
59 self
.msgqueue
= deque()
60 self
.slowmsgqueue
= deque()
62 self
._msgtimer
.start()
63 self
.joined_chans
= False
67 curs
= self
.parent
.query("UPDATE bots SET connected = 0 WHERE nick = %s", (self
.permnick
,))
72 if time
.time() > int(self
.parent
.cfg
.get('watchdog', 'maxtime', default
=300))+self
.lastreceived
:
73 self
.parse("ERROR :Fake-error from watchdog timer.")
75 if self
.conn
.registered():
76 self
.conn
.send("PING :%s" % (time
.time()))
78 watchdogtimer
= MyTimer(int(self
.parent
.cfg
.get('watchdog', 'interval', default
=30)), self
.watchdog
)
81 def log(self
, *args
, **kwargs
):
82 self
.parent
.log(self
.nick
, *args
, **kwargs
)
85 self
.log('!', "Connecting")
86 if self
.conn
.connect():
87 self
.log('!', "Connected")
88 self
.parent
.newfd(self
, self
.conn
.socket
.fileno())
92 recvd
= self
.conn
.read()
93 self
.lastreceived
= time
.time()
96 return [":%s ERROR :%s%r" % (self
.nick
, e
.__class
__.__name
__, e
.args
)]
98 def _checknick(self
): # check if we're using the right nick, try changing
99 if self
.nick
!= self
.permnick
and self
.conn
.registered():
100 self
.conn
.send("NICK %s" % (self
.permnick
))
102 def parse(self
, line
):
103 pieces
= line
.split()
105 if pieces
[0][0] == ":":
112 'NOTICE': self
._gotconnected
,
115 '376': self
._gotRegistered
,
116 '422': self
._gotRegistered
,
117 'PRIVMSG': self
._gotprivmsg
,
118 '353': self
._got
353, #NAMES
119 '354': self
._got
354, #WHO
120 '396': self
._gotHiddenHost
, # hidden host has been set
121 '433': self
._got
433, #nick in use
122 'JOIN': self
._gotjoin
,
123 'PART': self
._gotpart
,
124 'KICK': self
._gotkick
,
125 'QUIT': self
._gotquit
,
126 'NICK': self
._gotnick
,
127 'MODE': self
._gotmode
,
128 'PING': self
._gotping
,
129 'ERROR': self
._goterror
,
132 if self
.parent
.hasnumhook(numeric
):
133 hooks
= self
.parent
.getnumhook(numeric
)
134 for callback
in hooks
:
138 self
._cbexception
("numhook", line
)
140 if numeric
in dispatch
:
141 dispatch
[numeric
](pieces
)
143 def _gotconnected(self
, pieces
):
144 if not self
.conn
.registered():
146 def _gotping(self
, pieces
):
147 self
.conn
.send("PONG %s" % (pieces
[1]))
149 def _goterror(self
, pieces
):
150 # TODO: better handling, just reconnect that single bot
151 error
= ' '.join(pieces
)
153 raise Exception(error
)
154 except Exception as e
:
155 self
.parent
.mustquit
= e
157 self
.quit("Error detected: %s" % (error
))
160 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
163 self
.log('!', 'Bot exiting due to: %s' % (error
))
164 def _got001(self
, pieces
):
165 # We wait until the end of MOTD instead to consider ourselves registered, but consider uptime as of 001
166 self
.connecttime
= time
.time()
167 def _got004(self
, pieces
):
168 self
.servername
= pieces
[3]
169 def _gotRegistered(self
, pieces
):
170 self
.conn
.registered(True)
172 curs
= self
.parent
.query("UPDATE bots SET connected = 1 WHERE nick = %s", (self
.permnick
,))
173 if curs
: curs
.close()
175 self
.conn
.send("MODE %s +x" % (pieces
[2]))
176 if self
.authname
is not None and self
.authpass
is not None:
177 self
.conn
.send(self
.parent
.cfg
.get('erebus', 'auth_command', "AUTH %s %s") % (self
.authname
, self
.authpass
))
178 if not self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
181 self
.joined_chans
= True
182 def _gotHiddenHost(self
, pieces
):
183 if not self
.joined_chans
and self
.parent
.cfg
.getboolean('erebus', 'wait_for_hidden_host'):
186 self
.joined_chans
= True
187 def _gotprivmsg(self
, pieces
):
188 nick
= pieces
[0].split('!')[0][1:]
189 user
= self
.parent
.user(nick
)
191 msg
= ' '.join(pieces
[3:])[1:]
192 self
.parsemsg(user
, target
, msg
)
193 def _got353(self
, pieces
):
194 prefixes
= {'@': 'op', '+': 'voice'}
195 chan
= self
.parent
.channel(pieces
[4])
197 names
[0] = names
[0][1:] #remove colon
200 user
= self
.parent
.user(n
[1:])
201 chan
.userjoin(user
, prefixes
[n
[0]])
203 user
= self
.parent
.user(n
)
206 def _got354(self
, pieces
):
209 nick
, auth
= pieces
[4:6]
212 chan
, nick
, auth
= pieces
[4:7]
213 chan
= self
.parent
.channel(chan
)
214 user
= self
.parent
.user(nick
)
221 if qt
== 2: # triggered by !auth
224 self
.msg(nick
, "You are now known as #%s (access level: %s)" % (auth
, user
.glevel
))
226 self
.msg(nick
, "You are now known as #%s (not staff)" % (auth
))
228 self
.msg(nick
, "I tried, but you're not authed!")
229 def _got433(self
, pieces
):
230 if not self
.conn
.registered(): #we're trying to connect
231 newnick
= "%s%d" % (self
.nick
, random
.randint(111, 999))
232 self
.conn
.send("NICK %s" % (newnick
))
234 def _gotjoin(self
, pieces
):
235 nick
= pieces
[0].split('!')[0][1:]
236 chan
= self
.parent
.channel(pieces
[2])
238 if nick
== self
.nick
:
239 self
.conn
.send("WHO %s c%%cant,3" % (chan
))
241 user
= self
.parent
.user(nick
, send_who
=True)
244 def _clientLeft(self
, nick
, chan
):
245 if nick
== self
.nick
:
247 if u
.nick
!= self
.nick
:
248 self
._clientLeft
(u
.nick
, chan
)
250 user
= self
.parent
.user(nick
)
251 gone
= user
.part(chan
)
255 del self
.parent
.users
[nick
.lower()]
256 def _gotpart(self
, pieces
):
257 nick
= pieces
[0].split('!')[0][1:]
258 chan
= self
.parent
.channel(pieces
[2])
259 self
._clientLeft
(nick
, chan
)
260 def _gotkick(self
, pieces
):
262 chan
= self
.parent
.channel(pieces
[2])
263 self
._clientLeft
(nick
, chan
)
264 def _gotquit(self
, pieces
):
265 nick
= pieces
[0].split('!')[0][1:]
266 if nick
!= self
.nick
:
267 for chan
in self
.parent
.user(nick
).chans
:
268 chan
.userpart(self
.parent
.user(nick
))
269 self
.parent
.user(nick
).quit()
270 del self
.parent
.users
[nick
.lower()]
271 def _gotnick(self
, pieces
):
272 oldnick
= pieces
[0].split('!')[0][1:]
273 newnick
= pieces
[2][1:]
274 if oldnick
== self
.nick
:
277 if newnick
.lower() != oldnick
.lower():
278 self
.parent
.users
[newnick
.lower()] = self
.parent
.users
[oldnick
.lower()]
279 del self
.parent
.users
[oldnick
.lower()]
280 self
.parent
.users
[newnick
.lower()].nickchange(newnick
)
281 def _gotmode(self
, pieces
):
282 source
= pieces
[0].split('!')[0][1:]
284 if not chan
.startswith("#"): return
285 chan
= self
.parent
.channel(pieces
[2])
297 chan
.userop(self
.parent
.user(args
.pop(0)))
299 chan
.userdeop(self
.parent
.user(args
.pop(0)))
302 chan
.uservoice(self
.parent
.user(args
.pop(0)))
304 chan
.userdevoice(self
.parent
.user(args
.pop(0)))
306 pass # don't care about other modes
308 def _cbexception(self
, source
, *args
, chained
=False, **kwargs
):
309 if not chained
: # skip hooks if we were caused by a hook
310 exc
= sys
.exception()
311 if self
.parent
.hasexceptionhook(exc
):
312 for callback
in self
.parent
.getexceptionhook(exc
):
314 callback(self
, exc
, source
, *args
, **kwargs
)
316 self
._cbexception
('exceptionhook', chained
=True, module
=callback
.__module
__, function
=callback
.__name
__, underlying
=(source
, args
, kwargs
))
317 if self
.parent
.cfg
.getboolean('debug', 'cbexc'):
318 self
.conn
.send("PRIVMSG %s :%09.3f \ 34\1f!!! CBEXC\1f\ 3 %s" % (self
.parent
.cfg
.get('debug', 'owner'), time
.time() % 100000, source
))
319 traceback
.print_exc(chain
=not chained
)
320 self
.log('!', "CBEXC %s %r %r" % (source
, args
, kwargs
))
323 def parsemsg(self
, user
, target
, msg
):
324 if user
.glevel
<= -2: return # short circuit if user is IGNORED
326 chanparam
= None # was the channel specified as part of the command?
330 if target
== self
.nick
and msg
.startswith("\001"): #ctcp
331 msg
= msg
.strip("\001")
334 if pieces
[0] == "CLIENTINFO":
335 self
.msg(user
, "\001CLIENTINFO VERSION PING\001")
336 elif pieces
[0] == "VERSION":
337 self
.msg(user
, "\001VERSION Erebus v%d.%d - http://jfr.im/git/erebus.git\001" % (self
.parent
.APIVERSION
, self
.parent
.RELEASE
))
338 elif pieces
[0] == "PING":
340 self
.msg(user
, "\001PING %s\001" % (' '.join(pieces
[1:])))
342 self
.msg(user
, "\001PING\001")
345 triggerused
= msg
.startswith(self
.parent
.trigger
)
346 if triggerused
: msg
= msg
[len(self
.parent
.trigger
):]
352 if target
!= self
.nick
: # message was sent to a channel
354 if pieces
[0][:-1].lower() == self
.nick
.lower() and (pieces
[0][-1] == ":" or pieces
[0][-1] == ","):
355 pieces
.pop(0) # command actually starts with next word
356 if len(pieces
) == 0: # is there still anything left?
358 msg
= ' '.join(pieces
)
361 return # "message" is empty
365 if chanword
.startswith('#'):
366 chanparam
= self
.parent
.channel(chanword
)
368 if target
!= self
.nick
: # message was sent to a channel
369 chan
= self
.parent
.channel(target
)
371 if self
.parent
.haschanhook(target
.lower()):
372 for callback
in self
.parent
.getchanhook(target
.lower()):
374 cbret
= callback(self
, user
, chan
, *pieces
)
375 if isinstance(cbret
, stringbase
):
376 self
.reply(target
, user
, cbret
)
378 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
379 self
._cbexception
("chanhook", user
=user
, target
=target
, msg
=msg
)
380 return # not to bot, don't process!
382 cmd
= pieces
[0].lower()
384 if self
.parent
.hashook(cmd
):
385 for callback
in self
.parent
.gethook(cmd
):
386 if chanparam
is not None and (callback
.needchan
or callback
.wantchan
):
389 if chan
is None and callback
.needchan
:
391 self
.msg(user
, "You need to specify a channel for that command.")
392 elif user
.glevel
>= callback
.reqglevel
and (not callback
.needchan
or chan
.levelof(user
.auth
) >= callback
.reqclevel
):
395 cbret
= callback(self
, user
, chan
, target
, *pieces
[1:])
396 if isinstance(cbret
, stringbase
):
397 self
.reply(target
, user
, cbret
)
399 self
.msg(user
, "Command failed. Code: CBEXC%09.3f" % (time
.time() % 100000))
400 self
._cbexception
("hook", user
=user
, target
=target
, msg
=msg
)
401 except SystemExit as e
:
402 self
.parent
.mustquit
= e
404 curs
= self
.parent
.query("UPDATE bots SET connected = 0")
410 self
.msg(user
, "I don't know that command.")
412 self
.msg(user
, "You don't have enough access to run that command.")
414 def __debug_nomsg(self
, target
, msg
):
415 if self
.parent
.cfg
.getboolean('debug', 'nomsg'):
416 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
))
417 self
.log('!', "!!! NOMSG")
418 # print "%09.3f %s [!] %s" % (time.time() % 100000, self.nick, "!!! NOMSG")
419 traceback
.print_stack()
422 def reply(self
, chan
, user
, msg
):
423 if chan
is not None and (isinstance(chan
, self
.parent
.Channel
) or (isinstance(chan
, stringbase
) and chan
[0] == "#")):
424 self
.msg(chan
, "%s: %s" % (user
, msg
))
429 Does the work for msg/slowmsg/fastmsg. Uses the append_callback to append to the correct queue.
431 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.
433 def _msg(self
, target
, msg
, truncate
, append_callback
, msgtype
):
434 if self
.parent
.cfg
.getboolean('erebus', 'nofakelag'): append_callback
= self
.conn
.send
436 cmd
= self
._formatmsg
(target
, msg
, msgtype
)
437 # The max length is much shorter than conn.maxlen (510) because of the length the server adds on about the source (us).
438 # If you know your hostmask, you can of course figure the exact length, but it's very difficult to reliably know your hostmask.
439 maxlen
= self
.maxmsglen()
440 if len(cmd
) > maxlen
:
446 if self
.conn
.exceeded
or self
.conn
.bytessent
+len(cmd
) >= self
.conn
.recvq
:
451 self
.conn
.exceeded
= True
454 def msg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
455 """msgtype must be a valid IRC command, i.e. NOTICE or PRIVMSG; or leave as None to use default"""
456 return self
._msg
(target
, msg
, truncate
, self
.msgqueue
.append
, msgtype
)
458 def slowmsg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
459 return self
._msg
(target
, msg
, truncate
, self
.slowmsgqueue
.append
, msgtype
)
461 def fastmsg(self
, target
, msg
, truncate
=False, *, msgtype
=None):
462 return self
._msg
(target
, msg
, truncate
, self
.conn
.send
, msgtype
)
464 def _formatmsg(self
, target
, msg
, msgtype
):
465 if target
is None or msg
is None:
466 return self
.__debug
_nomsg
(target
, msg
)
470 if msgtype
is not None: command
= "%s %s :%s" % (msgtype
, target
, msg
)
471 elif target
.startswith('#'): command
= "PRIVMSG %s :%s" % (target
, msg
)
472 else: command
= "NOTICE %s :%s" % (target
, msg
)
478 self
.conn
.bytessent
-= self
.conn
.recvq
/3
479 if self
.conn
.bytessent
< 0: self
.conn
.bytessent
= 0
480 self
.conn
.exceeded
= True
484 cmd
= self
.msgqueue
.popleft()
487 cmd
= self
.slowmsgqueue
.popleft()
492 if self
.conn
.bytessent
+len(cmd
) > self
.conn
.recvq
: # If it's too long
493 if len(cmd
) > self
.conn
.recvq
: # Is the command itself somehow over max length???
494 self
._msgtimer
.start()
495 raise ValueError('Somehow a command that was too long made it into the message queue. Uhoh!', cmd
)
496 # Discard the message.
497 self
.msgqueue
.appendleft(cmd
) # Phew, we've just sent too much recently. Put it (back) on the (primary) queue.
501 self
._msgtimer
.start()
503 def _makemsgtimer(self
):
504 self
._msgtimer
= MyTimer(3, self
._popmsg
)
506 def join(self
, chan
):
507 self
.conn
.send("JOIN %s" % (chan
))
509 def part(self
, chan
):
510 self
.conn
.send("PART %s" % (chan
))
512 def quit(self
, reason
="Shutdown"):
513 self
.conn
.send("QUIT :%s" % (reason
))
518 - 63 # max hostname len
520 - 3 # the symbols in :nick!user@host
524 def __str__(self
): return self
.nick
525 def __repr__(self
): return "<Bot %r>" % (self
.nick
)
527 class BotConnection(object):
528 def __init__(self
, parent
, bind
, server
, port
):
530 self
.buffer = bytearray()
535 self
.port
= int(port
)
537 self
.state
= 0 # 0=disconnected, 1=registering, 2=connected
540 self
.recvq
= 510 # How much we can send per period
541 self
.exceeded
= False
542 self
._nowrite
= False
545 if self
.parent
.parent
.cfg
.getboolean('erebus', 'tls'):
547 undersocket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
548 context
= ssl
.create_default_context()
549 self
.socket
= context
.wrap_socket(undersocket
, server_hostname
=self
.server
)
551 self
.socket
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
552 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.
553 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_LINGER
, struct
.pack('ii', 0, 0))
554 self
.socket
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_KEEPALIVE
, 1)
555 self
.socket
.bind((self
.bind
, 0))
556 self
._write
_oidentd
()
557 self
.socket
.connect((self
.server
, self
.port
))
561 pss
= self
.parent
.parent
.cfg
.get('erebus', 'pass')
563 self
.send("PASS %s" % (pss
))
564 self
.send("NICK %s" % (self
.parent
.nick
))
565 self
.send("USER %s 0 * :%s" % (self
.parent
.user
, self
.parent
.realname
))
569 def registered(self
, done
=False):
572 self
._unwrite
_oidentd
()
573 return self
.state
== 2
575 def send(self
, line
):
576 if not self
._nowrite
:
577 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
578 self
.parent
.log('O', line
)
579 self
.bytessent
+= len(line
)
582 except socket
.error
as e
:
584 self
.parent
._goterror
(repr(e
))
586 if self
.parent
.parent
.cfg
.getboolean('debug', 'io'):
587 self
.parent
.log('X', line
)
589 def _write(self
, line
):
590 self
.socket
.sendall(line
.encode('utf-8', 'backslashreplace')+b
"\r\n")
592 def _getsockerr(self
):
593 try: # SO_ERROR might not exist on all platforms
594 return self
.socket
.getsockopt(socket
.SOL_SOCKET
, socket
.SO_ERROR
)
599 recvd
= self
.socket
.recv(8192)
601 raise EOFError("socket.recv returned empty", self
.parent
.nick
, self
._getsockerr
())
605 while b
"\r\n" in self
.buffer:
606 pieces
= self
.buffer.split(b
"\r\n", 1)
607 lines
.append(pieces
[0].decode('utf-8', 'backslashreplace'))
608 self
.buffer = pieces
[1]
612 def _format_oidentd(self
):
613 ident
= self
.parent
.user
614 fport
= self
.parent
.port
616 lport
= self
.socket
.getsockname()[1]
618 return 'fport %s from %s lport %s { reply "%s" }\n' % (fport
, from_
, lport
, ident
)
620 return 'fport %s lport %s { reply "%s" }\n' % (fport
, lport
, ident
)
621 def _write_oidentd(self
):
622 path
= self
.parent
.parent
.cfg
.get('erebus', 'oidentd_path')
624 with open(path
, 'a') as fh
:
625 fcntl
.lockf(fh
, fcntl
.LOCK_EX
)
626 fh
.write(self
._format
_oidentd
())
627 fcntl
.lockf(fh
, fcntl
.LOCK_UN
)
628 def _unwrite_oidentd(self
):
629 path
= self
.parent
.parent
.cfg
.get('erebus', 'oidentd_path')
631 with open(path
, 'r+') as fh
:
632 fcntl
.lockf(fh
, fcntl
.LOCK_EX
)
634 newdata
= data
.replace(self
._format
_oidentd
(), '')
638 fcntl
.lockf(fh
, fcntl
.LOCK_UN
)
640 def __str__(self
): return self
.parent
.nick
641 def __repr__(self
): return "<BotConnection %r (%r)>" % (self
.socket
.fileno(), self
.parent
.nick
)