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

68
main.py
View file

@ -102,28 +102,35 @@ class pircbot():
self.log.debug("--- SOCKET OPENING ---")
try:
self.socket.connect((self.server, self.port))
except socket.error as e:
self.log.critical("Fehler: %s" % e)
return
except Exception as e:
self.log.critical("Fehler beim Verbinden: %s", e)
self.disconnect(send_quit=False)
# start getting data
try:
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)
try:
# optionally send a server password
if self.serverpasswd != "": self.send("PASS %s" % self.serverpasswd)
# get a nick
self.send("NICK %s" % self.nicknames.pop(0))
# 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
def disconnect(self, reason="", send_quit=True):
if send_quit:
try:
self.send("QUIT :%s" % reason)
try: self.send("QUIT :%s" % reason)
except Exception as e: self.log.critical("Fehler beim Senden der QUIT-Nachricht: %s", e)
sleep(1)
except: pass
self.die_event.set()
ctr = 0
while self.recvloop.is_alive() and self.parseloop.is_alive() and ctr < 15:
@ -133,7 +140,7 @@ class pircbot():
try:
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
except: pass
except Exception as e: self.log.warning("Fehler beim Schließen des Sockets: %s", e)
### threaded functions ###
@ -144,16 +151,25 @@ class pircbot():
Loop for reciving data
"""
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.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():
ap = p.poll(1000)
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():
try:
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 ---")
# loop for parsing incoming data
@ -289,7 +305,7 @@ class pircbot():
self.log.debug("< %s" % data)
try: self.socket.send(self.encode("".join((data, "\r\n"))))
except Exception as e:
self.log.critical(e)
self.log.critical("Fehler beim Senden von Daten: %s", e)
self.disconnect(send_quit=False)
# decides whether to reply to user or to channel
@ -348,8 +364,17 @@ class pircbot():
greeting = "".join(("Hi " + origin["nick"] +"!"))
return greeting
# say
if command == "say":
elif command == "say":
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>
elif command in ("duckduckgo", "ddg") and self.duckduckgo_cfg["Active"] == "1":
@ -426,35 +451,36 @@ class pircbot():
def parseargs():
import argparse
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",
default = "help",
choices = ["start", "stop", "checkconf"],
help = "What to do?"
)
help = "What to do?")
p.add_argument("--loglevel", "-l",
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")
return p.parse_args()
def main():
# get the logging-module logger
log = logging.getLogger(__name__)
global bot
# parse command line and config
args = parseargs()
cfg = ConfigObj("bot.conf")
# set the loglevel
nll = getattr(logging, cfg["Behavior"]["Loglevel"].upper(), None)
if not isinstance(nll, int):
raise ValueError('Invalid log level: %s' % cfg["Behavior"]["Loglevel"])
if not isinstance(nll, int): raise ValueError('Invalid log level: %s' % cfg["Behavior"]["Loglevel"])
if args.loglevel != None: nll = getattr(logging, args.loglevel.upper(), None)
if not isinstance(nll, int):
raise ValueError('Invalid log level: %s' % args.loglevel)
log.setLevel(nll)
# do awesome stuff!
if args.action == "start":
try:
bot = pircbot(
@ -491,6 +517,8 @@ def main():
except KeyboardInterrupt:
log.info("Got Ctrl-C, dying now...")
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 ---")
elif args.action == "stop": print("nope!")
elif args.action == "checkconf":