]> jfr.im git - erebus.git/blobdiff - bot.py
trivia - updated example json
[erebus.git] / bot.py
diff --git a/bot.py b/bot.py
index f3df2785d42f2e1281aafbf5ed7b0962201fa66e..9bf8e0d092dbb5de4d64b7ac3db877151902448d 100644 (file)
--- a/bot.py
+++ b/bot.py
@@ -3,7 +3,7 @@
 # Erebus IRC bot - Author: John Runyon
 # "Bot" and "BotConnection" classes (handling a specific "arm")
 
-import socket, sys, time, threading, os
+import socket, sys, time, threading, os, random
 from collections import deque
 
 #bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
@@ -11,6 +11,7 @@ class Bot(object):
        def __init__(self, parent, nick, user, bind, authname, authpass, server, port, realname):
                self.parent = parent
                self.nick = nick
+               self.permnick = nick
                self.user = user
                self.realname = realname
 
@@ -28,6 +29,7 @@ class Bot(object):
                self.msgqueue = deque()
                self.slowmsgqueue = deque()
                self.makemsgtimer()
+               self.msgtimer.start()
 
        def __del__(self):
                curs = self.parent.db.cursor()
@@ -35,6 +37,9 @@ class Bot(object):
                curs.close()
 
 
+       def log(self, *args, **kwargs):
+               self.parent.log(self.nick, *args, **kwargs)
+
        def connect(self):
                if self.conn.connect():
                        self.parent.newfd(self, self.conn.socket.fileno())
@@ -42,19 +47,28 @@ class Bot(object):
        def getdata(self):
                return self.conn.read()
 
+       def _checknick(self): # check if we're using the right nick, try changing
+               if self.nick != self.permnick and self.conn.registered():
+                       self.conn.send("NICK %s" % (self.permnick))
+
        def parse(self, line):
+               self.log('I', line)
                pieces = line.split()
 
                # dispatch dict
                zero = { #things to look for without source
-                       'NOTICE': self._gotregistered,
+                       'NOTICE': self._gotconnected,
                        'PING': self._gotping,
                        'ERROR': self._goterror,
                }
                one = { #things to look for after source
                        '001': self._got001,
+                       '376': self._gotRegistered,
+                       '422': self._gotRegistered,
                        'PRIVMSG': self._gotprivmsg,
-                       '354': self._got354,
+                       '353': self._got353, #NAMES
+                       '354': self._got354, #WHO
+                       '433': self._got433, #nick in use
                        'JOIN': self._gotjoin,
                        'PART': self._gotpart,
                        'QUIT': self._gotquit,
@@ -75,18 +89,21 @@ class Bot(object):
                elif pieces[1] in one:
                        one[pieces[1]](pieces)
 
-       def _gotregistered(self, pieces):
+       def _gotconnected(self, pieces):
                if not self.conn.registered():
                        self.conn.register()
        def _gotping(self, pieces):
                self.conn.send("PONG %s" % (pieces[1]))
-       def _goterror(self, pieces): #TODO handle better
+               self._checknick()
+       def _goterror(self, pieces): #TODO handle more gracefully
                curs = self.parent.db.cursor()
                curs.execute("UPDATE bots SET connected = 0")
                curs.close()
                sys.exit(2)
                os._exit(2)
        def _got001(self, pieces):
+               pass # wait until the end of MOTD instead
+       def _gotRegistered(self, pieces):
                self.conn.registered(True)
 
                curs = self.parent.db.cursor()
@@ -104,11 +121,35 @@ class Bot(object):
                target = pieces[2]
                msg = ' '.join(pieces[3:])[1:]
                self.parsemsg(user, target, msg)
+       def _got353(self, pieces):
+               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')
+                       else:
+                               chan.userjoin(user)
+                       user.join(chan)
        def _got354(self, pieces):
-               qt, nick, auth = pieces[3:6]
+               qt = int(pieces[3])
+               if qt < 3:
+                       nick, auth = pieces[4:6]
+                       chan = None
+               else:
+                       chan, nick, auth = pieces[4:7]
+                       chan = self.parent.channel(chan)
                user = self.parent.user(nick)
                user.authed(auth)
-               if qt == "2":
+
+               if chan is not None:
+                       user.join(chan)
+                       chan.userjoin(user)
+
+               if qt == 2: # triggered by !auth
                        if user.isauthed():
                                if user.glevel > 0:
                                        self.msg(nick, "You are now known as #%s (access level: %s)" % (auth, user.glevel))
@@ -116,12 +157,17 @@ class Bot(object):
                                        self.msg(nick, "You are now known as #%s (not staff)" % (auth))
                        else:
                                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))
+                       self.conn.send("NICK %s" % (newnick))
+                       self.nick = newnick
        def _gotjoin(self, pieces):
                nick = pieces[0].split('!')[0][1:]
                chan = self.parent.channel(pieces[2])
 
                if nick == self.nick:
-                       self.conn.send("WHO %s c%%ant,1" % (chan))
+                       self.conn.send("WHO %s c%%cant,3" % (chan))
                else:
                        user = self.parent.user(nick, justjoined=True)
                        chan.userjoin(user)
@@ -131,11 +177,16 @@ class Bot(object):
                chan = self.parent.channel(pieces[2])
 
                if nick != self.nick:
-                       self.parent.user(nick).part(chan)
+                       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 _gotquit(self, pieces):
                nick = pieces[0].split('!')[0][1:]
                if nick != self.nick:
+                       for chan in self.parent.user(nick).chans:
+                               chan.userpart(self.parent.user(nick))
                        self.parent.user(nick).quit()
                        del self.parent.users[nick.lower()]
        def _gotnick(self, pieces):
@@ -145,15 +196,37 @@ class Bot(object):
                        self.parent.users[newnick.lower()] = self.parent.users[oldnick.lower()]
                        del self.parent.users[oldnick.lower()]
                self.parent.users[newnick.lower()].nickchange(newnick)
-       def _gotmode(self, pieces): #TODO parse for ops/voices (at least)
-               pass
-
+       def _gotmode(self, pieces):
+               source = pieces[0].split('!')[0][1:]
+               chan = self.parent.channel(pieces[2])
+               mode = pieces[3]
+               args = pieces[4:]
+
+               adding = True
+               for c in mode:
+                       if c == '+':
+                               adding = True
+                       elif c == '-':
+                               adding = False
+                       elif c == 'o':
+                               if adding:
+                                       chan.userop(self.parent.user(args.pop(0)))
+                               else:
+                                       chan.userdeop(self.parent.user(args.pop(0)))
+                       elif c == 'v':
+                               if adding:
+                                       chan.uservoice(self.parent.user(args.pop(0)))
+                               else:
+                                       chan.userdevoice(self.parent.user(args.pop(0)))
+                       else:
+                               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:
-                       self.conn.send("PRIVMSG %s :%09.3f ^C4^B!!!^B^C CBEXC %s" % (self.parent.cfg.get('debug', 'owner'), time.time() % 100000, source))
+                       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()
-                       print "%09.3f %s [!] CBEXC %s %r %r" % (time.time() % 100000, self.nick, source, args, kwargs)
+                       self.log('!', "CBEXC %s %r %r" % (source, args, kwargs))
+#                      print "%09.3f %s [!] CBEXC %s %r %r" % (time.time() % 100000, self.nick, source, args, kwargs)
 
 
        def parsemsg(self, user, target, msg):
@@ -218,30 +291,37 @@ class Bot(object):
                                                curs.execute("UPDATE bots SET connected = 0")
                                                curs.close()
                                                raise e
+               else:
+                       self.msg(user, "I don't know that command.")
 
        def __debug_nomsg(self, target, msg):
                if int(self.parent.cfg.get('debug', 'nomsg', default=0)) == 1:
-                       self.conn.send("PRIVMSG %s :%09.3f \ 34\ 2!!!\ 2\ 3 NOMSG %r, %r" % (self.parent.cfg.get('debug', 'owner'), time.time() % 100000, target, msg))
-                       print "%09.3f %s [!] %s" % (time.time() % 100000, self.nick, "!!! 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.msgtimer.start()
+               cmd = self._formatmsg(target, msg)
+               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
 
        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()
+               cmd = self._formatmsg(target, msg)
+               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
 
        def fastmsg(self, target, msg):
+               self.conn.send(self._formatmsg(target, msg))
+               self.conn.exceeded = True
+
+       def _formatmsg(self, target, msg):
                if target is None or msg is None:
                        return self.__debug_nomsg(target, msg)
 
@@ -250,23 +330,32 @@ class Bot(object):
                if target[0] == '#': 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):
@@ -293,6 +382,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))
@@ -310,7 +403,9 @@ class BotConnection(object):
                return self.state == 2
 
        def send(self, line):
-               print "%09.3f %s [O] %s" % (time.time() % 100000, self.parent.nick, line)
+               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):
@@ -322,8 +417,8 @@ class BotConnection(object):
 
                while "\r\n" in self.buffer:
                        pieces = self.buffer.split("\r\n", 1)
-                       print "%09.3f %s [I] %s" % (time.time() % 100000, self.parent.nick, pieces[0])
-#                      print (time.time() % 1460000000), self.parent.nick, '[I]', pieces[0]
+#                      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])
                        self.buffer = pieces[1]