diff options
| -rw-r--r-- | geldschieberbot.py | 11 | ||||
| -rwxr-xr-x | single_shot.py | 35 | ||||
| -rwxr-xr-x | test.py | 4 |
3 files changed, 26 insertions, 24 deletions
diff --git a/geldschieberbot.py b/geldschieberbot.py index 046d543..ff859f0 100644 --- a/geldschieberbot.py +++ b/geldschieberbot.py @@ -1009,8 +1009,6 @@ class Geldschieberbot: self.dry_run = dry_run # Run without changing the stored state self.record_changes = True # Should changes be recorded - self.load_state() - # Command dispatch table self.cmds = { 'reg': self.register, @@ -1046,8 +1044,13 @@ class Geldschieberbot: 'thanks': self.thanks, } - def __del__(self): - self.save_state() + def __enter__(self): + self.load_state() + return self + + def __exit__(self, exc_type, exc_value, exc_tb): + if not exc_type: + self.save_state() def enable_dry_run(self) -> bool: """Enable dry run""" diff --git a/single_shot.py b/single_shot.py index 41d9849..0c85947 100755 --- a/single_shot.py +++ b/single_shot.py @@ -80,24 +80,23 @@ def main(): if not group_id: die('A group id must be provided') - bot = Geldschieberbot(state_path, group_id, dry_run=args.dry_run) - - # Read cmds from stdin - for line in sys.stdin.read().splitlines(): - try: - envelope = json.loads(line)['envelope'] - except json.JSONDecodeError: - print(datetime.now(), line, "not valid json") - continue - - quote = None - if not args.no_quote: - quote = Quote(timestamp=envelope['timestamp'], - author=envelope['source']) - - send(send_cmd, bot.handle(envelope), quote) - - send(send_cmd, bot.run_scheduled_cmds()) + with Geldschieberbot(state_path, group_id, dry_run=args.dry_run) as bot: + # Read cmds from stdin + for line in sys.stdin.read().splitlines(): + try: + envelope = json.loads(line)['envelope'] + except json.JSONDecodeError: + print(datetime.now(), line, "not valid json") + continue + + quote = None + if not args.no_quote: + quote = Quote(timestamp=envelope['timestamp'], + author=envelope['source']) + + send(send_cmd, bot.handle(envelope), quote) + + send(send_cmd, bot.run_scheduled_cmds()) if __name__ == "__main__": @@ -1417,8 +1417,8 @@ class TestStateLoadStore(unittest.TestCase): def test_init(self): sp = "test/state_3users.json" - bot = Geldschieberbot(sp, DEFAULT_GROUP_ID) - self.assertTrue(compare_state(sp, state=bot.state)) + with Geldschieberbot(sp, DEFAULT_GROUP_ID) as bot: + self.assertTrue(compare_state(sp, state=bot.state)) def test_explicit_load(self): sp = "test/state_3users.json" |
