Cleaned up the code

This commit is contained in:
Juhani Haverinen 2015-03-01 02:30:59 +02:00
parent 49a485c347
commit ad48a0695b
2 changed files with 284 additions and 193 deletions

194
botcmd.py
View File

@ -9,12 +9,15 @@ concmd=['/q','/lt','/st','/lg']
blacklist = ['bslsk05'] blacklist = ['bslsk05']
doctor = eliza.eliza() doctor = eliza.eliza()
trusted = [] trusted = []
trustedlock = threading.Lock() trustedlock = threading.Lock()
gods = [] gods = []
godslock = threading.Lock() godslock = threading.Lock()
msgs = {} msgs = {}
msglock=threading.Lock() msgslock = threading.Lock()
authcheck = {} authcheck = {}
authchecklock = threading.Lock() authchecklock = threading.Lock()
@ -27,14 +30,17 @@ class Cron(threading.Thread):
self.cronctrl = [] self.cronctrl = []
self.cronctrllock = threading.Lock() self.cronctrllock = threading.Lock()
threading.Thread.__init__(self) threading.Thread.__init__(self)
def queuejob(self, time, fn): def queuejob(self, time, fn):
self.timedjobslock.acquire() self.timedjobslock.acquire()
self.timedjobs.append((time, fn)) self.timedjobs.append((time, fn))
self.timedjobslock.release() self.timedjobslock.release()
def ctrl(self, cmd): def ctrl(self, cmd):
self.cronctrllock.acquire() self.cronctrllock.acquire()
self.cronctrl.append(cmd) self.cronctrl.append(cmd)
self.cronctrllock.release() self.cronctrllock.release()
def run(self): def run(self):
run = True run = True
while run: while run:
@ -56,61 +62,105 @@ class Cron(threading.Thread):
for fn in torun: for fn in torun:
fn() fn()
msglock.acquire() cron=Cron()
cron.start()
def loadmessages():
global msgs, msgslock
msgslock.acquire()
f = open('msgs.txt', 'r') f = open('msgs.txt', 'r')
for line in f: for line in f:
while len(line)>0 and line[-1]=='\n': line=line[:-1] while len(line) > 0 and line[-1] == '\n':
line = line[:-1]
if len(line) > 0: if len(line) > 0:
receiver, sender, msg = line.split('\t') receiver, sender, msg = line.split('\t')
if receiver not in msgs: if receiver not in msgs:
msgs[receiver] = [] msgs[receiver] = []
msgs[receiver].append((sender, msg)) msgs[receiver].append((sender, msg))
f.close()
msglock.release()
cron=Cron() f.close()
cron.start() msgslock.release()
def savemessages():
global msgs, msgslock
msgslock.acquire()
f=open('msgs.txt', 'w')
for receiver in msgs:
for sender, msg in msgs[receiver]:
f.write('%s\t%s\t%s\n' % (receiver, sender, msg))
f.close()
msgslock.release()
loadmessages()
def addtrusted(nick): def addtrusted(nick):
global trusted, trustedlock
trustedlock.acquire() trustedlock.acquire()
if nick not in trusted: if nick not in trusted:
trusted.append(nick) trusted.append(nick)
trustedlock.release() trustedlock.release()
def rmtrusted(nick): def rmtrusted(nick):
global trusted, trustedlock
trustedlock.acquire() trustedlock.acquire()
if nick in trusted: if nick in trusted:
trusted.remove(nick) trusted.remove(nick)
trustedlock.release() trustedlock.release()
def loadtrusted(): def loadtrusted():
global trusted, trustedlock
trustedlock.acquire() trustedlock.acquire()
while len(trusted)>0: trusted.pop() #I'm really sorry but trusted=[] created trusted as local variable trusted = []
trustedlock.release() trustedlock.release()
f=open('trusted.txt', 'r') f=open('trusted.txt', 'r')
for line in f: for line in f:
while len(line)>0 and line[-1]=='\n': line=line[:-1] while len(line) > 0 and line[-1] == '\n':
line = line[:-1]
if len(line) > 0: if len(line) > 0:
addtrusted(line) addtrusted(line)
f.close() f.close()
def loadgods(): def loadgods():
global gods, godslock
godslock.acquire() godslock.acquire()
while len(gods)>0: gods.pop() #See above gods = []
f=open('gods.txt', 'r') f=open('gods.txt', 'r')
for line in f: for line in f:
while len(line)>0 and line[-1]=='\n': line=line[:-1] while len(line) > 0 and line[-1] == '\n':
line = line[:-1]
if len(line) > 0: if len(line) > 0:
gods.append(line) gods.append(line)
addtrusted(line) addtrusted(line)
f.close() f.close()
godslock.release() godslock.release()
def savetrusted(): def savetrusted():
global trusted, trustedlock
trustedlock.acquire() trustedlock.acquire()
f=open('trusted.txt', 'w') f=open('trusted.txt', 'w')
for i in trusted: for i in trusted:
f.write(i+'\n') f.write(i+'\n')
f.close f.close
trustedlock.release() trustedlock.release()
@ -137,12 +187,14 @@ def istrusted(nick):
def initauthcheck(nick): def initauthcheck(nick):
global authcheck, authchecklock global authcheck, authchecklock
authchecklock.acquire() authchecklock.acquire()
authcheck[nick] = None authcheck[nick] = None
authchecklock.release() authchecklock.release()
def setauthcheckstate(nick, state): def setauthcheckstate(nick, state):
global authcheck, authchecklock global authcheck, authchecklock
authchecklock.acquire() authchecklock.acquire()
if nick in authcheck: if nick in authcheck:
authcheck[nick] = state authcheck[nick] = state
@ -150,14 +202,17 @@ def setauthcheckstate(nick, state):
def getauthcheckstate(nick): def getauthcheckstate(nick):
global authcheck, authchecklock global authcheck, authchecklock
authchecklock.acquire() authchecklock.acquire()
if nick in authcheck: if nick in authcheck:
state = authcheck[nick] state = authcheck[nick]
authchecklock.release() authchecklock.release()
return state return state
def removeauthcheck(nick): def removeauthcheck(nick):
global authcheck, authchecklock global authcheck, authchecklock
authchecklock.acquire() authchecklock.acquire()
if nick in authcheck: if nick in authcheck:
del authcheck[nick] del authcheck[nick]
@ -294,6 +349,11 @@ def parsecmd(line, args):
return out return out
def parse((line, irc)): def parse((line, irc)):
global blacklist
global msgs, msgslock
global trusted, trustedlock, gods, godslock
global doctor, die_expr
line = line.split(' ') line = line.split(' ')
nick = line[0].split('!')[0][1:] nick = line[0].split('!')[0][1:]
chan = line[2] if line[2][0] == '#' else nick chan = line[2] if line[2][0] == '#' else nick
@ -309,9 +369,9 @@ def parse((line,irc)):
cmdline = [line[3][1:]] + line[4:] cmdline = [line[3][1:]] + line[4:]
while '' in cmdline: while '' in cmdline:
cmdline.remove('') cmdline.remove('')
if matchcmd(cmdline, '#echo'): if matchcmd(cmdline, '#echo'):
text = parsecmd(cmdline, '{text}') text = parsecmd(cmdline, '{text}')
print text #debg
irc.msg(chan, zwsp+text) irc.msg(chan, zwsp+text)
elif matchcmd(cmdline, '#op'): elif matchcmd(cmdline, '#op'):
args = parsecmd(cmdline, '{args}') args = parsecmd(cmdline, '{args}')
@ -344,11 +404,11 @@ def parse((line,irc)):
elif matchcmd(cmdline, '#msg'): elif matchcmd(cmdline, '#msg'):
if matchcmd(cmdline, '#msg', 'nick {message}'): if matchcmd(cmdline, '#msg', 'nick {message}'):
msgnick, message = parsecmd(cmdline, 'nick {message}') msgnick, message = parsecmd(cmdline, 'nick {message}')
msglock.acquire() msgslock.acquire()
if msgnick not in msgs: if msgnick not in msgs:
msgs[msgnick] = [] msgs[msgnick] = []
msgs[msgnick].append((nick, message)) msgs[msgnick].append((nick, message))
msglock.release() msgslock.release()
else: else:
irc.msg(chan, 'Usage: #msg nick message') irc.msg(chan, 'Usage: #msg nick message')
elif matchcmd(cmdline, '#trusted?'): elif matchcmd(cmdline, '#trusted?'):
@ -431,38 +491,24 @@ def parse((line,irc)):
if line[5] == '0': if line[5] == '0':
irc.msg(line[3][1:], 'Register account with NickServ') irc.msg(line[3][1:], 'Register account with NickServ')
elif line[5] == '1': elif line[5] == '1':
irc.msg(line[3][1:], 'PRIVMSG %s :Identify with NickServ') irc.msg(line[3][1:], 'Identify with NickServ')
else: else:
irc.msg(line[3][1:], 'WTF, NickServ returned %s'+line[5]) irc.msg(line[3][1:], 'WTF, NickServ returned %s' % line[5])
elif line[1] == 'INVITE' and line[2] == irc.nick and line[3][1:] in irc.chan.split(' '): elif line[1] == 'INVITE' and line[2] == irc.nick and line[3][1:] in irc.chan.split(' '):
if isauthorized(irc, nick): if isauthorized(irc, nick):
irc.send('JOIN ' + line[3]) irc.send('JOIN ' + line[3])
elif line[1] == '482': elif line[1] == '482':
irc.msg(line[3], 'Not op') irc.msg(line[3], 'Not op')
#elif line[1]=='332' or line[1]=='TOPIC':
# if line[1]=='332':
# ch=line[3]
# tp=' '.join(line[4:])[1:]
# elif line[1]=='TOPIC':
# ch=line[2]
# tp=' '.join(line[3:])[1:]
# #Do the magic here
msglock.acquire() msgslock.acquire()
if (line[1] == 'PRIVMSG' or line[1] == 'JOIN') and nick in msgs: if (line[1] == 'PRIVMSG' or line[1] == 'JOIN') and nick in msgs:
for sender, msg in msgs.pop(nick): for sender, msg in msgs.pop(nick):
irc.msg(nick, '<%s> %s' % (sender, msg)) irc.msg(nick, '<%s> %s' % (sender, msg))
msglock.release() msgslock.release()
def execcmd(cmdline): def execcmd(cmdline):
if cmdline[0] == '/q': if cmdline[0] == '/q':
msglock.acquire() savemessages()
f=open('msgs.txt','w')
for receiver in msgs:
for sender, msg in msgs[receiver]:
f.write('%s\t%s\t%s\n'%(receiver,sender,msg))
f.close()
msglock.release()
savetrusted() savetrusted()
cron.ctrl('QUIT') cron.ctrl('QUIT')
@ -473,38 +519,54 @@ def execcmd(cmdline):
elif cmdline[0] == '/lg': elif cmdline[0] == '/lg':
loadgods() loadgods()
def help(cmd): def usage(cmd, message = True):
if cmd=='': usage = {'#echo': 'text',
return '#echo #op #deop #voice #devoice #kick #src #msg #trusted? #trust #untrust #ls-trusted #invite #help' '#op': '[nick]',
elif cmd=='#echo': '#deop': '[nick]',
return '#echo text echo text back' '#voice': '[nick]',
elif cmd=='#op': '#devoice': '[nick]',
return '#op [nick] give nick or yourself op rights in case you are trusted by oonbotti2 and identified with NickServ' '#kick': 'nick [reason]',
elif cmd=='#deop': '#src': '',
return '#deop [nick] remove your/nick\'s op rights' '#msg': 'nick message',
elif cmd=='#voice': '#trusted?': 'nick',
return '#voice [nick] give nick or yourself voice in case you are trusted by oonbotti2 and identified with NickServ' '#trust': 'nick',
elif cmd=='#devoice': '#untrust': 'nick',
return '#devoice [nick] remove your or nick\'s voice in case you are trusted by oonbotti2 and identified with NickServ' '#ls-trusted': '',
elif cmd=='#kick': '#invite': 'nick',
return '#kick nick reason kicks nick with specified reason' '#help': '[command]'}
elif cmd=='#src':
return '#src paste a link to oonbotti2\'s git repo' if cmd in usage:
elif cmd=='#msg': if message:
return '#msg nick message send a message to nick' return 'Usage: %s %s' % (cmd, usage[cmd])
elif cmd=='#trusted?': else:
return '#trusted? [nick] tell you if nick or yourself is trusted by oonbotti2' return usage[cmd]
elif cmd=='#trust': else:
return '#trust nick add nick to trusted list' return None
elif cmd=='#untrust':
return '#untrust nick remove nick from trusted list' def help(cmd):
elif cmd=='#ls-trusted': helptext = {'#echo': '#echo text back',
return '#ls-trusted list nicks that are trusted. use only in a query' '#op': 'give nick or yourself op rights in case you are trusted by oonbotti2 and identified with NickServ',
elif cmd=='#invite': '#deop': 'remove your/nick\'s op rights',
return '#invite nick invites nick to channel' '#voice': 'give nick or yourself voice in case you are trusted by oonbotti2 and identified with NickServ',
elif cmd=='#help': '#devoice': 'remove your or nick\'s voice in case you are trusted by oonbotti2 and identified with NickServ',
return '#help [command] give short info of command or list commands' '#kick': 'kicks nick with specified reason',
elif cmd=='me': '#src': 'paste a link to oonbotti2\'s git repo',
return 'I shall.' '#msg': 'send a message to nick',
'#trusted?': 'tell you if nick or yourself is trusted by oonbotti2',
'#trust': 'add nick to trusted list',
'#untrust': 'remove nick from trusted list',
'#ls-trusted': 'list nicks that are trusted. use only in a query',
'#invite': 'invites nick to channel',
'#help': 'give short info of command or list commands'}
if cmd=='':
return '#echo #op #deop #voice #devoice #kick #src #msg #trusted? #trust #untrust #ls-trusted #invite #help'
elif cmd=='me':
return 'I shall.'
elif cmd in helptext:
if helptext[cmd]:
return '%s %s %s' % (cmd, usage(cmd, False), helptext[cmd])
else:
return '%s %s' % (cmd, usage(cmd, False))
else: else:
return None return None

View File

@ -10,20 +10,25 @@ class Channel:
def __init__(self): def __init__(self):
self.lock = threading.Lock() self.lock = threading.Lock()
self.msg = [] self.msg = []
def send(self, msg): def send(self, msg):
self.lock.acquire() self.lock.acquire()
self.msg.append(msg) self.msg.append(msg)
self.lock.release() self.lock.release()
def recv(self, wait = True): def recv(self, wait = True):
while True: while True:
self.lock.acquire() self.lock.acquire()
if len(self.msg) > 0: if len(self.msg) > 0:
msg = self.msg.pop(0) msg = self.msg.pop(0)
self.lock.release() self.lock.release()
return msg return msg
if not wait: if not wait:
self.lock.release() self.lock.release()
return None return None
self.lock.release() self.lock.release()
time.sleep(0.1) time.sleep(0.1)
@ -45,6 +50,7 @@ class Irc:
class Connhandler(threading.Thread): class Connhandler(threading.Thread):
def __init__(self, server, port, chan, nick, botname, inpc, logc): def __init__(self, server, port, chan, nick, botname, inpc, logc):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.server = server self.server = server
self.port = port self.port = port
self.nick = nick self.nick = nick
@ -52,12 +58,16 @@ class Connhandler(threading.Thread):
self.chan = chan self.chan = chan
self.inpc = inpc self.inpc = inpc
self.logc = logc self.logc = logc
def send(self, s): def send(self, s):
s = s.replace('\n', '\\n').replace('\r', '\\r') # Sanitize output s = s.replace('\n', '\\n').replace('\r', '\\r') # Sanitize output
if len(s)>512: s=s[:512] if len(s) > 512:
s = s[:512]
self.sock.send(s + '\r\n') self.sock.send(s + '\r\n')
if s.split(' ')[0] != 'PONG': if s.split(' ')[0] != 'PONG':
self.logc.send(s + '\n') self.logc.send(s + '\n')
def check(self, line): def check(self, line):
args = line.split(' ') args = line.split(' ')
if args[0] == 'PING': if args[0] == 'PING':
@ -80,20 +90,25 @@ class Connhandler(threading.Thread):
self.sock = None self.sock = None
continue continue
break break
if self.sock is None: if self.sock is None:
self.logc.send('QUIT'); self.logc.send('QUIT');
sys.exit(1); sys.exit(1);
self.sock.settimeout(0.1) self.sock.settimeout(0.1)
self.send('NICK %s' % self.nick) self.send('NICK %s' % self.nick)
self.send('USER %s a a :%s' % (self.nick, self.name)) self.send('USER %s a a :%s' % (self.nick, self.name))
f = open('startcmd.txt', 'r') f = open('startcmd.txt', 'r')
for i in f: for i in f:
if i[-1]=='\n': i=i[:-1] if i[-1] == '\n':
i = i[:-1]
self.send(i) self.send(i)
f.close() f.close()
for i in self.chan.split(' '): for i in self.chan.split(' '):
self.send('JOIN %s'%(i)) self.send('JOIN %s' % i)
buf = '' buf = ''
while True: while True:
@ -103,6 +118,7 @@ class Connhandler(threading.Thread):
break break
except: except:
pass pass
cmd = self.inpc.recv(wait = False) cmd = self.inpc.recv(wait = False)
if cmd == 'QUIT': if cmd == 'QUIT':
data = None data = None
@ -110,33 +126,43 @@ class Connhandler(threading.Thread):
break break
elif cmd: elif cmd:
self.send(cmd) self.send(cmd)
time.sleep(0.1) time.sleep(0.1)
if not data: break
if not data:
break
buf += data buf += data
buf = buf.split('\n') buf = buf.split('\n')
for line in buf[:-1]: for line in buf[:-1]:
if line[-1]=='\r': line=line[:-1] if line[-1] == '\r':
line = line[:-1]
self.check(line) self.check(line)
buf = buf[-1] buf = buf[-1]
self.sock.close() self.sock.close()
class Keyhandler(threading.Thread): class Keyhandler(threading.Thread):
def __init__(self, outc): def __init__(self, outc):
self.outc = outc self.outc = outc
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
while True: while True:
line = raw_input() line = raw_input()
c=line.split(' ') if line == '':
if c == '':
continue continue
c = line.split(' ')
if c[0] in botcmd.concmd: if c[0] in botcmd.concmd:
botcmd.execcmd(c) botcmd.execcmd(c)
if c[0] == '/j' and len(c) == 2: if c[0] == '/j' and len(c) == 2:
self.outc.send('JOIN ' + c[1]) self.outc.send('JOIN ' + c[1])
elif c[0] == '/m' and len(c) > 2: elif c[0] == '/m' and len(c) > 2:
self.outc.send('PRIVMSG %s :%s' % (c[1], ' '.join(c[2:]))) self.outc.send('PRIVMSG %s :%s' % (c[1], ' '.join(c[2:])))
elif c[0]=='/q' and len(c)==1: elif c[0] == '/q':
if len(c) > 1:
self.outc.send('QUIT :%s' % ' '.join(c[1:]))
self.outc.send('QUIT') self.outc.send('QUIT')
break break
elif c[0][0] == '/' and c[0] not in botcmd.concmd: elif c[0][0] == '/' and c[0] not in botcmd.concmd:
@ -146,10 +172,12 @@ class Loghandler(threading.Thread):
def __init__(self, inpc): def __init__(self, inpc):
self.inpc = inpc self.inpc = inpc
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
while True: while True:
s = self.inpc.recv() s = self.inpc.recv()
if s=='QUIT': break if s == 'QUIT':
break
sys.stdout.write(''.join([i if ord(i)>=32 or i=='\n' else '^'+chr(ord(i)+64) for i in s])) sys.stdout.write(''.join([i if ord(i)>=32 or i=='\n' else '^'+chr(ord(i)+64) for i in s]))
class Threadwrapper(threading.Thread): class Threadwrapper(threading.Thread):
@ -157,6 +185,7 @@ class Threadwrapper(threading.Thread):
self.func = func self.func = func
self.arg = arg self.arg = arg
threading.Thread.__init__(self) threading.Thread.__init__(self)
def run(self): def run(self):
self.func(self.arg) self.func(self.arg)