From 4d29570a2de26ad181431e8e0f6514f1ccc3fc37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Ml=C3=A1dek?= Date: Wed, 26 May 2021 20:35:37 +0200 Subject: [PATCH] replace pickle with json --- bot.py | 28 +++++++++++----------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/bot.py b/bot.py index 94c9044..f08e3a4 100644 --- a/bot.py +++ b/bot.py @@ -1,7 +1,7 @@ import asyncio import logging import os -import pickle +import json import re import textwrap from asyncio import sleep @@ -17,13 +17,7 @@ config.WEBHOOK_URL = os.getenv("WEBHOOK_URL", config.WEBHOOK_URL) config.TG_CHAT_ID = os.getenv("TG_CHAT_ID", config.TG_CHAT_ID) config.TG_API_KEY = os.getenv("TG_API_KEY", config.TG_API_KEY) -STATE_PATH = os.getenv("STATE_PATH", "state.pickle") - - -class State: - def __init__(self) -> None: - self.notified = [] - self.notified_soon = [] +STATE_PATH = os.getenv("STATE_PATH", "state.json") def process_event(event, template): @@ -100,10 +94,10 @@ def get_event_id(event: Event) -> str: async def main(): try: - with open(STATE_PATH, "rb") as state_fp: - state = pickle.load(state_fp) + with open(STATE_PATH, "r") as state_fp: + state = json.load(state_fp) except FileNotFoundError: - state = State() + state = {"notified": [], "notified_soon": []} while True: calendars = [] @@ -123,23 +117,23 @@ async def main(): for event in future_events: if ( - get_event_id(event) not in state.notified + get_event_id(event) not in state["notified"] and event.begin.shift(days=-2) < arrow.now() ): logging.info(f"Sending description of {event.name}") await send_message(process_event(event, config.EVENT_TEMPLATE)) - state.notified.append(get_event_id(event)) + state["notified"].append(get_event_id(event)) if ( - get_event_id(event) not in state.notified_soon + get_event_id(event) not in state["notified_soon"] and event.begin.shift(hours=-2) < arrow.now() ): logging.info(f"Notifying of {event.name}") await send_message(process_event(event, config.SOON_TEMPLATE)) - state.notified_soon.append(get_event_id(event)) + state["notified_soon"].append(get_event_id(event)) - with open(STATE_PATH, "wb") as state_fp: - pickle.dump(state, state_fp) + with open(STATE_PATH, "w") as state_fp: + json.dump(state, state_fp) logging.debug("Sleeping for 60s...") await sleep(60)