-
Notifications
You must be signed in to change notification settings - Fork 4
/
weeelab_bot.py
2118 lines (1853 loc) · 85.4 KB
/
weeelab_bot.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding:utf-8
"""
WEEELAB_BOT - Telegram bot.
Author: WEEE Open Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import datetime
# Modules
import json
import os
import random
import time
import traceback # Print stack traces in logs
from datetime import timedelta
from enum import Enum
from json import JSONDecodeError
from subprocess import PIPE, run
from threading import Thread
from time import sleep
from typing import List, Optional
# from requests_html import HTMLSession
# noinspection PyUnresolvedReferences
import owncloud
import requests # send HTTP requests to Telegram server
import simpleaudio
from pytarallo.AuditEntry import AuditChanges, AuditEntry
from pytarallo.Errors import AuthenticationError, ItemNotFoundError
from pytarallo.Tarallo import Tarallo
from LdapWrapper import AccountLockedError, AccountNotFoundError, DuplicateEntryError, LdapConnection, LdapConnectionError, People, Person, User, Users
from Quotes import Quotes
from remote_commands import shutdown_command, ssh_i_am_door_command, ssh_weeelab_command
from ssh_util import SSHUtil
from stream_yt_audio import LofiVlcPlayer
from ToLab import ToLab, Tolab_Calendar
from variables import * # internal library with the environment variables
from Weeelablib import WeeelabLogs
from Wol import Wol
class BotHandler:
"""
class with method used by the bot, for more details see https://core.telegram.org/bots/api
"""
def __init__(self, token):
"""
init function to set bot token and reference url
"""
print("Bot handler started")
self.token = token
self.api_url = "https://api.telegram.org/bot{}/".format(token)
self.offset = None
# These are returned when a user sends an unknown command.
self.unknown_command_messages_last = -1
self.unknown_command_messages = [
"Sorry, I didn't understand that.\nWanna try /history? That one I do understand",
"Sorry, I didn't understand that.\nWanna try /tolab? That one I do understand",
"I don't know that command, but do you know /history? It's pretty cool",
"I don't know that command, but do you know /tolab? It's pretty cool",
"What? I don't understand :(\nBut I do understand /history",
"What? I don't understand :(\nBut I do understand /tolab",
"Unknown command. But do you know /history? It's pretty cool",
"Unknown command. But do you know /tolab? It's pretty cool",
"Bad command or file name.\nDo you know what's good? /history",
"Bad command or file name.\nDo you know what's good? /tolab",
]
self.game_questions_last = -1
self.game_questions = [
"Who said this?",
"Guess the author",
"Guess the author!",
"Who wants to be a millionaire?",
"Who's the author?",
"Who said this magnificent quote?",
"Who said this memorable quote?",
"Who said this famous quote?",
"Who said this one?",
"Who said this?",
"Who said it?",
"Who said it first?",
"Who said this first?",
"Who's the author of this memorable quote?",
"Guess the disagio",
"Ah, this famous quote - who said it?",
"Do you know this one?",
"Do you know who said this one?",
]
self.active_sessions = []
def get_updates(self, timeout=120):
"""
method to receive incoming updates using long polling
[Telegram API -> getUpdates ]
"""
params = {"offset": self.offset, "timeout": timeout}
requests_timeout = timeout + 5
# noinspection PyBroadException
try:
result = requests.get(self.api_url + "getUpdates", params, timeout=requests_timeout).json()["result"]
if len(result) > 0:
self.offset = result[-1]["update_id"] + 1
return result
except requests.exceptions.Timeout:
print(f"Polling timed out after f{str(requests_timeout)} seconds")
return None
except Exception as e:
print("Failed to get updates: " + str(e))
return None
def send_message(
self,
chat_id,
text,
parse_mode="HTML",
disable_notification: bool = False,
disable_web_page_preview: bool = True,
reply_markup=None,
):
"""
method to send text messages [ Telegram API -> sendMessage ]
On success, the sent Message is returned.
"""
params = {
"chat_id": chat_id,
"text": text,
"parse_mode": parse_mode,
"disable_web_page_preview": disable_web_page_preview,
"disable_notification": disable_notification,
}
if reply_markup is not None:
params["reply_markup"] = {"inline_keyboard": reply_markup}
self.__do_post("sendMessage", params)
def send_photo(
self,
chat_id,
photo,
caption: str = None,
parse_mode: str = "HTML",
disable_notification: bool = False,
reply_markup=None,
):
"""
method to send photos [ Telegram API -> sendPhoto ]
On success, the sent Message is returned.
"""
params = {
"chat_id": chat_id,
"photo": photo,
"caption": caption,
"parse_mode": parse_mode,
"disable_notification": disable_notification,
"reply_markup": reply_markup,
}
if reply_markup is not None:
params["reply_markup"] = {"inline_keyboard": reply_markup}
self.__do_post("sendPhoto", params)
def edit_message(
self,
chat_id: int,
message_id: int,
text: Optional[str] = None,
reply_markup=None,
parse_mode="HTML",
disable_web_page_preview=True,
):
params = {
"chat_id": chat_id,
"message_id": message_id,
}
if text is not None:
params["text"] = text
params["parse_mode"] = parse_mode
params["disable_web_page_preview"] = disable_web_page_preview
if reply_markup is not None:
params["reply_markup"] = {"inline_keyboard": reply_markup}
self.__do_post("editMessageText", params)
def __do_post(self, endpoint, params):
result = requests.post(self.api_url + endpoint, json=params)
if result.status_code >= 400:
print(f"Telegram server says there's an error: {result.status_code}")
print(result.content)
print("Our message:")
print(json.dumps(params))
def get_last_update(self):
"""
method to get last message if there is.
in case of error return an error code used in the main function
"""
get_result = self.get_updates(120) # recall the function to get updates
if not get_result:
return -1
elif len(get_result) > 0: # check if there are new messages
return get_result[-1] # return the last message in json format
else:
return -1
def leave_chat(self, chat_id):
"""
method to send text messages [ Telegram API -> leaveChat ]
On success, the leave Chat returns True.
"""
params = {
"chat_id": chat_id,
}
return requests.post(self.api_url + "leaveChat", params)
@property
def unknown_command_message(self):
self.unknown_command_messages_last += 1
self.unknown_command_messages_last %= len(self.unknown_command_messages)
return self.unknown_command_messages[self.unknown_command_messages_last]
@property
def game_question(self):
self.game_questions_last += 1
self.game_questions_last %= len(self.game_questions)
return self.game_questions[self.game_questions_last]
def escape_all(string):
return string.replace("&", "&").replace("<", "<").replace(">", ">")
class AcceptableQueriesLoFi(Enum):
play = "lofi_play"
pause = "lofi_pause"
close = "lofi_close"
volume_plus = "lofi_vol+"
volume_down = "lofi_vol-"
class AcceptableQueriesShutdown(Enum):
weeelab_yes = "weeelab_yes"
weeelab_no = "weeelab_no"
i_am_door_yes = "i_am_door_yes"
i_am_door_no = "i_am_door_no"
class Machines(Enum):
scma = "scma"
piall = "piall"
def inline_keyboard_button(label: str, callback_data: str):
return {"text": label, "callback_data": callback_data}
def calculate_time_to_sleep(hour: int, minute: int = 0) -> int:
"""
Calculate time to sleep to perform an action at a given hour and minute
by e-caste
"""
# hour is before given hour -> wait until today at given hour and minute
if int(datetime.datetime.now().time().strftime("%k")) < hour:
time_to_sleep = int((datetime.datetime.today().replace(hour=hour, minute=minute, second=0) - datetime.datetime.now()).total_seconds())
# hour is equal to given hour
elif int(datetime.datetime.now().time().strftime("%k")) == hour:
# minute is before given minute -> wait until today at given time
if int(datetime.datetime.now().time().strftime("%M")) < minute:
time_to_sleep = int((datetime.datetime.today().replace(hour=hour, minute=minute, second=0) - datetime.datetime.now()).total_seconds())
# minute is after given minute -> wait until tomorrow at given time
else:
time_to_sleep = int(
(datetime.datetime.today().replace(hour=hour, minute=minute, second=0) + timedelta(days=1) - datetime.datetime.now()).total_seconds()
)
# hour is after given hour -> wait until tomorrow at given time
else:
time_to_sleep = int(
(datetime.datetime.today().replace(hour=hour, minute=minute, second=0) + timedelta(days=1) - datetime.datetime.now()).total_seconds()
)
return time_to_sleep
def human_readable_number(num: int) -> str:
"""
e.g. human_readable_number(14832675) is 14,832,675
:param num: a big number
:return: a comma separated number string
"""
return "{:,}".format(num)
def fah_ranker(bot: BotHandler, hour: int, minute: int):
while True:
try:
# first sleep until 5am
sleep(calculate_time_to_sleep(hour=5, minute=0))
# then sleep until the given hour which is now computed correctly even in case of hour change
sleep(calculate_time_to_sleep(hour, minute))
team_number = 249208
url = f"https://api.foldingathome.org/team/{team_number}/members"
url_team_info = f"https://api.foldingathome.org/team/{team_number}"
url_total_team_count = "https://api.foldingathome.org/team/count"
for _ in range(10):
res = requests.get(url)
json_res = res.json()
res_info = requests.get(url_team_info)
json_res_info = res_info.json()
res_count = requests.get(url_total_team_count)
json_res_count = res_count.json()
if any(
str(sc).startswith("4")
for sc in (
res.status_code,
res_info.status_code,
res_count.status_code,
)
) or any("error" in j for j in (json_res, json_res_info)):
sleep(1)
continue
else:
break
else:
continue
json_fields = dict(zip(json_res[0], range(0, len(json_res))))
del json_res[0]
def _fah_get(json_list, name: str):
pos = json_fields.get(name, -1)
if pos < 0:
return None
if pos >= len(json_list):
return None
return json_list[pos]
last = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
# save data to JSON
json_history = "fah_history.json"
json_history_content = {}
new_file = False
daily = False
try:
try:
with open(json_history, "r") as inf:
daily = True
json_history_content = json.load(inf)
previous_snapshot_key = max(k for k, v in json_history_content.items())
donors_previous_score = {_fah_get(donor, "name"): _fah_get(donor, "score") for donor in json_res}
# associate daily increase to each name
donors_daily_score = {name: donors_previous_score[name] - score for name, score in json_history_content[previous_snapshot_key].items()}
# sort by top score first
top_3_donors_by_daily_score = {
k: v
for k, v in sorted(
donors_daily_score.items(),
key=lambda item: item[1],
reverse=True,
)[:3]
}
top_3 = "\n".join(
[
f"<code>#{i+1}</code> <b>{name}</b> with " f"<i>{human_readable_number(score)}</i> points"
for i, (name, score) in enumerate(top_3_donors_by_daily_score.items())
if score > 0
]
)
except FileNotFoundError:
# create file if it doesn't exist
new_file = True
# insert new snapshot in JSON
json_history_content[last] = {_fah_get(donor, "name"): _fah_get(donor, "score") for donor in json_res}
with open(json_history, "w") as outf:
json.dump(json_history_content, outf)
except TypeError as te:
print(te)
except JSONDecodeError as jde:
print(jde)
top_10 = []
for i, member in enumerate(json_res[:10]):
this_top_10 = f"<code>#{i+1}</code> <b>{_fah_get(member, 'name')}</b> with "
this_top_10 += f"<i>{human_readable_number(_fah_get(member, 'score'))}</i> points"
this_top_10 += f", <i>{_fah_get(member, 'wus')}</i> WUs"
if _fah_get(member, "rank") is not None:
this_top_10 += f", rank <i>{human_readable_number(_fah_get(member, 'rank'))}</i>"
top_10.append(this_top_10)
top_10 = "\n".join(top_10)
total_credit = 0
total_wus = 0
for member in json_res:
total_credit += _fah_get(member, "score")
total_wus += _fah_get(member, "wus")
delta = ""
if daily:
delta = f"Daily increase: <b>{human_readable_number(sum(donors_daily_score.values()))}</b>\n" if not new_file else ""
top_3_daily = ""
if not new_file:
top_3_daily = f"Daily MVPs:\n{top_3}\n\n" if top_3 else "No MVPs today since the score has not increased.\n\n"
text = (
f"Total Team Score: <b>{human_readable_number(total_credit)}</b>\n"
f"Total Team Work Units: <b>{human_readable_number(total_wus)}</b>\n"
f"Team Rank: {human_readable_number(json_res_info['rank'])} "
f"/ {human_readable_number(json_res_count)} "
f"-> top <b>{round(json_res_info['rank']/json_res_count*100, 2)}%</b>\n"
f"Last update: {last}\n\n"
f"{delta}"
f"{top_3_daily}"
f"Top members:\n{top_10}\n\n"
f'See all the stats <a href="https://stats.foldingathome.org/team/{team_number}">here</a>'
)
bot.send_message(chat_id=WEEE_FOLD_ID, text=text, disable_notification=True)
except Exception as e: # TODO: specify any expected Exception class
print(e)
# def fah_grapher(bot: BotHandler, hour: int, minute: int):
# while True:
# try:
# sleep(calculate_time_to_sleep(hour, minute))
#
# team_number = 249208
# s = HTMLSession()
# url = f"https://folding.extremeoverclocking.com/graphs/production_day_total.php?s=&t={team_number}"
#
# img_enc_png = s.get(url).content
# bot.send_photo(chat_id=WEEE_FOLD_ID,
# photo=img_enc_png)
#
# except Exception as e:
# print(e)
def run_shell_cmd(cmd: str) -> str:
cmd = cmd.strip().replace(" ", " ").split(" ") # is now a list of strings
return run(cmd, stdout=PIPE).stdout.decode("utf-8")
class CommandHandler:
"""
Aggregates all the possible commands within one class.
"""
def __init__(
self,
bot: BotHandler,
tarallo: Tarallo,
logs: WeeelabLogs,
tolab: ToLab,
users: Users,
people: People,
conn: LdapConnection,
wol: dict,
quotes: Quotes,
):
self.bot = bot
self.tarallo = tarallo
self.logs = logs
self.quotes = quotes
self.tolab_db = tolab
self.users = users
self.people = people
self.conn = conn
self.wol_dict = wol
self.user: Optional[User] = None
self.__last_from = None
self.__last_chat_id = None
self.__last_user_id = None
self.__last_user_nickname = None
self.lofi_player = LofiVlcPlayer()
self.lofi_player_last_volume = -1
def read_user_from_callback(self, last_update):
self.__last_from = last_update["callback_query"]["from"]
self.__last_chat_id = last_update["callback_query"]["message"]["chat"]["id"]
self.__last_user_id = last_update["callback_query"]["from"]["id"]
self.__last_user_nickname = last_update["callback_query"]["from"]["username"] if "username" in last_update["callback_query"]["from"] else None
return self.__read_user(None)
def read_user_from_message(self, last_update):
self.__last_from = last_update["message"]["from"]
self.__last_chat_id = last_update["message"]["chat"]["id"]
self.__last_user_id = last_update["message"]["from"]["id"]
self.__last_user_nickname = last_update["message"]["from"]["username"] if "username" in last_update["message"]["from"] else None
return self.__read_user(last_update["message"]["text"])
def __read_user(self, text: Optional[str]):
self.user = None
try:
self.user = self.users.get(self.__last_user_id, self.__last_user_nickname, self.conn)
return True
except (LdapConnectionError, DuplicateEntryError) as e:
self.exception(e.__class__.__name__)
except AccountLockedError:
self.__send_message(
"Your account is locked. You cannot use the bot until an administrator unlocks it.\n"
"If you're a new team member, that will happen after the test on safety."
)
except AccountNotFoundError:
if text is not None:
# Maybe it is the invite link for an account that doesn't exist yet?
responded = self.respond_to_invite_link(text)
if responded:
return
self.store_id()
msg = f"""Sorry, you are not allowed to use this bot.
If you're part of <a href=\"http://weeeopen.polito.it/\">WEEE Open</a> add your user ID in the account management panel
or ask an administrator to unlock your account.
Your user ID is: <b>{self.__last_user_id}</b>"""
self.__send_message(msg)
return False
def __send_message(self, message):
for i in range(0, len(message), 4096):
self.bot.send_message(self.__last_chat_id, message[i : i + 4096])
def __send_inline_keyboard(self, message, markup):
self.bot.send_message(self.__last_chat_id, message, reply_markup=markup)
def __edit_message(self, message_id, message, markup):
self.bot.edit_message(self.__last_chat_id, message_id, message, reply_markup=markup)
def respond_to_invite_link(self, message) -> bool:
message: str
if not message.startswith(INVITE_LINK):
return False
link = message.split(" ", 1)[0]
code = link[len(INVITE_LINK) :]
try:
self.users.update_invite(code, self.__last_user_id, self.__last_user_nickname, self.conn)
except AccountNotFoundError:
self.__send_message("I couldn't find your invite. Are you sure of that link?")
return True
self.__send_message(
"Hey, I've filled some fields in the registration form for you, no need to say thanks.\n"
f"Just go back to {link} and complete the registration.\n"
"See you!"
)
return True
def start(self):
"""
Called with /start
"""
self.__send_message(
"\
<b>WEEE Open Telegram bot</b>.\nThe goal of this bot is to obtain information \
about who is currently in the lab, who has done what, compute some stats and, \
in general, simplify the life of our members and to avoid waste of paper \
as well.\nFor a list of the available commands type /help.",
)
def format_user_in_list(self, username: str, other=""):
person = self.people.get(username, self.conn)
user_id = None if person is None or person.tgid is None else person.tgid # This is unreadable. Deal with it.
display_name = CommandHandler.try_get_display_name(username, person)
haskey = chr(128273) if person.haskey else ""
sir = ""
if self.user.isadmin and person.dateofsafetytest is not None and not person.signedsir:
sir = f" (Remember to sign the SIR! {chr(128221)})"
if user_id is None:
return f"\n- {display_name}{haskey}{other}{sir}"
else:
return f'\n- <a href="tg://user?id={user_id}">{display_name}</a>{haskey}{other}{sir}'
@staticmethod
def try_get_display_name(username: str, person: Optional[Person]):
if person is None or person.cn is None:
return username
else:
return person.cn
def inlab(self):
"""
Called with /inlab
"""
inlab = self.logs.get_log().get_entries_inlab()
people_inlab = set()
if len(inlab) == 0:
msg = "Nobody is in lab right now."
elif len(inlab) == 1:
msg = "There is one student in lab right now:"
else:
msg = f"There are {str(len(inlab))} students in lab right now:"
for username in inlab:
msg += self.format_user_in_list(username)
people_inlab.add(username)
user_themself_inlab = self.user.uid in people_inlab
self.tolab_db.check_tolab(people_inlab)
people_going = self.tolab_db.filter_tolab(people_inlab)
number_of_people_going = len(people_going)
right_now = datetime.datetime.now(self.tolab_db.local_tz)
if number_of_people_going > 0:
today = right_now.date()
if number_of_people_going == 1:
msg += "\n\nThere is one student that is going to lab:"
else:
msg += f"\n\nThere are {str(number_of_people_going)} students that are going to lab:"
user_themself_tolab = False
for user in people_going:
username = user["username"]
going_day = user["tolab"].date()
hh = str(user["tolab"].hour).zfill(2)
mm = str(user["tolab"].minute).zfill(2)
if today == going_day:
msg += self.format_user_in_list(username, f" today at {hh}:{mm}")
elif today + datetime.timedelta(days=1) == going_day:
msg += self.format_user_in_list(username, f" tomorrow at {hh}:{mm}")
else:
msg += self.format_user_in_list(username, f" on {str(going_day)} at {hh}:{mm}")
if username == self.user.uid:
user_themself_tolab = True
if not user_themself_tolab and not user_themself_inlab:
msg += "\nAre you going, too? Tell everyone with /tolab."
else:
if right_now.hour > 19:
msg += "\n\nAre you going to the lab tomorrow? Tell everyone with /tolab."
elif not user_themself_inlab:
msg += "\n\nAre you going to the lab later? Tell everyone with /tolab."
if len(inlab) > 0 and not user_themself_inlab:
msg += "\n\nUse /ring for the bell, if you are at door 3."
self.__send_message(msg)
def tolab(self, the_time: str, day: str = None, is_gui: bool = False):
try:
the_time = self._tolab_parse_time(the_time)
except ValueError:
self.__send_message("Use correct time format, e.g. 10:30, or <i>no</i> to cancel")
return
if the_time is not None:
try:
day = self._tolab_parse_day(day)
except ValueError:
self.__send_message("Use correct day format: +1 for tomorrow, +2 for the day after tomorrow and so on")
return
# noinspection PyBroadException
try:
if the_time is None:
# Delete previous entry via Telegram ID
self.tolab_db.delete_entry(self.user.tgid)
self.__send_message(f"Ok, you aren't going to the lab, I've taken note.")
else:
sir_message = ""
if not self.user.signedsir and self.user.dateofsafetytest is not None:
sir_message = "\nRemember to sign the SIR when you get there!"
days = self.tolab_db.set_entry(self.user.uid, self.user.tgid, the_time, day)
if not is_gui:
if days <= 0:
self.__send_message(
f"I took note that you'll go to the lab at {the_time}. "
f"Use /tolab_no to cancel. Check if "
f"anybody else is coming with /inlab.{sir_message}"
)
elif days == 1:
self.__send_message(
f"So you'll go the lab at {the_time} tomorrow. Use /tolab_no to cancel. " f"Check if anyone else is coming with /inlab{sir_message}"
)
else:
last_message = sir_message if sir_message != "" else "\nMark it down on your calendar!"
self.__send_message(
f"So you'll go the lab at {the_time} in {days} days. Use /tolab_no to "
f"cancel. Check if anyone else is coming with /inlab"
f"{last_message}"
)
except Exception as e:
self.__send_message(f"An error occurred: {str(e)}")
print(traceback.format_exc())
def tolabGui(self):
calendar = Tolab_Calendar().make()
idx = 0
self.__send_inline_keyboard(message=f"Select a date", markup=calendar)
def get_tolab_active_sessions(self):
return self.bot.active_sessions
@staticmethod
def _tolab_parse_time(the_time: str):
"""
Parse time and coerce it into a standard format
:param the_time: Time string, provided by the user
:return: Time in HH:mm format, or None if "no"
"""
if the_time == "no":
return None
elif len(the_time) == 1 and the_time.isdigit():
return f"0{the_time}:00"
elif len(the_time) == 2 and the_time.isdigit() and 0 <= int(the_time) <= 23:
return f"{the_time}:00"
elif len(the_time) == 4 and the_time[0].isdigit() and the_time[2:4].isdigit() and 0 <= int(the_time[2:4]) <= 59:
if the_time[1] == ".":
return ":".join(the_time.split("."))
elif the_time[1] == ":":
return the_time
elif len(the_time) == 5 and the_time[0:2].isdigit() and the_time[3:4].isdigit():
if the_time[2] == ".":
the_time = ":".join(the_time.split("."))
if the_time[2] == ":":
if 0 <= int(the_time[0:2]) <= 23 and 0 <= int(the_time[3:5]) <= 59:
return the_time
raise ValueError
@staticmethod
def _tolab_parse_day(day: str):
"""
Convert day offset to an integer
:param day: Day as specified by the user
:return: Days, 0 if None
"""
if day is None:
return 0
else:
if day.startswith("+") and day[1:].isdigit():
day = int(day[1:])
if not day == 0:
return day
raise ValueError
def _get_tolab_gui_days(self, idx: int, date: str):
self.bot.active_sessions[idx][2]
day = date.split()
day[1] = datetime.datetime.strptime(day[1], "%B").month
day = f"{day[0]} {day[1]} {day[2]}"
day = datetime.datetime.strptime(day, "%d %m %Y")
today = datetime.datetime.now().timetuple()
today = f"{today.tm_mday} {today.tm_mon} {today.tm_year}"
today = datetime.datetime.strptime(today, "%d %m %Y")
diff = day - today
return diff.days
def ring(self, wave_obj):
"""
Called with /ring
"""
inlab = self.logs.get_log().get_entries_inlab()
if len(inlab) <= 0:
self.__send_message("Nobody is in lab right now, I cannot ring the bell.")
return
if self.lofi_player.player_exist():
lofi_player = self.lofi_player.get_player()
if lofi_player.is_playing():
lofi_player.stop()
sleep(1)
wave_obj.play()
sleep(1)
lofi_player.play()
else:
wave_obj.play()
else:
wave_obj.play()
self.__send_message("You rang the bell 🔔 Wait at door 3 until someone comes. 🔔")
def user_is_in_lab(self, uid):
inlab = self.logs.get_log().get_entries_inlab()
for username in inlab:
if username == uid:
return True
return False
def log(self, cmd_days_to_filter=None):
"""
Called with /log
"""
self.logs.get_log()
if cmd_days_to_filter is not None and cmd_days_to_filter.isdigit():
# Command is "/log [number]"
days_to_print = int(cmd_days_to_filter)
elif cmd_days_to_filter == "all":
# This won't work. Will never work. There's a length limit on messages.
# Whatever, this variant had been missing for months and nobody even noticed...
days_to_print = 31
else:
days_to_print = 1
days = {}
# reversed() doesn't create a copy
for line in reversed(self.logs.log):
this_day = line.day()
if this_day not in days:
if len(days) >= days_to_print:
break
days[this_day] = []
print_name = CommandHandler.try_get_display_name(line.username, self.people.get(line.username, self.conn))
if line.inlab:
days[this_day].append(f"<i>{print_name}</i> is in lab\n")
else:
days[this_day].append(f"<i>{print_name}</i>: {escape_all(line.text)}\n")
msg = ""
for this_day in days:
msg += "<b>{day}</b>\n{rows}\n".format(day=this_day, rows="".join(days[this_day]))
msg = msg + "Latest log update: <b>{}</b>".format(self.logs.log_last_update)
self.__send_message(msg)
def stat(self, cmd_target_user=None):
if cmd_target_user is None:
# User asking its own /stat
target_username = self.user.uid
else:
# Asking for somebody else
target_username = str(cmd_target_user)
if target_username.lower() != self.user.uid.lower():
# *Really* somebody else
if self.user.isadmin:
# Are you an admin? Then go on!
person = self.people.get(target_username, self.conn)
if person is None:
# Downloads them only if needed
self.logs.get_old_logs()
self.logs.get_log()
if not self.logs.user_exists_in_logs(target_username):
target_username = None
self.__send_message("No statistics for the given user. Have you typed it correctly?")
else:
target_username = person.uid
else:
target_username = None
self.__send_message("Sorry! You are not allowed to see stat of other users!\nOnly admins can!")
# Do we know what to search?
if target_username is not None:
# Downloads them only if needed
self.logs.get_old_logs()
self.logs.get_log()
month_mins, total_mins = self.logs.count_time_user(target_username)
month_mins_hh, month_mins_mm = self.logs.mm_to_hh_mm(month_mins)
total_mins_hh, total_mins_mm = self.logs.mm_to_hh_mm(total_mins)
name = CommandHandler.try_get_display_name(target_username, self.people.get(target_username, self.conn))
msg = (
f"Stat for {name}:"
f"\n<b>{month_mins_hh} h {month_mins_mm} m</b> this month."
f"\n<b>{total_mins_hh} h {total_mins_mm} m</b> in total."
f"\n\nLast log update: {self.logs.log_last_update}"
)
self.__send_message(msg)
def item_command_error(self, command):
self.__send_message(f"Add the item the code, e.g. /{command} R100")
def history(self, item, cmd_limit=None):
if cmd_limit is None:
limit = 6
else:
limit = int(cmd_limit)
if limit < 1:
limit = 1
elif limit > 50:
limit = 50
try:
history = self.tarallo.get_history(item, limit)
msg = f"<b>History of item {item}</b>\n\n"
entries = 0
for index in range(0, len(history)):
history: List[AuditEntry]
change = history[index].change
h_user = history[index].user
h_other = history[index].other
h_time = datetime.datetime.fromtimestamp(int(history[index].time)).strftime("%d-%m-%Y %H:%M")
if change == AuditChanges.Move:
msg += f"➡️ Moved to <b>{h_other}</b>\n"
elif change == AuditChanges.Update:
msg += "🛠️ Updated features\n"
elif change == AuditChanges.Create:
msg += "📋 Created\n"
elif change == AuditChanges.Rename:
msg += f"✏️ Renamed from <b>{h_other}</b>\n"
elif change == AuditChanges.Delete:
msg += "❌ Deleted\n"
elif change == AuditChanges.Lose:
msg += "🔍 Lost\n"
else:
msg += f"Unknown change {change.value}"
entries += 1
display_user = CommandHandler.try_get_display_name(h_user, self.people.get(h_user, self.conn))
msg += f"{h_time} by <i>{display_user}</i>\n\n"
if entries >= 6:
self.__send_message(msg)
msg = ""
entries = 0
if entries != 0:
self.__send_message(msg)
except ItemNotFoundError:
self.__send_message(f"Item {item} not found.")
except AuthenticationError:
self.__send_message("Sorry, cannot authenticate with T.A.R.A.L.L.O.")
except RuntimeError:
fail_msg = f"Sorry, an error has occurred (HTTP status: {str(self.tarallo.response.status_code)})."
self.__send_message(fail_msg)
def item_info(self, item):
try:
item = self.tarallo.get_item(item)
location = " → ".join(item.location)
msg = f"Item <b>{item.code}</b>\nLocation: {location}\n\n"
for feature in item.features:
msg += f"{feature}: {item.features[feature]}\n"
if item.product is not None:
msg += f"----------------------------\n"
for feature in item.product.features:
msg += f"{feature}: {item.product.features[feature]}\n"
msg += f'\n<a href="{self.tarallo.url}/item/{item.code}">View on Tarallo</a>'
self.__send_message(msg)
except ItemNotFoundError:
self.__send_message(f"Item {item} not found.")
except (RuntimeError, AuthenticationError):
fail_msg = f"Sorry, an error has occurred (HTTP status: {str(self.tarallo.response.status_code)})."
self.__send_message(fail_msg)
def item_location(self, item):
try:
item = self.tarallo.get_item(item, 0)
location = " → ".join(item.location)
msg = f"Item <b>{item.code}</b>\nLocation: {location}\n"
msg += f'\n<a href="{self.tarallo.url}/item/{item.code}">View on Tarallo</a>'
self.__send_message(msg)
except ItemNotFoundError:
self.__send_message(f"Item {item} not found.")
except (RuntimeError, AuthenticationError):
fail_msg = f"Sorry, an error has occurred (HTTP status: {str(self.tarallo.response.status_code)})."
self.__send_message(fail_msg)
def top(self, cmd_filter=None):
"""
Called with /top <filter>.
Currently, the only accepted filter is "all", and besides that,
it returns the monthly filter
"""
if self.user.isadmin:
# Downloads them only if needed
self.logs.get_old_logs()
self.logs.get_log()
# TODO: add something like "/top 04 2018" that returns top list for April 2018
if cmd_filter == "all":
msg = "Top User List!\n"
rank = self.logs.count_time_all()
else:
msg = "Top Monthly User List!\n"
rank = self.logs.count_time_month()
# sort the dict by value in descending order (and convert dict to list of tuples)
rank = sorted(rank.items(), key=lambda x: x[1], reverse=True)
n = 0
for rival, the_time in rank:
entry = self.people.get(rival, self.conn)