bot: drastically catch exceptions

For whatever reason systemd stop signals are not caught anymore by the
"except KeyboardInterrupt", so the storage file is lost on what should
be a graceful shutdown.
master
dece 2 years ago
parent 0a304f9b6c
commit bec9ff4d76

@ -2,6 +2,7 @@ import importlib
import json
import os
import time
import signal
from pathlib import Path
import irc.client
@ -21,6 +22,7 @@ class Bot(irc.client.SimpleIRCClient, Logger):
self.plugins = []
self.values = {}
self.storage = self.__get_storage()
self.done = False
@property
def nick(self):
@ -111,13 +113,15 @@ class Bot(irc.client.SimpleIRCClient, Logger):
self.load_plugins()
self.log_i("Connecting to server.")
self.connect(self.config["host"], self.config["port"], self.nick)
signal.signal(signal.SIGTERM, self.handle_sigterm)
try:
self.start()
except KeyboardInterrupt:
self.log_i("Caught keyboard interrupt.")
except: # Yes, I know, who are you going to call?
self.log_i("Caught unhandled exception.")
finally:
self.log_i("Stopping Edmond.")
self.__save_storage()
self.cleanup()
def load_plugins(self):
"""Load all installed plugins."""
@ -171,3 +175,17 @@ class Bot(irc.client.SimpleIRCClient, Logger):
continue
if callbacks[etype](event):
break
def handle_sigterm(self, *args):
"""Handle SIGTERM (keyboard interrupt, systemd stop, etc)."""
self.cleanup()
def cleanup(self):
"""Save the storage file and close the connection. Run only once."""
if self.done:
return
self.log_i("Stopping Edmond.")
self.__save_storage()
if self.connection.is_connected():
self.connection.close()
self.done = True

Loading…
Cancel
Save