This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmensabot.py
306 lines (224 loc) · 8.29 KB
/
mensabot.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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import requests
import os
import logging
from argparse import ArgumentParser
import re
from bs4 import BeautifulSoup
from collections import namedtuple
from peewee import SqliteDatabase, IntegerField, Model
import telepot
from telepot.exception import BotWasBlockedError, BotWasKickedError, TelegramError
from time import sleep
from functools import lru_cache
from datetime import datetime, timedelta
import pytz
import schedule
import dateutil.parser
import retrying
from emoji import emojize
from dotenv import load_dotenv
load_dotenv()
log = logging.getLogger('mensabot')
ingredients_re = re.compile(r'[(](\d+[a-z]*,?\s*)+[)]')
price_re = re.compile(r'(\d+),(\d+) €')
comma_re = re.compile(r'(\w[")]?)\s*,(\w)')
URL = 'https://www.stwdo.de/mensa-co/tu-dortmund/hauptmensa/'
TZ = pytz.timezone('Europe/Berlin')
parser = ArgumentParser()
parser.add_argument('--database', default='mensabot_clients.sqlite')
MenuItem = namedtuple(
'MenuItem',
['category', 'description', 'supplies', 'emoticons', 'p_student', 'p_staff', 'p_guest']
)
supplies_emoticons = {
'Mit Schweinefleisch': emojize(':pig:'),
'Mit Rindfleisch': emojize(':cow:'),
'Mit Geflügel': emojize(':rooster:'),
'Mit Fisch bzw. Meeresfrüchten': emojize(':fish:'),
'Ohne Fleisch': emojize(':carrot:'),
'Vegane Speise': emojize(':deciduous_tree:')
}
db = SqliteDatabase(None)
class Client(Model):
chat_id = IntegerField(unique=True)
class Meta:
database = db
class MenuNotFound(Exception):
pass
def find_item(soup, cls):
return soup.find('div', {'class': re.compile('item {}.*'.format(cls))})
@retrying.retry(
stop_max_delay=30000,
wait_fixed=2000,
)
def download_menu_page(day):
log.info('Downloading menu for day {}'.format(day))
ret = requests.get(URL, params={'tx_pamensa_mensa[date]': str(day)})
ret.raise_for_status()
log.info('Done')
return BeautifulSoup(ret.text, 'lxml')
def extract_menu_items(soup):
menu_div = soup.find('div', {'class': 'meals-wrapper'})
if menu_div is None:
raise MenuNotFound
menu_items = menu_div.find_all('div', {'class': 'meal-item'})
return list(map(parse_menu_item, menu_items))
def parse_price(price_div):
m = price_re.search(price_div.text)
euros, cents = map(int, m.groups())
return euros + cents / 100
def parse_menu_item(menu_item):
category_item = find_item(menu_item, 'category').find('img')
if category_item is not None:
category = category_item['title']
else:
category = ''
description = find_item(menu_item, 'description').text.lstrip()
description = ingredients_re.sub('', description)
description = comma_re.sub(r'\1, \2', description)
supplies = [
img.get('title', '')
for img in find_item(menu_item, 'supplies').find_all('img')
]
emoticons = ''.join(supplies_emoticons.get(s, '') for s in supplies)
p_student = parse_price(find_item(menu_item, 'price student'))
p_staff = parse_price(find_item(menu_item, 'price staff'))
p_guest = parse_price(find_item(menu_item, 'price guest'))
return MenuItem(category, description, supplies, emoticons, p_student, p_staff, p_guest)
@lru_cache(maxsize=10)
def get_menu(day):
soup = download_menu_page(day)
items = extract_menu_items(soup)
return items
def format_menu(menu, full=False, date=None):
if full is False:
menu = filter(lambda i: i.category not in ('Grillstation', 'Beilagen'), menu)
title = '*Hauptmensa*'
if date is not None:
title += ' ({:%d.%m.%Y})'.format(date)
last_category = ''
items = []
for item in menu:
category = item.category or last_category
last_category = item.category
items.append(
'*{category}* - {item.emoticons}\n{item.description}'.format(
category=category, item=item
)
)
return title + '\n\n' + '\n\n'.join(items)
def build_menu_reply(text):
full = text.startswith('/fullmenu')
try:
datestring = text.split()[1]
dt = dateutil.parser.parse(datestring)
except (ValueError, IndexError):
dt = datetime.now(TZ)
if dt.hour >= 15:
dt += timedelta(days=1)
day = dt.date()
if day.weekday() >= 5:
return 'Am Wochenende bleibt die Mensaküche kalt'
try:
menu = get_menu(day)
except Exception:
log.error('Error getting menu')
return 'Fehler beim herunterladen von Tag {}'.format(day)
try:
return format_menu(menu, full=full, date=dt)
except Exception:
log.exception('Error formatting menu')
return 'Fehler beim formatieren von Tag {}'.format(day)
def create_message(day):
try:
menu = get_menu(day)
except Exception:
log.error('Error getting menu')
return 'Fehler beim herunterladen des Menüs für {}'.format(day)
if len(menu) == 0:
log.error('Empty menu {}'.format(menu))
return 'Leeres Menü für {}'.format(day)
try:
return format_menu(menu, date=day)
except Exception as e:
logging.exception('Error formatting menu')
return 'Fehler beim formatieren des Menüs für {}'.format(day)
class MensaBot(telepot.Bot):
def handle(self, msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if chat_type == 'private':
start = 'Du bekommst '
else:
start = 'Ihr bekommt '
if content_type != 'text':
return
text = msg['text']
if text.startswith('/start'):
client, new = Client.get_or_create(chat_id=chat_id)
if new:
reply = start + 'ab jetzt jeden Tag um 11 das Menü'
else:
reply = start + 'das Menü schon!'
elif text.startswith('/stop'):
try:
client = Client.get(chat_id=chat_id)
client.delete_instance()
reply = start + 'das Menü ab jetzt nicht mehr'
except Client.DoesNotExist:
reply = start + 'das Menü doch gar nicht'
elif text.startswith('/menu') or text.startswith('/fullmenu'):
reply = build_menu_reply(text)
else:
reply = 'Das habe ich nicht verstanden'
log.info('Sending message to {}'.format(chat_id))
self.sendMessage(chat_id, reply, parse_mode='markdown')
def send_menu_to_clients(self):
day = datetime.now(TZ).date()
if day.weekday() >= 5:
return
text = create_message(day)
for client in Client.select():
log.info('Sending menu to {}'.format(client.chat_id))
try:
self.sendMessage(client.chat_id, text, parse_mode='markdown')
except (BotWasBlockedError, BotWasKickedError):
log.warning('Removing client {}'.format(client.chat_id))
client.delete_instance()
except TelegramError as e:
if e.error_code == 403:
log.warning('Removing client {}'.format(client.chat_id))
client.delete_instance()
except Exception as e:
logging.exception('Error sending message to client {}'.format(client.chat_id))
def main():
args = parser.parse_args()
log.setLevel(logging.DEBUG)
formatter = logging.Formatter(
fmt='%(asctime)s|%(levelname)s|%(name)s|%(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
log.addHandler(stream_handler)
file_handler = logging.FileHandler('mensabot.log')
file_handler.setFormatter(formatter)
log.addHandler(file_handler)
db.init(args.database)
Client.create_table(safe=True)
log.info("Using database {}".format(os.path.abspath(args.database)))
log.info("Database contains {} active clients".format(Client.select().count()))
bot = MensaBot(os.environ['BOT_TOKEN'])
bot.message_loop()
log.info('Bot runnning')
schedule.every().day.at('11:00').do(bot.send_menu_to_clients)
while True:
try:
schedule.run_pending()
except:
log.exception('Exception during schedule execution')
sleep(1)
if __name__ == '__main__':
try:
main()
except (KeyboardInterrupt, SystemExit):
log.info('Aborted')