Compare commits
No commits in common. "6f9da6f761bbc26715cfbb3a86a676695c1f3874" and "e91d2948d1342b46e1a04010fc85f786ace09918" have entirely different histories.
6f9da6f761
...
e91d2948d1
70
bot.py
70
bot.py
|
|
@ -8,50 +8,40 @@ import logging
|
||||||
import requests
|
import requests
|
||||||
import schedule
|
import schedule
|
||||||
|
|
||||||
STATUS_URL = "https://isfswiaiopen.wiai.de?json"
|
logging.basicConfig(format='%(levelname)s %(name)s:%(message)s', level=logging.DEBUG)
|
||||||
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__)
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
def parse_time(string):
|
def parse_time(string):
|
||||||
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
|
return datetime.datetime.strptime(string, "%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
def get_status():
|
def get_status():
|
||||||
status = requests.get(STATUS_URL).json()
|
status = requests.get("https://isfswiaiopen.wiai.de?json").json()
|
||||||
status["timestamp"] = parse_time(status['timestamp'])
|
status["timestamp"] = parse_time(status['timestamp'])
|
||||||
return status
|
return status
|
||||||
|
|
||||||
def get_status_text(config, src=get_status):
|
def get_status_text(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):
|
def post(chats, text, token):
|
||||||
url = MESSAGE_URL.format(token=token)
|
url = "https://api.telegram.org/bot{token}/sendMessage".format(token=token)
|
||||||
for chat in chats:
|
for chat in chats:
|
||||||
response = requests.post(url, data={'chat_id': chats[chat], "text": text})
|
response = requests.post(url, data={'chat_id': chats[chat], "text": text})
|
||||||
log.info("post message: %s", response.status_code)
|
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"}):
|
def main(args={"config": "settings.json"}):
|
||||||
log.info("run once")
|
log.info("run once")
|
||||||
config = get_config(args)
|
config = json.load(open(args['config']))
|
||||||
text = get_status_text(config)
|
text = get_status_text()
|
||||||
post(config['groups'], text, config['token'])
|
post(config['groups'], text, config['token'])
|
||||||
post_plot(config)
|
post_plot(config)
|
||||||
|
|
||||||
def loop(args={"config": "settings.json"}):
|
def loop(args={"config": "settings.json"}):
|
||||||
log.info("prepare loop")
|
log.info("prepare loop")
|
||||||
config = get_config(args)
|
config = json.load(open(args['config']))
|
||||||
setup(config)
|
setup(config)
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
|
@ -64,40 +54,29 @@ def do_loop(config):
|
||||||
last_state = None
|
last_state = None
|
||||||
while True:
|
while True:
|
||||||
log.info("enter loop")
|
log.info("enter loop")
|
||||||
changed = 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
|
||||||
if changed:
|
if changed:
|
||||||
last_state = update(new_state)
|
last_state = new_state
|
||||||
|
text = get_status_text(lambda: last_state)
|
||||||
|
post(config["groups"], text, config["token"])
|
||||||
log.info("run pending tasks")
|
log.info("run pending tasks")
|
||||||
schedule.run_pending()
|
schedule.run_pending()
|
||||||
log.info("sleep")
|
log.info("sleep")
|
||||||
time.sleep(config['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):
|
def post_plot(config):
|
||||||
from plot import get_plot
|
from plot import get_plot
|
||||||
with NamedTemporaryFile() as target:
|
with NamedTemporaryFile() as target:
|
||||||
image_url = IMAGE_URL.format(token=config['token'])
|
image_url = 'https://api.telegram.org/bot{token}/sendPhoto'.format(token=config['token'])
|
||||||
photo, last = get_plot(target)
|
files = {'photo': 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']:
|
for chat in config['groups']:
|
||||||
files['photo'].seek(0)
|
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)
|
r = requests.post(image_url, files=files, data=values)
|
||||||
log.info("post photo: %s", r.status_code)
|
log.info("post photo: %s", r.status_code)
|
||||||
|
|
||||||
|
|
@ -108,7 +87,6 @@ if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="DoorStateBot")
|
parser = argparse.ArgumentParser(description="DoorStateBot")
|
||||||
parser.add_argument("--config", "-c", default="settings.json", help="Configuration file")
|
parser.add_argument("--config", "-c", default="settings.json", help="Configuration file")
|
||||||
parser.add_argument("--loop", "-l", action="store_true", help="Loop")
|
parser.add_argument("--loop", "-l", action="store_true", help="Loop")
|
||||||
parser.add_argument("--interval", "-i", help="Interval")
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
if args.loop:
|
if args.loop:
|
||||||
loop(vars(args))
|
loop(vars(args))
|
||||||
|
|
|
||||||
15
plot.py
15
plot.py
|
|
@ -6,6 +6,7 @@ import requests
|
||||||
import matplotlib
|
import matplotlib
|
||||||
matplotlib.use('Agg')
|
matplotlib.use('Agg')
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
import matplotlib.patches as mpatches
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -40,13 +41,15 @@ def plot(raw, target="wiai.png"):
|
||||||
ax.set_yticks(np.arange(7))
|
ax.set_yticks(np.arange(7))
|
||||||
ax.set_yticklabels(DAYS_ABBR)
|
ax.set_yticklabels(DAYS_ABBR)
|
||||||
ax.set_xticks(np.arange(24))
|
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.title("Aggregated opening count FS WIAI")
|
||||||
plt.figtext(0.5, 0.25, "created: " + str(date.today()), 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")
|
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")
|
plt.savefig(target, format="PNG", transparent=True, bbox_inches="tight")
|
||||||
return target, last[0]
|
return target
|
||||||
|
|
||||||
|
|
||||||
def local(target):
|
def local(target):
|
||||||
|
|
@ -56,7 +59,7 @@ def local(target):
|
||||||
|
|
||||||
|
|
||||||
def prod(target):
|
def prod(target):
|
||||||
return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target)
|
plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target)
|
||||||
|
|
||||||
def get_plot(target):
|
def get_plot(target):
|
||||||
return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target)
|
return plot(requests.get('https://isfswiaiopen.wiai.de/log').json(), target=target)
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,5 @@
|
||||||
"WIAIdoorTest": -234502,
|
"WIAIdoorTest": -234502,
|
||||||
"name": -1333,
|
"name": -1333,
|
||||||
"fswiai main": -1001
|
"fswiai main": -1001
|
||||||
},
|
|
||||||
"texts":{
|
|
||||||
"-1": "fs WIAI is undefined ¯\_(ツ)_/¯",
|
|
||||||
"0": "fs WIAI is closed :(",
|
|
||||||
"1": "fs WIAI is open :)"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue