]> jfr.im git - erebus.git/blobdiff - bot.py
* - change old code to use newer cfg.getboolean instead of bool(int())
[erebus.git] / bot.py
diff --git a/bot.py b/bot.py
index aa22989c1b8c9957e025c83a52e0bdb30a9637dc..d5d397153821e7d3d8f4ce4c84cf476b3ec300a6 100644 (file)
--- a/bot.py
+++ b/bot.py
@@ -6,6 +6,14 @@
 import socket, sys, time, threading, os, random
 from collections import deque
 
+MAXLEN = 400 # arbitrary max length of a command generated by Bot.msg functions
+
+class MyTimer(threading._Timer):
+       def __init__(self, *args, **kwargs):
+               threading._Timer.__init__(self, *args, **kwargs)
+               self.daemon = True
+
+
 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
 class Bot(object):
        def __init__(self, parent, nick, user, bind, authname, authpass, server, port, realname):
@@ -18,23 +26,34 @@ class Bot(object):
                self.authname = authname
                self.authpass = authpass
 
-               curs = self.parent.db.cursor()
-               if curs.execute("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self.nick,)):
+               curs = self.parent.query("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self.nick,))
+               if curs:
                        chansres = curs.fetchall()
                        curs.close()
                        self.chans = [self.parent.newchannel(self, row['chname']) for row in chansres]
+               else:
+                       self.chans = []
 
                self.conn = BotConnection(self, bind, server, port)
 
+               self.lastreceived = time.time() #time we last received a line from the server
+               self.watchdog()
+
                self.msgqueue = deque()
                self.slowmsgqueue = deque()
                self.makemsgtimer()
+               self.msgtimer.start()
 
        def __del__(self):
-               curs = self.parent.db.cursor()
-               curs.execute("UPDATE bots SET connected = 0 WHERE nick = %s", (self.nick,))
-               curs.close()
+               try:
+                       curs = self.parent.query("UPDATE bots SET connected = 0 WHERE nick = %s", (self.nick,))
+                       curs.close()
+               except: pass
 
+       def watchdog(self):
+               if time.time() > int(self.parent.cfg.get('watchdog', 'maxtime', default=300))+self.lastreceived:
+                       self.parse("ERROR :Fake-error from watchdog timer.")
+               self.watchdogtimer = MyTimer(int(self.parent.cfg.get('watchdog', 'interval', default=30)), self.watchdog)
 
        def log(self, *args, **kwargs):
                self.parent.log(self.nick, *args, **kwargs)
@@ -44,6 +63,7 @@ class Bot(object):
                        self.parent.newfd(self, self.conn.socket.fileno())
 
        def getdata(self):
+               self.lastreceived = time.time()
                return self.conn.read()
 
        def _checknick(self): # check if we're using the right nick, try changing
@@ -51,7 +71,8 @@ class Bot(object):
                        self.conn.send("NICK %s" % (self.permnick))
 
        def parse(self, line):
-               self.log('I', line)
+               if self.parent.cfg.getboolean('debug', 'io'):
+                       self.log('I', line)
                pieces = line.split()
 
                # dispatch dict
@@ -70,6 +91,7 @@ class Bot(object):
                        '433': self._got433, #nick in use
                        'JOIN': self._gotjoin,
                        'PART': self._gotpart,
+                       'KICK': self._gotkick,
                        'QUIT': self._gotquit,
                        'NICK': self._gotnick,
                        'MODE': self._gotmode,
@@ -94,10 +116,12 @@ class Bot(object):
        def _gotping(self, pieces):
                self.conn.send("PONG %s" % (pieces[1]))
                self._checknick()
-       def _goterror(self, pieces): #TODO handle more gracefully
-               curs = self.parent.db.cursor()
-               curs.execute("UPDATE bots SET connected = 0")
-               curs.close()
+       def _goterror(self, pieces):
+               try:
+                       self.quit("Error detected: %s" % ' '.join(pieces))
+                       curs = self.parent.query("UPDATE bots SET connected = 0")
+                       curs.close()
+               except: pass
                sys.exit(2)
                os._exit(2)
        def _got001(self, pieces):
@@ -105,9 +129,8 @@ class Bot(object):
        def _gotRegistered(self, pieces):
                self.conn.registered(True)
 
-               curs = self.parent.db.cursor()
-               curs.execute("UPDATE bots SET connected = 1 WHERE nick = %s", (self.nick,))
-               curs.close()
+               curs = self.parent.query("UPDATE bots SET connected = 1 WHERE nick = %s", (self.nick,))
+               if curs: curs.close()
 
                self.conn.send("MODE %s +x" % (pieces[2]))
                if self.authname is not None and self.authpass is not None:
@@ -121,16 +144,16 @@ class Bot(object):
                msg = ' '.join(pieces[3:])[1:]
                self.parsemsg(user, target, msg)
        def _got353(self, pieces):
+               prefixes = {'@': 'op', '+': 'voice'}
                chan = self.parent.channel(pieces[4])
                names = pieces[5:]
                names[0] = names[0][1:] #remove colon
                for n in names:
-                       user = self.parent.user(n.lstrip('@+'))
-                       if n[0] == '@':
-                               chan.userjoin(user, 'op')
-                       elif n[0] == '+':
-                               chan.userjoin(user, 'voice')
+                       if n[0] in prefixes:
+                               user = self.parent.user(n[1:])
+                               chan.userjoin(user, prefixes[n[0]])
                        else:
+                               user = self.parent.user(n)
                                chan.userjoin(user)
                        user.join(chan)
        def _got354(self, pieces):
@@ -171,16 +194,21 @@ class Bot(object):
                        user = self.parent.user(nick, justjoined=True)
                        chan.userjoin(user)
                        user.join(chan)
-       def _gotpart(self, pieces):
-               nick = pieces[0].split('!')[0][1:]
-               chan = self.parent.channel(pieces[2])
-
+       def _clientLeft(self, nick, chan):
                if nick != self.nick:
                        gone = self.parent.user(nick).part(chan)
                        chan.userpart(self.parent.user(nick))
                        if gone:
                                self.parent.user(nick).quit()
                                del self.parent.users[nick.lower()]
+       def _gotpart(self, pieces):
+               nick = pieces[0].split('!')[0][1:]
+               chan = self.parent.channel(pieces[2])
+               self._clientLeft(nick, chan)
+       def _gotkick(self, pieces):
+               nick = pieces[3]
+               chan = self.parent.channel(pieces[2])
+               self._clientLeft(nick, chan)
        def _gotquit(self, pieces):
                nick = pieces[0].split('!')[0][1:]
                if nick != self.nick:
@@ -197,6 +225,8 @@ class Bot(object):
                self.parent.users[newnick.lower()].nickchange(newnick)
        def _gotmode(self, pieces):
                source = pieces[0].split('!')[0][1:]
+               chan = pieces[2]
+               if not chan.startswith("#"): return
                chan = self.parent.channel(pieces[2])
                mode = pieces[3]
                args = pieces[4:]
@@ -221,7 +251,7 @@ class Bot(object):
                                pass # don't care about other modes
 
        def __debug_cbexception(self, source, *args, **kwargs):
-               if int(self.parent.cfg.get('debug', 'cbexc', default=0)) == 1:
+               if self.parent.cfg.getboolean('debug', 'cbexc'):
                        self.conn.send("PRIVMSG %s :%09.3f \ 34\1f!!! CBEXC\1f\ 3 %s" % (self.parent.cfg.get('debug', 'owner'), time.time() % 100000, source))
                        __import__('traceback').print_exc()
                        self.log('!', "CBEXC %s %r %r" % (source, args, kwargs))
@@ -229,55 +259,64 @@ class Bot(object):
 
 
        def parsemsg(self, user, target, msg):
+               if user.glevel <= -2: return # short circuit if user is IGNORED
                chan = None
+               chanparam = None # was the channel specified as part of the command?
                if len(msg) == 0:
                        return
 
-               triggerused = msg[0] == self.parent.trigger
-               if triggerused: msg = msg[1:]
+               triggerused = msg.startswith(self.parent.trigger)
+               if triggerused: msg = msg[len(self.parent.trigger):]
                pieces = msg.split()
 
                if target == self.nick:
-                       if msg[0] == "\001": #ctcp
+                       if msg.startswith("\001"): #ctcp
                                msg = msg.strip("\001")
                                if msg == "VERSION":
                                        self.msg(user, "\001VERSION Erebus v%d.%d - http://github.com/zonidjan/erebus" % (self.parent.APIVERSION, self.parent.RELEASE))
                                return
-                       if len(pieces) > 1:
-                               chanword = pieces[1]
-                               if chanword[0] == '#':
-                                       chan = self.parent.channel(chanword)
-                                       if chan is not None: #if chan is still none, there's no bot on "chanword", and chanword is used as a parameter.
-                                               pieces.pop(1)
-
-               else: # message was sent to a channel
-                       chan = self.parent.channel(target)
+
+               if target != self.nick: # message was sent to a channel
                        try:
-                               if msg[0] == '*': # message may be addressed to bot by "*BOTNICK" trigger?
+                               if msg.startswith('*'): # message may be addressed to bot by "*BOTNICK" trigger?
                                        if pieces[0][1:].lower() == self.nick.lower():
                                                pieces.pop(0) # command actually starts with next word
                                                msg = ' '.join(pieces) # command actually starts with next word
-                               elif not triggerused:
-                                       if self.parent.haschanhook(target.lower()):
-                                               for callback in self.parent.getchanhook(target.lower()):
-                                                       try:
-                                                               cbret = callback(self, user, chan, *pieces)
-                                                       except NotImplementedError:
-                                                               self.msg(user, "Command not implemented.")
-                                                       except:
-                                                               self.msg(user, "Command failed. Code: CBEXC%09.3f" % (time.time() % 100000))
-                                                               self.__debug_cbexception("chanhook", user=user, target=target, msg=msg)
-                                       return # not to bot, don't process!
+                                               triggerused = True
                        except IndexError:
                                return # "message" is empty
 
-               cmd = pieces[0].lower()
+               if len(pieces) > 1:
+                       chanword = pieces[1]
+                       if chanword.startswith('#'):
+                               chanparam = self.parent.channel(chanword)
+
+               if target != self.nick: # message was sent to a channel
+                       chan = self.parent.channel(target)
+                       if not triggerused:
+                               if self.parent.haschanhook(target.lower()):
+                                       for callback in self.parent.getchanhook(target.lower()):
+                                               try:
+                                                       cbret = callback(self, user, chan, *pieces)
+                                               except NotImplementedError:
+                                                       self.msg(user, "Command not implemented.")
+                                               except:
+                                                       self.msg(user, "Command failed. Code: CBEXC%09.3f" % (time.time() % 100000))
+                                                       self.__debug_cbexception("chanhook", user=user, target=target, msg=msg)
+                               return # not to bot, don't process!
 
+               cmd = pieces[0].lower()
+               rancmd = False
                if self.parent.hashook(cmd):
                        for callback in self.parent.gethook(cmd):
+                               if chanparam is not None and (callback.needchan or callback.wantchan):
+                                       chan = chanparam
+                                       pieces.pop(1)
                                if chan is None and callback.needchan:
+                                       rancmd = True
                                        self.msg(user, "You need to specify a channel for that command.")
                                elif user.glevel >= callback.reqglevel and (not callback.needchan or chan.levelof(user.auth) >= callback.reqclevel):
+                                       rancmd = True
                                        try:
                                                cbret = callback(self, user, chan, target, *pieces[1:])
                                        except NotImplementedError:
@@ -286,60 +325,88 @@ class Bot(object):
                                                self.msg(user, "Command failed. Code: CBEXC%09.3f" % (time.time() % 100000))
                                                self.__debug_cbexception("hook", user=user, target=target, msg=msg)
                                        except SystemExit as e:
-                                               curs = self.parent.db.cursor()
-                                               curs.execute("UPDATE bots SET connected = 0")
-                                               curs.close()
+                                               try:
+                                                       curs = self.parent.query("UPDATE bots SET connected = 0")
+                                                       curs.close()
+                                               except: pass
                                                raise e
+               else:
+                       rancmd = True
+                       self.msg(user, "I don't know that command.")
+               if not rancmd:
+                       self.msg(user, "You don't have enough access to run that command.")
 
        def __debug_nomsg(self, target, msg):
-               if int(self.parent.cfg.get('debug', 'nomsg', default=0)) == 1:
+               if self.parent.cfg.getboolean('debug', 'nomsg'):
                        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))
                        self.log('!', "!!! NOMSG")
 #                      print "%09.3f %s [!] %s" % (time.time() % 100000, self.nick, "!!! NOMSG")
                        __import__('traceback').print_stack()
 
        def msg(self, target, msg):
-               if target is None or msg is None:
-                       return self.__debug_nomsg(target, msg)
-
-               self.msgqueue.append((target, msg))
-               if not self.msgtimer.is_alive():
-                       self._popmsg()
+               if self.parent.cfg.getboolean('erebus', 'nofakelag'): return self.fastmsg(target, msg)
+               cmd = self._formatmsg(target, msg)
+               if len(cmd) > MAXLEN: return False
+               if self.conn.exceeded or self.conn.bytessent+len(cmd) >= self.conn.recvq:
+                       self.msgqueue.append(cmd)
+               else:
+                       self.conn.send(cmd)
+               self.conn.exceeded = True
+               return True
 
        def slowmsg(self, target, msg):
-               if target is None or msg is None:
-                       return self.__debug_nomsg(target, msg)
-
-               self.slowmsgqueue.append((target, msg))
-               if not self.msgtimer.is_alive():
-                       self.msgtimer.start()
+               if self.parent.cfg.getboolean('erebus', 'nofakelag'): return self.fastmsg(target, msg)
+               cmd = self._formatmsg(target, msg)
+               if len(cmd) > MAXLEN: return False
+               if self.conn.exceeded or self.conn.bytessent+len(cmd) >= self.conn.recvq:
+                       self.slowmsgqueue.append(cmd)
+               else:
+                       self.conn.send(cmd)
+               self.conn.exceeded = True
+               return True
 
        def fastmsg(self, target, msg):
+               cmd = self._formatmsg(target, msg)
+               if len(cmd) > MAXLEN: return False
+               self.conn.send(cmd)
+               self.conn.exceeded = True
+               return True
+
+       def _formatmsg(self, target, msg):
                if target is None or msg is None:
                        return self.__debug_nomsg(target, msg)
 
                target = str(target)
 
-               if target[0] == '#': command = "PRIVMSG %s :%s" % (target, msg)
+               if target.startswith('#'): command = "PRIVMSG %s :%s" % (target, msg)
                else: command = "NOTICE %s :%s" % (target, msg)
 
-               self.conn.send(command)
+               return command
 
        def _popmsg(self):
                self.makemsgtimer()
+               self.conn.bytessent -= self.conn.recvq/3
+               if self.conn.bytessent < 0: self.conn.bytessent = 0
+               self.conn.exceeded = False
 
                try:
-                       self.fastmsg(*self.msgqueue.popleft())
-                       self.msgtimer.start()
+                       cmd = self.msgqueue.popleft()
+                       if not self.conn.exceeded and self.conn.bytessent+len(cmd) < self.conn.recvq:
+                               self.conn.send(cmd)
+                               self.conn.exceeded = True
+                       else: raise IndexError
                except IndexError:
                        try:
-                               self.fastmsg(*self.slowmsgqueue.popleft())
-                               self.msgtimer.start()
+                               cmd = self.slowmsgqueue.popleft()
+                               if not self.conn.exceeded and self.conn.bytessent+len(cmd) < self.conn.recvq:
+                                       self.conn.send(cmd)
+                                       self.conn.exceeded = True
                        except IndexError:
                                pass
+               self.msgtimer.start()
 
        def makemsgtimer(self):
-               self.msgtimer = threading.Timer(2, self._popmsg)
+               self.msgtimer = threading.Timer(3, self._popmsg)
                self.msgtimer.daemon = True
 
        def join(self, chan):
@@ -366,6 +433,10 @@ class BotConnection(object):
 
                self.state = 0 # 0=disconnected, 1=registering, 2=connected
 
+               self.bytessent = 0
+               self.recvq = 500
+               self.exceeded = False
+
        def connect(self):
                self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                self.socket.bind((self.bind, 0))
@@ -383,8 +454,10 @@ class BotConnection(object):
                return self.state == 2
 
        def send(self, line):
-               self.parent.log('O', line)
+               if self.parent.cfg.getboolean('debug', 'io'):
+                       self.parent.log('O', line)
 #              print "%09.3f %s [O] %s" % (time.time() % 100000, self.parent.nick, line)
+               self.bytessent += len(line)
                self._write(line)
 
        def _write(self, line):