-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.py
372 lines (300 loc) · 11.6 KB
/
functions.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
"""
Unicam Eat! - Telegram Bot (Core functions file)
Authors: Azzeccagarbugli (f.coppola1998@gmail.com)
Porchetta (clarantonio98@gmail.com)
Da rivedere:
- report_error
- boolean file
"""
from settings import Dirs, MENU_URL
import os
import requests
import filecmp
import time
import datetime
from colorama import Fore
from io import StringIO
import xml.etree.ElementTree as ET
import numpy as np
import qrcode
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from telepot.exception import TelegramError
def server_status():
"""
This function pings the ERSU's server
:returns: bool -- **True Success**, **False Error**.
"""
# Try to ping the server
SITE_URL = "http://www.ersucam.it/"
if requests.head(SITE_URL).status_code == 200:
return True
else:
return False
def get_updated_menu_xml(canteen, day, meal):
"""
Get the updated menu parsing an xml file
"""
request = requests.get(MENU_URL)
# Writing pdf
filename = os.path.dirname(os.path.abspath(__file__)) + '/Temp/menu_data.xml'
with open(filename, 'wb') as f:
f.write(request.content)
per_bene = {
"Lunedì": 0,
"Martedì": 1,
"Mercoledì": 2,
"Giovedì": 3,
"Venerdì": 4,
"Sabato": 5,
"Domenica": 6
}
tree = ET.parse(filename)
root = tree.getroot()
# Getting stuff ready for the query
day_data = (datetime.datetime.today() - datetime.timedelta(days=datetime.datetime.today().weekday()) + datetime.timedelta(days=per_bene[day])).strftime("%Y-%m-%d")
canteen_data = 'MensaCP' if canteen == "Colle Paradiso" else 'MensaDA'
meal_data = "S" if meal == 'Cena' else "N"
courses = [[], [], [], [], [], []]
def append_product(index, product):
"""
Internal function to append products to courses list
"""
# Getting product_name
product_name = product.attrib.get('Descrizione').capitalize()
# Fixing typo error
if index == 5:
if "The" in product_name:
product_name = product_name.replace("The", "Tè")
# Concatenating prices
if product.attrib.get('FlagPrezzo') == 'S':
product_name += " _[{} €]_".format(product.attrib.get('Prezzo')[0:4])
else:
product_name += " _[{} pt]_".format(product.attrib.get('Punti'))
# Appending product
courses[index].append(product_name)
for child in root:
if day_data in child.attrib.get('Data').split('T')[0] and child.attrib.get(canteen_data) == "S" and child.attrib.get('FlagCena') == meal_data:
for product in child:
# Primi
if product.attrib.get('TipoProdotto') == 'P':
append_product(0, product)
# Secondi
if product.attrib.get('TipoProdotto') == 'S':
append_product(1, product)
# Pizza e panini
if product.attrib.get('TipoProdotto') == 'Z':
append_product(2, product)
# Altro
if product.attrib.get('TipoProdotto') == 'A':
append_product(3, product)
# Extra
if product.attrib.get('TipoProdotto') == 'E':
append_product(4, product)
# Bevande
if product.attrib.get('TipoProdotto') == 'B':
append_product(5, product)
if not courses[0] and not courses[1] and not courses[2] and not courses[3] and not courses[4] and not courses[5]:
return "Error"
# Courses names
courses_texts = ["🍝 - *Primi:*\n", "🍖 - *Secondi:*\n", "🍕 - *Pizza/Panini:*\n", "🍰 - *Altro:*\n", "🧀 - *Extra:*\n", "🍺 - *Bevande:*\n"]
msg_menu = "🗓 - *{}* - *{}* - *{}*\n\n".format(canteen, day, meal)
for course_text, course in zip(courses_texts, courses):
msg_menu += course_text
for el in course:
msg_menu += "• " + el + "\n"
msg_menu += "\n"
msg_menu += "_Il menù potrebbe subire variazioni_"
return msg_menu
def create_graph(db, days, graph_name):
"""
Creates a graph that shows the usage of the bot during the past 30 days
:param days: The number of the days that the graph should show.
:type days: int.
:returns: str -- name of the output image of the graph
"""
fig, ax = plt.subplots()
for axis in [ax.xaxis, ax.yaxis]:
axis.set_major_locator(ticker.MaxNLocator(integer=True))
daily_users_data = db.get_daily_users(days)
days = np.arange(0, -days, -1)
plt.plot(days, daily_users_data, marker='o', color='b')
plt.fill_between(days, daily_users_data, 0, color='0.822')
loc = ticker.MultipleLocator(base=3.0)
ax.xaxis.set_major_locator(loc)
plt.xlabel("Giorni del mese")
plt.ylabel("Utilizzo di Unicam Eat")
plt.title("Statistiche di utilizzo")
plt.grid(True)
plt.savefig(graph_name)
plt.clf()
def get_cp_keyboard(user_role=0):
"""
Return the custom markup for the keyboard, based on the day of the week.
:param user_role: The role of the current user.
:type user_role: integer.
:returns: list -- An array containing the tags to be used for the keyboard of Colle Paradiso.
"""
# Get the day
days_week_normal = datetime.datetime.today().weekday()
# Check which day is today and so set the right keyboard
if user_role > 0:
markup_array = [["Lunedì"],
["Martedì", "Mercoledì", "Giovedì"],
["Venerdì", "Sabato", "Domenica"]]
elif days_week_normal == 0:
markup_array = [["Oggi"],
["Martedì", "Mercoledì", "Giovedì"],
["Venerdì", "Sabato", "Domenica"]]
elif days_week_normal == 1:
markup_array = [["Oggi"],
["Mercoledì", "Giovedì", "Venerdì"],
["Sabato", "Domenica"]]
elif days_week_normal == 2:
markup_array = [["Oggi"],
["Giovedì", "Venerdì"],
["Sabato", "Domenica"]]
elif days_week_normal == 3:
markup_array = [["Oggi"],
["Venerdì", "Sabato", "Domenica"]]
elif days_week_normal == 4:
markup_array = [["Oggi"],
["Sabato", "Domenica"]]
elif days_week_normal == 5:
markup_array = [["Oggi"],
["Domenica"]]
elif days_week_normal == 6:
markup_array = [["Oggi"]]
else:
print(Fore.RED + "[COLLEPARADISO KEYBOARD] Nice shit bro :)")
return markup_array
def get_da_keyboard(user_role=0):
"""
Return the custom markup for the keyboard, based on the day of the week.
:param user_role: The role of the current user.
:type user_role: integer.
:returns: list -- An array containing the tags to be used for the keyboard of D'Avack.
"""
# Get the day
days_week_normal = datetime.datetime.today().weekday()
# Check which day is today and so set the right keyboard
if user_role > 0:
markup_array = [["Lunedì"],
["Martedì", "Mercoledì", "Giovedì"]]
elif days_week_normal == 0:
markup_array = [["Oggi"],
["Martedì", "Mercoledì", "Giovedì"]]
elif days_week_normal == 1:
markup_array = [["Oggi"],
["Mercoledì", "Giovedì"]]
elif days_week_normal == 2:
markup_array = [["Oggi"],
["Giovedì"]]
elif days_week_normal == 3:
markup_array = [["Oggi"]]
else:
print(Fore.RED + "[AVACK KEYBOARD] Nice shit bro :)")
return markup_array
def get_launch_dinner_keyboard(canteen, day, user_role=0):
"""
Return the custom markup for the keyboard, based on the lunch or dinner.
:param user_role: The role of the current user.
:type user_role: integer.
:param canteen: Name of the canteen.
:type canteen: str.
:param day: Day of the week.
:type day: str.
:returns: list -- An array containing the tags to be used for the keyboard.
"""
# Lunch or supper based on the choose of the user
if canteen == "Colle Paradiso":
if (day != "Sabato" and day != "Domenica") or user_role > 0:
markup_array = [["Pranzo"],
["Cena"]]
else:
markup_array = [["Pranzo"]]
elif canteen == "D'Avack":
markup_array = [["Pranzo"]]
else:
print(Fore.RED + "[SET KEYBOARD LUNCH/DINNER] Nice shit bro :)")
return markup_array
def delete_files_infolder(folder_dir):
"""
Simply deletes all the file inside a folder.
:param folder_dir: The path of the folder.
:type folder_dir: str.
"""
for the_file in os.listdir(folder_dir):
the_file_path = os.path.join(folder_dir, the_file)
try:
if os.path.isfile(the_file_path):
os.unlink(the_file_path)
except Exception as e:
print(Fore.RED + "[ERROR] Errore nella funzione delete_files_infolder: " + e)
def check_dir_files():
"""
Checks the existance of all the directories and files
"""
if not os.path.exists(Dirs.QRCODE):
print(Fore.CYAN + "[DIRECTORY] I'm creating this folder for the QR Code for you. Stupid human.")
os.makedirs(Dirs.QRCODE)
if not os.path.exists(Dirs.TEMP):
print(Fore.CYAN + "[DIRECTORY] I'm creating this folder for the Temps file for you. Stupid human.")
os.makedirs(Dirs.TEMP)
def generate_qr_code(chat_id, msg, folder_dir, date, canteen, meal):
"""
Generate the QR Code for the selected menu
:param chat_id: A string containing the value of the chat_id.
:type chat_id: str.
:param msg: A string containing the menu of the day.
:type msg: str.
:param folder_dir: A string containing the path of the folder.
:type folder_dir: str.
:param date: The current date.
:type date: str.
:param canteen: The selected canteen.
:type canteen: str.
:param meal: The selected meal.
:type meal: str.
:returns: str -- The path of the QR Code.
"""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=7,
border=4,
)
qr.add_data(str(chat_id) + " - " + date + " - " + canteen + " - " + meal + "\n\n" + msg)
qr.make(fit=True)
filename = folder_dir + str(chat_id) + "_" + "QRCode.png"
img = qr.make_image(fill_color="black", back_color="white")
img.save(filename)
return filename
class OrderCountdown:
def __init__(self, seconds, msg_id, my_bot):
self._original_seconds = seconds
self._current_seconds = seconds
self._msg_id = msg_id
self._my_bot = my_bot
def order_timeout(self):
"""
Reset the message after a determinate number of seconds
:param seconds: The number of the seconds.
:type seconds: int.
:param msg_id: A string containing the previous message.
:type msg_id: str.
"""
while self._current_seconds:
time.sleep(1)
self._current_seconds -= 1
try:
self._my_bot.bot.deleteMessage(self._msg_id)
self._my_bot.sender.sendMessage("_Il comando è stato resettato in maniera automatica_", parse_mode="Markdown", disable_notification=True)
except TelegramError as e:
if e.description == 'Bad Request: message to delete not found':
pass
del self
def reset(self):
self._current_seconds = self._original_seconds