]> jfr.im git - erebus.git/blobdiff - bot.py
userinfo - remove _ from keys/has/get/set/delete
[erebus.git] / bot.py
diff --git a/bot.py b/bot.py
index fc9557e2ce507a5753c0b134d0a2d33a87a1193b..d56be6f94e9bcf50229766494c0f9dc23a605919 100644 (file)
--- a/bot.py
+++ b/bot.py
@@ -1,4 +1,5 @@
 #!/usr/bin/python
+# vim: fileencoding=utf-8
 
 # Erebus IRC bot - Author: John Runyon
 # "Bot" and "BotConnection" classes (handling a specific "arm")
@@ -6,11 +7,23 @@
 import socket, sys, time, threading, os, random
 from collections import deque
 
-class MyTimer(threading._Timer):
+MAXLEN = 400 # arbitrary max length of a command generated by Bot.msg functions
+
+if sys.version_info.major < 3:
+       timerbase = threading._Timer
+       stringbase = basestring
+else:
+       timerbase = threading.Timer
+       stringbase = str
+class MyTimer(timerbase):
        def __init__(self, *args, **kwargs):
-               threading._Timer.__init__(self, *args, **kwargs)
+               timerbase.__init__(self, *args, **kwargs)
                self.daemon = True
 
+if sys.version_info.major < 3:
+       stringbase = basestring
+else:
+       stringbase = str
 
 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
 class Bot(object):
@@ -24,8 +37,8 @@ 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]
@@ -43,14 +56,15 @@ class Bot(object):
                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() > self.parent.cfg.get('watchdog', 'maxtime', default=300)+self.lastreceived:
+               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(self.parent.cfg.get('watchdog', 'interval', default=30), self.watchdog)
+               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)
@@ -68,7 +82,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
@@ -113,11 +128,11 @@ class Bot(object):
                self.conn.send("PONG %s" % (pieces[1]))
                self._checknick()
        def _goterror(self, pieces):
-               try: self.quit("Error detected: %s" % ' '.join(pieces))
+               try:
+                       self.quit("Error detected: %s" % ' '.join(pieces))
+                       curs = self.parent.query("UPDATE bots SET connected = 0")
+                       curs.close()
                except: pass
-               curs = self.parent.db.cursor()
-               curs.execute("UPDATE bots SET connected = 0")
-               curs.close()
                sys.exit(2)
                os._exit(2)
        def _got001(self, pieces):
@@ -125,9 +140,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:
@@ -178,7 +192,7 @@ class Bot(object):
                                self.msg(nick, "I tried, but you're not authed!")
        def _got433(self, pieces):
                if not self.conn.registered(): #we're trying to connect
-                       newnick = "%s%d" % (self.nick, random.randint(111,999))
+                       newnick = "%s%d" % (self.nick, random.randint(111, 999))
                        self.conn.send("NICK %s" % (newnick))
                        self.nick = newnick
        def _gotjoin(self, pieces):
@@ -248,7 +262,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))
@@ -262,10 +276,6 @@ class Bot(object):
                if len(msg) == 0:
                        return
 
-               triggerused = msg.startswith(self.parent.trigger)
-               if triggerused: msg = msg[len(self.parent.trigger):]
-               pieces = msg.split()
-
                if target == self.nick:
                        if msg.startswith("\001"): #ctcp
                                msg = msg.strip("\001")
@@ -273,6 +283,10 @@ class Bot(object):
                                        self.msg(user, "\001VERSION Erebus v%d.%d - http://github.com/zonidjan/erebus" % (self.parent.APIVERSION, self.parent.RELEASE))
                                return
 
+               triggerused = msg.startswith(self.parent.trigger)
+               if triggerused: msg = msg[len(self.parent.trigger):]
+               pieces = msg.split()
+
                if target != self.nick: # message was sent to a channel
                        try:
                                if msg.startswith('*'): # message may be addressed to bot by "*BOTNICK" trigger?
@@ -283,6 +297,9 @@ class Bot(object):
                        except IndexError:
                                return # "message" is empty
 
+               if len(pieces) == 0:
+                       return
+
                if len(pieces) > 1:
                        chanword = pieces[1]
                        if chanword.startswith('#'):
@@ -316,15 +333,20 @@ class Bot(object):
                                        rancmd = True
                                        try:
                                                cbret = callback(self, user, chan, target, *pieces[1:])
+                                               if cbret is NotImplemented:
+                                                       raise NotImplementedError
+                                               elif isinstance(cbret, stringbase):
+                                                       self.reply(chan, user, cbret)
                                        except NotImplementedError:
                                                self.msg(user, "Command not implemented.")
                                        except Exception:
                                                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
@@ -333,31 +355,47 @@ class Bot(object):
                        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 reply(self, chan, user, msg):
+               if chan is not None:
+                       self.msg(chan, "%s: %s" % (user, msg))
+               else:
+                       self.msg(user, msg)
+
        def msg(self, target, msg):
+               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 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):
-               self.conn.send(self._formatmsg(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:
@@ -411,7 +449,7 @@ class Bot(object):
 class BotConnection(object):
        def __init__(self, parent, bind, server, port):
                self.parent = parent
-               self.buffer = ''
+               self.buffer = bytearray(8192)
                self.socket = None
 
                self.bind = bind
@@ -441,23 +479,21 @@ class BotConnection(object):
                return self.state == 2
 
        def send(self, line):
-               self.parent.log('O', line)
-#              print "%09.3f %s [O] %s" % (time.time() % 100000, self.parent.nick, line)
+               if self.parent.parent.cfg.getboolean('debug', 'io'):
+                       self.parent.log('O', line)
                self.bytessent += len(line)
                self._write(line)
 
        def _write(self, line):
-               self.socket.sendall(line+"\r\n")
+               self.socket.sendall(line.encode('utf-8', 'backslashreplace')+b"\r\n")
 
        def read(self):
                self.buffer += self.socket.recv(8192)
                lines = []
 
-               while "\r\n" in self.buffer:
-                       pieces = self.buffer.split("\r\n", 1)
-#                      self.parent.log('I', pieces[0]) # replaced by statement in Bot.parse()
-#                      print "%09.3f %s [I] %s" % (time.time() % 100000, self.parent.nick, pieces[0])
-                       lines.append(pieces[0])
+               while b"\r\n" in self.buffer:
+                       pieces = self.buffer.split(b"\r\n", 1)
+                       lines.append(pieces[0].decode('utf-8', 'backslashreplace'))
                        self.buffer = pieces[1]
 
                return lines