diff --git a/bot.py b/bot.py index 107525a..2918bf9 100644 --- a/bot.py +++ b/bot.py @@ -8,41 +8,50 @@ import logging import requests import schedule -logging.basicConfig(format='%(levelname)s %(name)s:%(message)s', level=logging.DEBUG) +STATUS_URL = "https://isfswiaiopen.wiai.de?json" +MESSAGE_URL = "https://api.telegram.org/bot{token}/sendMessage" +IMAGE_URL = "https://api.telegram.org/bot{token}/sendPhoto" + +logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s:%(message)s', level=logging.DEBUG, datefmt="%Y.%m.%d %H:%M:%S") log = logging.getLogger(__name__) def parse_time(string): return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S") def get_status(): - status = requests.get("https://isfswiaiopen.wiai.de?json").json() + status = requests.get(STATUS_URL).json() status["timestamp"] = parse_time(status['timestamp']) return status def get_status_text(config, src=get_status): return config["texts"][str(get_status()["doorstate"])] - if get_status()["doorstate"]: - text = "fs WIAI is open :)" - else: - text = "fs WIAI is closed :(" - return text def post(chats, text, token): - url = "https://api.telegram.org/bot{token}/sendMessage".format(token=token) + url = MESSAGE_URL.format(token=token) for chat in chats: response = requests.post(url, data={'chat_id': chats[chat], "text": text}) log.info("post message: %s", response.status_code) +def has_argument(args, key): + return key in args and args[key] + +def get_config(args): + config = json.load(open(args['config'])) + if has_argument(args, "interval"): + log.info("Overwrite sleep value by argument…") + config["sleep"] = args["interval"] + return config + def main(args={"config": "settings.json"}): log.info("run once") - config = json.load(open(args['config'])) + config = get_config(args) text = get_status_text(config) post(config['groups'], text, config['token']) #post_plot(config) def loop(args={"config": "settings.json"}): log.info("prepare loop") - config = json.load(open(args['config'])) + config = get_config(args) setup(config) while True: try: @@ -55,29 +64,40 @@ def do_loop(config): last_state = None while True: log.info("enter loop") - changed = False - new_state = get_status() - if last_state is None: - changed = True - elif not last_state["doorstate"] == new_state["doorstate"]: - changed = True + changed = has_changed(last_state) if changed: - last_state = new_state - text = get_status_text(config, lambda: last_state) - post(config["groups"], text, config["token"]) + last_state = update(new_state) log.info("run pending tasks") schedule.run_pending() log.info("sleep") time.sleep(config['sleep']) +def has_changed(last_state): + changed = False + new_state = get_status() + if last_state is None: + changed = True + elif not last_state["doorstate"] == new_state["doorstate"]: + changed = True + return changed + +def update(state): + text = get_status_text(config, lambda: state) + post(config["groups"], text, config["token"]) + return state + def post_plot(config): from plot import get_plot with NamedTemporaryFile() as target: - image_url = 'https://api.telegram.org/bot{token}/sendPhoto'.format(token=config['token']) - files = {'photo': get_plot(target)} + image_url = IMAGE_URL.format(token=config['token']) + photo, last = get_plot(target) + files = {'photo': photo} + if last + datetime.timedelta(days=1) < datetime.datetime.today(): + log.info("skipping image, no new updates...") + return for chat in config['groups']: files['photo'].seek(0) - values = {"chat_id":config['groups'][chat]} + values = {"chat_id": config['groups'][chat]} r = requests.post(image_url, files=files, data=values) log.info("post photo: %s", r.status_code) @@ -88,6 +108,7 @@ if __name__ == "__main__": parser = argparse.ArgumentParser(description="DoorStateBot") parser.add_argument("--config", "-c", default="settings.json", help="Configuration file") parser.add_argument("--loop", "-l", action="store_true", help="Loop") + parser.add_argument("--interval", "-i", help="Interval") args = parser.parse_args() if args.loop: loop(vars(args)) diff --git a/plot.py b/plot.py index a436471..ee458cd 100644 --- a/plot.py +++ b/plot.py @@ -6,7 +6,6 @@ import requests import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt -import matplotlib.patches as mpatches import numpy as np @@ -41,15 +40,13 @@ def plot(raw, target="wiai.png"): ax.set_yticks(np.arange(7)) ax.set_yticklabels(DAYS_ABBR) ax.set_xticks(np.arange(24)) - - colors = [ im.cmap(im.norm(value)) for value in values ] - patches = [ mpatches.Patch(color=colors[i], label=str(values[i])) for i in range(len(values))] - plt.legend(handles=patches, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.title("Aggregated opening count FS WIAI") - plt.figtext(0.5, 0.25, "created: "+str(date.today()), ha="center") - plt.figtext(0.5, 0.2, str(first[0])+" → "+str(last[0]), ha="center") + plt.figtext(0.5, 0.25, "created: " + str(date.today()), ha="center") + plt.figtext(0.5, 0.2, str(first[0]) + " → " + str(last[0]), ha="center") + cax = plt.axes((0.95, 0.15, 0.05, 0.5)) + plt.colorbar(im, cax=cax) plt.savefig(target, format="PNG", transparent=True, bbox_inches="tight") - return target + return target, last[0] def local(target): @@ -59,7 +56,7 @@ def local(target): def prod(target): - plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target) + return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target) def get_plot(target): return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target)