doorbot_giftgnom/bot.py

88 lines
2.4 KiB
Python

import argparse
import datetime
import json
import time
from tempfile import NamedTemporaryFile
import requests
import schedule
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["timestamp"] = parse_time(status['timestamp'])
return status
def get_status_text(src=get_status):
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)
for chat in chats:
requests.post(url, data={'chat_id': chats[chat], "text": text})
def main(args={"config": "settings.json"}):
text = get_status_text()
config = json.load(open(args['config']))
post(config['groups'], text, config['token'])
post_plot(config)
def loop(args={"config": "settings.json"}):
config = json.load(open(args['config']))
while True:
try:
do_loop(config)
except Exception as e:
print(e, e.args)
time.sleep(config['sleep'])
def do_loop(config):
last_state = None
while True:
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:
last_state = new_state
text = get_status_text(lambda: last_state)
post(config["groups"], text, config["token"])
schedule.run_pending()
time.sleep(config['sleep'])
def post_plot(config):
from plot import get_plot
target= NamedTemporaryFile()
image_url = 'https://api.telegram.org/bot{token}/sendPhoto'.format(token=config['token'])
files = {'photo': get_plot(target)}
for chat in config['groups']:
files['photo'].seek(0)
values = {"chat_id":config['groups'][chat]}
r = requests.post(image_url, files=files, data=values)
print(r)
def setup(config):
#schedule.every(30).seconds.do(lambda: post_plot(config))
#schedule.every().week.do(post_plot)
schedule.every().day.do(lambda: post_plot(config))
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")
args = parser.parse_args()
setup(vars(args))
if args.loop:
loop(vars(args))
else:
main(vars(args))