Caught signals that would otherwise be fatal and saveless.
[halbot.git] / safety.py
blobef3277157a1390fbd042c98ddb540fd46beef679
1 import logging, time, traceback
2 logging.getLogger().addHandler(logging.FileHandler("error.log"))
4 class Buffer(object):
5 def __init__(self, prefix=""):
6 self.data = prefix
7 def write(self, unbuffered):
8 self.data += unbuffered
10 def get_timestamp(when=None):
11 if when == None:
12 when = time.time()
13 return time.ctime(when) + " " + time.tzname[time.daylight]
15 def safe_call(func, args):
16 try:
17 func(*args)
18 except Exception, e:
19 if isinstance(e, SystemExit):
20 raise
21 buffer = Buffer("Exception in function %s at %s:\n"
22 % (func.__name__, get_timestamp()))
23 traceback.print_exc(file=buffer)
24 logging.getLogger().error(buffer.data)
25 # Try to report the error interactively.
26 from basic_commands import reply
27 if len(args) >= 2 and type(args[0]) == type(args[1]) == str:
28 try:
29 reply(args[0], args[1], "Ow! Ohh, man, that didn't feel good. " \
30 +"Somebody get FunnyMan, quick!")
31 except Exception:
32 pass
33 elif len(args) and type(args[0]) == str:
34 try:
35 reply('', args[0], "Ow! Ohh, man, that didn't feel good. " \
36 +"Somebody get FunnyMan, quick!", all=True)
37 except Exception:
38 pass
40 def safe(func):
41 return lambda *args: safe_call(func, args)