-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
166 lines (139 loc) · 5.76 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
#!/usr/bin/env python3
# Copyright 2020 by Michael Thies <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
Zulip bot for sending Mensa Academica Aachen's menu to the PLT Zulip chat every workday at 11:25.
"""
import configparser
import datetime
import logging
from typing import Iterable
import time
import os.path
import pytz
import zulip
import mensa_aachen
__author__ = "Michael Thies <[email protected]>"
__version__ = "1.0"
INFO_TIME = datetime.time(11, 25, 00, tzinfo=pytz.timezone('Europe/Berlin'))
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def main_loop():
logger.info("Initializing client ...")
config_file = os.path.join(os.path.dirname(__file__), "config.ini")
config = configparser.ConfigParser()
config.read(config_file)
zulip_client = zulip.Client(config_file=config_file)
stream_name = config['message']['stream']
logger.info("Starting into main loop ...")
while True:
try:
# Calculate time until message and sleep
sleep_time = calculate_sleep_time()
logger.info("Scheduling next message for {}.".format(sleep_time))
logarithmic_sleep(sleep_time)
# Send messages
send_menu(zulip_client, stream_name)
# Prevent fast retriggering
time.sleep(1)
except KeyboardInterrupt:
logger.info("Received KeyobardInterrupt. Exiting …")
return
except Exception as e:
logger.error("Exception in main loop:", exc_info=e)
def calculate_sleep_time() -> datetime.datetime:
now = datetime.datetime.now(tz=INFO_TIME.tzinfo)
res = now.replace(hour=INFO_TIME.hour, minute=INFO_TIME.minute, second=INFO_TIME.second,
microsecond=INFO_TIME.microsecond)
if res <= now:
res += datetime.timedelta(days=1)
# Skip the weekend
if res.weekday() >= 5:
res += datetime.timedelta(days=7 - res.weekday())
return res
def logarithmic_sleep(target: datetime.datetime):
while True:
diff = (target - datetime.datetime.now(tz=datetime.timezone.utc)).total_seconds()
if diff < 0.2:
time.sleep(diff)
return
else:
time.sleep(diff/2)
def send_menu(client: zulip.Client, stream: str):
logger.info("Fetching menu data ...")
try:
menu_data = mensa_aachen.get_dishes(mensa_aachen.Canteens.MENSA_ACADEMICA)
menu = menu_data[datetime.date.today()]
except Exception as e:
logger.error("Error while fetching canteen menu:", exc_info=e)
return
logger.info("Fetching menu data finished.")
filtered_dishes = [dish for dish in menu.main_dishes
if dish.menu_category not in ("Pizza Classics", "Burger Classics", "Fingerfood",
"Ofenkartoffel")]
formatted_menu = (
"# Speiseplan Mensa Academica {:%d.%m.%Y}\n\n"
"| | Gericht | Fleisch |\n|---|---|---|\n".format(datetime.date.today())
+ "\n".join(
"| **{}** | {}{} | {} |".format(
dish.menu_category,
dish.main_component.title,
" 〈{}〉".format(" • ".join(c.title for c in dish.aux_components)) if dish.aux_components else "",
meat_emojis(dish.meat))
for dish in filtered_dishes)
+ "\n\n Dazu:\n\n* {}, sowie\n* {}".format(
" oder ".join(dish.main_component.title
for dish in menu.side_dishes
if dish.menu_category == "Hauptbeilagen"),
" oder ".join(dish.main_component.title for
dish in menu.side_dishes
if dish.menu_category == "Nebenbeilage"))
)
subject = "Mensa Speiseplan {:%d.%m.%Y}".format(datetime.date.today())
logger.info("Sending messages ...")
client.send_message({
"type": "stream",
"to": [stream],
"subject": subject,
"content": formatted_menu,
})
client.send_message({
"type": "stream",
"to": [stream],
"subject": subject,
"content": "@all Wer kommt mit essen? Bitte mit 👍 oder 👎 reagieren.",
})
logger.info("Sending messages finished.")
MEAT_ICONS = {
mensa_aachen.MeatType.RIND: "🐂",
mensa_aachen.MeatType.SCHWEIN: "🐖",
mensa_aachen.MeatType.GEFLUEGEL: "🐔",
mensa_aachen.MeatType.VEGETARIAN: "🧀",
mensa_aachen.MeatType.VEGAN: "🥦",
mensa_aachen.MeatType.FISCH: "🐟",
}
def meat_emojis(meat: Iterable[mensa_aachen.MeatType]) -> str:
meat = set(meat)
if mensa_aachen.MeatType.VEGAN in meat:
meat.discard(mensa_aachen.MeatType.VEGETARIAN)
return " ".join(MEAT_ICONS[m] for m in meat)
if __name__ == "__main__":
main_loop()