157 lines
5.5 KiB
Python
157 lines
5.5 KiB
Python
|
#!/usr/bin/python3
|
||
|
# -*- coding: utf-8 -*-
|
||
|
|
||
|
import datetime
|
||
|
import json
|
||
|
import sys
|
||
|
import urllib.request
|
||
|
import xml.etree.ElementTree as ET
|
||
|
from time import sleep
|
||
|
from urllib.error import HTTPError
|
||
|
|
||
|
import telepot
|
||
|
from telepot.loop import MessageLoop
|
||
|
|
||
|
from Daemon import Daemon
|
||
|
|
||
|
|
||
|
class Essen:
|
||
|
def __init__(self, name, preis, kategorie):
|
||
|
self.name = name
|
||
|
self.preis = preis
|
||
|
self.kategorie = kategorie
|
||
|
|
||
|
def __str__(self):
|
||
|
return str("%s: *%s* (%.2f €)" % (self.kategorie, self.name, self.preis))
|
||
|
|
||
|
|
||
|
class HSMensaW_daemon(Daemon):
|
||
|
def run(self):
|
||
|
while True:
|
||
|
now = datetime.datetime.today()
|
||
|
nextDay = datetime.datetime(now.year, now.month, now.day) + datetime.timedelta(1, 36000)
|
||
|
print("Sleeping: " + str((nextDay - now).seconds))
|
||
|
sleep((nextDay - now).seconds)
|
||
|
get_essen()
|
||
|
if len(essen) > 0:
|
||
|
for i in ids:
|
||
|
send_essen(i)
|
||
|
sleep(30)
|
||
|
|
||
|
|
||
|
config_filename = "config.json"
|
||
|
monate = ["Januar", "Februar", "März", "April", "Mai", "Juni", "August", "September", "Oktober", "November", "Dezember"]
|
||
|
wochentage = ["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"]
|
||
|
|
||
|
|
||
|
def handle(msg):
|
||
|
global essen
|
||
|
|
||
|
content_type, chat_type, chat_id = telepot.glance(msg)
|
||
|
if content_type == "text":
|
||
|
text = str(msg["text"]).lower()
|
||
|
if msg["text"].startswith("/start"):
|
||
|
ids.append(chat_id)
|
||
|
bot.sendMessage(chat_id, "Bot wurde aktiviert")
|
||
|
with open('config.json', 'w') as outfile:
|
||
|
json.dump(config, outfile)
|
||
|
elif msg["text"].startswith("/stop"):
|
||
|
try:
|
||
|
ids.remove(chat_id)
|
||
|
bot.sendMessage(chat_id, "Bot wurde deaktiviert")
|
||
|
with open('config.json', 'w') as outfile:
|
||
|
json.dump(config, outfile)
|
||
|
except ValueError:
|
||
|
bot.sendMessage(chat_id, "Bot war nicht aktiv")
|
||
|
elif msg["text"].startswith("/essen") or msg["text"].startswith("/mensa") or \
|
||
|
msg["text"].startswith("/speiseplan"):
|
||
|
get_essen()
|
||
|
if len(essen) == 0:
|
||
|
bot.sendMessage(chat_id, "Für heute ist leider kein Speiseplan verfügbar.")
|
||
|
else:
|
||
|
send_essen(chat_id)
|
||
|
elif content_type == "new_chat_member":
|
||
|
if msg["new_chat_participant"]["id"] == bot.getMe()["id"]:
|
||
|
bot.sendMessage(chat_id, "*Mensa-Bot der Hochschule Mittweida*\nDieser Bot versendet jeden Tag um 10 Uhr "
|
||
|
"den aktuellen Mensa-Speiseplan. Er wird über /start für den aktuellen Chat oder "
|
||
|
"die aktuelle Gruppe gestartet, /stop beendet ihn wieder. Mit /essen, /mensa und "
|
||
|
"/speiseplan kann der aktuelle Speiseplan manuell abgerufen werden.\n\n"
|
||
|
"_Haftungsausschluss: Dieser Bot steht in keiner Verbindung mit der Hochschule "
|
||
|
"Mittweida oder dem Studentenwerk Freiberg. Alle Angaben ohne Gewähr._",
|
||
|
"markdown")
|
||
|
elif content_type == "left_chat_member":
|
||
|
if msg["left_chat_participant"]["id"] == bot.getMe()["id"]:
|
||
|
if chat_id in ids:
|
||
|
ids.remove(chat_id)
|
||
|
with open('config.json', 'w') as outfile:
|
||
|
json.dump(config, outfile)
|
||
|
|
||
|
|
||
|
def send_essen(chat_id):
|
||
|
global datum, essen
|
||
|
nachricht = "Speiseplan am WOCHENTAG, den %s:\n" % datum.strftime("%d. MONAT %Y")
|
||
|
nachricht = nachricht.replace("MONAT", monate[datum.month])
|
||
|
nachricht = nachricht.replace("WOCHENTAG", wochentage[datum.weekday()])
|
||
|
for i in essen:
|
||
|
nachricht += str(i).replace(".", ",") + "\n"
|
||
|
bot.sendMessage(chat_id, nachricht, "markdown")
|
||
|
|
||
|
|
||
|
def get_essen():
|
||
|
global datum, essen
|
||
|
essen = []
|
||
|
try:
|
||
|
response = urllib.request.urlopen(url)
|
||
|
except HTTPError:
|
||
|
return
|
||
|
data = response.read()
|
||
|
response.close()
|
||
|
text = data.decode('utf-8')
|
||
|
|
||
|
et = ET.fromstring(text)
|
||
|
date = et.findall("./menus/day/date")[0].text
|
||
|
datum = datetime.date(int(date[:4]), int(date[5:7]), int(date[8:10]))
|
||
|
menus = et.findall("./menus/day/menu")
|
||
|
|
||
|
for i in menus:
|
||
|
kategorie = i.findall("type")[0].text
|
||
|
name = i.findall("description")[0].text.strip("()1234567890, ")
|
||
|
preis = float(i.findall("./prices/price[label='Studenten']/value")[0].text.replace(",", "."))
|
||
|
essen.append(Essen(name, preis, kategorie))
|
||
|
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
try:
|
||
|
with open(config_filename, 'r') as config_file:
|
||
|
config = json.load(config_file)
|
||
|
except FileNotFoundError as e:
|
||
|
print('Error: config file "{}" not found: {}'.format(config_filename, e))
|
||
|
sys.exit(-1)
|
||
|
except ValueError as e:
|
||
|
print('Error: invalid config file "{}": {}'.format(config_filename, e))
|
||
|
sys.exit(-1)
|
||
|
|
||
|
telegram_bot_token = config.get("telegram_bot_token")
|
||
|
url = config.get("url")
|
||
|
ids = config.get("ids")
|
||
|
|
||
|
bot = telepot.Bot(telegram_bot_token)
|
||
|
MessageLoop(bot, handle).run_as_thread()
|
||
|
|
||
|
daemon = HSMensaW_daemon("daemon.pid")
|
||
|
|
||
|
if len(sys.argv) == 2:
|
||
|
if 'start' == sys.argv[1]:
|
||
|
daemon.start()
|
||
|
elif 'stop' == sys.argv[1]:
|
||
|
daemon.stop()
|
||
|
elif 'restart' == sys.argv[1]:
|
||
|
daemon.restart()
|
||
|
else:
|
||
|
print("Unknown command")
|
||
|
sys.exit(2)
|
||
|
sys.exit(0)
|
||
|
else:
|
||
|
print("usage: %s start|stop|restart" % sys.argv[0])
|
||
|
sys.exit(2)
|