1
0
Fork 0

redone logging of exceptions

added more try ... except
added choose command
done some commenting
This commit is contained in:
fanir 2014-03-06 16:44:14 +01:00
parent e1b0e83e98
commit 421c206719

90
main.py
View file

@ -102,28 +102,35 @@ class pircbot():
self.log.debug("--- SOCKET OPENING ---") self.log.debug("--- SOCKET OPENING ---")
try: try:
self.socket.connect((self.server, self.port)) self.socket.connect((self.server, self.port))
except socket.error as e: except Exception as e:
self.log.critical("Fehler: %s" % e) self.log.critical("Fehler beim Verbinden: %s", e)
return self.disconnect(send_quit=False)
# start getting data # start getting data
self.recvloop = Thread(target=self.recv, name="recvloop") try:
self.recvloop.start() self.recvloop = Thread(target=self.recv, name="recvloop")
self.recvloop.start()
except Exception as e:
self.log.critical("Fehler beim Starten des Empfangs von Daten vom IRC: %s", e)
self.disconnect(send_quit=False)
# optionally send a server password try:
if self.serverpasswd != "": self.send("PASS %s" % self.serverpasswd) # optionally send a server password
# get a nick if self.serverpasswd != "": self.send("PASS %s" % self.serverpasswd)
self.send("NICK %s" % self.nicknames.pop(0)) # get a nick
# set user data self.send("NICK %s" % self.nicknames.pop(0))
self.send("USER %s 0 * :%s" % (self.ident, self.realname)) # set user data
self.send("USER %s 0 * :%s" % (self.ident, self.realname))
except Exception as e:
self.log.critical("Fehler beim IRC-Handshake: %s", e)
self.disconnect(send_quit=False)
# implements irc command QUIT and (more or less) clean exiting # implements irc command QUIT and (more or less) clean exiting
def disconnect(self, reason="", send_quit=True): def disconnect(self, reason="", send_quit=True):
if send_quit: if send_quit:
try: try: self.send("QUIT :%s" % reason)
self.send("QUIT :%s" % reason) except Exception as e: self.log.critical("Fehler beim Senden der QUIT-Nachricht: %s", e)
sleep(1) sleep(1)
except: pass
self.die_event.set() self.die_event.set()
ctr = 0 ctr = 0
while self.recvloop.is_alive() and self.parseloop.is_alive() and ctr < 15: while self.recvloop.is_alive() and self.parseloop.is_alive() and ctr < 15:
@ -133,7 +140,7 @@ class pircbot():
try: try:
self.socket.shutdown(socket.SHUT_RDWR) self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close() self.socket.close()
except: pass except Exception as e: self.log.warning("Fehler beim Schließen des Sockets: %s", e)
### threaded functions ### ### threaded functions ###
@ -144,16 +151,25 @@ class pircbot():
Loop for reciving data Loop for reciving data
""" """
self.log.debug("--- RECVLOOP STARTING ---") self.log.debug("--- RECVLOOP STARTING ---")
self.parseloop = Thread(target=self.parser, name="parser") try: self.parseloop = Thread(target=self.parser, name="parser")
except Exception as e:
self.log.error("Fehler beim Vorbereiten des Threads zum Parsen von Nachrichten von IRC: %s", e)
p = poll() p = poll()
p.register(self.socket.fileno(), POLLIN) try: p.register(self.socket.fileno(), POLLIN)
except Exception as e:
self.log.critical("Fehler, der eigentlich nie auftreten sollte: %s", e)
while not self.die_event.is_set(): while not self.die_event.is_set():
ap = p.poll(1000) ap = p.poll(1000)
if (self.socket.fileno(), POLLIN) in ap: if (self.socket.fileno(), POLLIN) in ap:
self.recvbuffer.extend(self.socket.recv(1024)) try: self.recvbuffer.extend(self.socket.recv(1024))
except Exception as e:
self.log.critical("Konnte keine Daten vom IRC lesen. Verbindung tot? Fehler: %s", e)
if not self.parseloop.is_alive(): if not self.parseloop.is_alive():
self.parseloop = Thread(target=self.parser, name="parser") try:
self.parseloop.start() self.parseloop = Thread(target=self.parser, name="parser")
self.parseloop.start()
except Exception as e:
self.log.critical("Fehler beim Starten des Threads zum Parsen von Nachrichten vom IRC: %s", e)
self.log.debug("--- RECVLOOP EXITING ---") self.log.debug("--- RECVLOOP EXITING ---")
# loop for parsing incoming data # loop for parsing incoming data
@ -289,7 +305,7 @@ class pircbot():
self.log.debug("< %s" % data) self.log.debug("< %s" % data)
try: self.socket.send(self.encode("".join((data, "\r\n")))) try: self.socket.send(self.encode("".join((data, "\r\n"))))
except Exception as e: except Exception as e:
self.log.critical(e) self.log.critical("Fehler beim Senden von Daten: %s", e)
self.disconnect(send_quit=False) self.disconnect(send_quit=False)
# decides whether to reply to user or to channel # decides whether to reply to user or to channel
@ -348,8 +364,17 @@ class pircbot():
greeting = "".join(("Hi " + origin["nick"] +"!")) greeting = "".join(("Hi " + origin["nick"] +"!"))
return greeting return greeting
# say # say
if command == "say": elif command == "say":
return " ".join(params) return " ".join(params)
# choose
elif command == "choose":
choices = " ".join(params).split(", ")# if numparams>1 else params.split(", ")
if choices[0] == "":
return "Whaddayawant? (Seperated by \", \")"
elif len(choices) == 1:
return "Such a difficult question... I don't know..."
else:
return choice(choices)
# DuckDuckGo, ddg <query> # DuckDuckGo, ddg <query>
elif command in ("duckduckgo", "ddg") and self.duckduckgo_cfg["Active"] == "1": elif command in ("duckduckgo", "ddg") and self.duckduckgo_cfg["Active"] == "1":
@ -426,35 +451,36 @@ class pircbot():
def parseargs(): def parseargs():
import argparse import argparse
p = argparse.ArgumentParser( p = argparse.ArgumentParser(
description = "guess what? i think my desc is still missing!" description = "guess what? i think my desc is still missing!")
)
p.add_argument("action", p.add_argument("action",
default = "help", default = "help",
choices = ["start", "stop", "checkconf"], choices = ["start", "stop", "checkconf"],
help = "What to do?" help = "What to do?")
)
p.add_argument("--loglevel", "-l", p.add_argument("--loglevel", "-l",
choices = ["critical", "error", "warning", "info", "debug"], choices = ["critical", "error", "warning", "info", "debug"],
help = "Verbosity of logging" help = "Verbosity of logging")
)
#p.add_argument("--daemon", "-d", type = bool, choices = [1, 0], default=1, help="Daemonize, Default: 1") #p.add_argument("--daemon", "-d", type = bool, choices = [1, 0], default=1, help="Daemonize, Default: 1")
return p.parse_args() return p.parse_args()
def main(): def main():
# get the logging-module logger
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
global bot global bot
# parse command line and config
args = parseargs() args = parseargs()
cfg = ConfigObj("bot.conf") cfg = ConfigObj("bot.conf")
# set the loglevel
nll = getattr(logging, cfg["Behavior"]["Loglevel"].upper(), None) nll = getattr(logging, cfg["Behavior"]["Loglevel"].upper(), None)
if not isinstance(nll, int): if not isinstance(nll, int): raise ValueError('Invalid log level: %s' % cfg["Behavior"]["Loglevel"])
raise ValueError('Invalid log level: %s' % cfg["Behavior"]["Loglevel"])
if args.loglevel != None: nll = getattr(logging, args.loglevel.upper(), None) if args.loglevel != None: nll = getattr(logging, args.loglevel.upper(), None)
if not isinstance(nll, int): if not isinstance(nll, int):
raise ValueError('Invalid log level: %s' % args.loglevel) raise ValueError('Invalid log level: %s' % args.loglevel)
log.setLevel(nll) log.setLevel(nll)
# do awesome stuff!
if args.action == "start": if args.action == "start":
try: try:
bot = pircbot( bot = pircbot(
@ -491,6 +517,8 @@ def main():
except KeyboardInterrupt: except KeyboardInterrupt:
log.info("Got Ctrl-C, dying now...") log.info("Got Ctrl-C, dying now...")
bot.disconnect("Ouch! Got shot by Ctrl-C, dying now... See you!") bot.disconnect("Ouch! Got shot by Ctrl-C, dying now... See you!")
except Exception as e:
log.exception("Fehler: %s", e)
log.debug("--- MAIN EXITING ---") log.debug("--- MAIN EXITING ---")
elif args.action == "stop": print("nope!") elif args.action == "stop": print("nope!")
elif args.action == "checkconf": elif args.action == "checkconf":