-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschool_bot.py
More file actions
1658 lines (1443 loc) · 80.8 KB
/
school_bot.py
File metadata and controls
1658 lines (1443 loc) · 80.8 KB
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
# -*- coding: utf-8 -*-
"""
### WATERMARK ###
# Dev: Pavel Krupenko #
# Git: greengroat #
# VK: @greengroat
# Telegram: @greengroat #
# Discord: '3EJLEHblN 4EJLOBEK#3374'
### WATERMARK ###
Main скрипт бота. Используется vkbottle.
"""
import datetime
import itertools
import json
import os
import sys
import time
import traceback
import zipfile
from asyncio import sleep
from datetime import timedelta
import loguru
import requests
from vkbottle import Callback, GroupEventType, GroupTypes
from vkbottle import Keyboard, KeyboardButtonColor, Text, CtxStorage, BaseStateGroup
from vkbottle import PhotoMessageUploader, DocMessagesUploader
from vkbottle.bot import Bot, Message, MessageEvent
from vkbottle_types.objects import WallPostType
from modules.botdb import BotDB
from modules.config import *
from modules.creating_images import create_img, create_report, generation_total_report
from modules.parse_site import post_to_site
from modules.paths import *
from netschoolapi import NetSchoolAPI
# Debug
loguru.logger.add(full_path_to_errors_txt, level="ERROR")
# Creating DataBase
db = BotDB(os.getcwd() + path_to_school_db_db)
db.making_table()
# preparatory stage
bot = Bot(vk_acces_token)
ctx = CtxStorage()
class States(BaseStateGroup):
wall_news_header = 'wall_news_header'
login = 'login'
password = 'password'
output_type = 'output_type'
right_week = 'right_week'
id_login = 1
id_pass = 2
report = 'report'
id_answ = 3
day = 'day'
site = ''
school = 'school'
question = 'question'
# Write to file peoples`s online
async def write_online(user_id):
global online_data
if datetime.date.today().strftime('%d.%m.%y') in online_data.keys():
if user_id not in online_data[datetime.date.today().strftime('%d.%m.%y')]:
online_data[datetime.date.today().strftime('%d.%m.%y')].append(user_id)
else:
online_data[datetime.date.today().strftime('%d.%m.%y')] = [user_id]
with open(path_to_online_json, 'a', encoding='utf-8') as file:
file.truncate(0)
json.dump(online_data, file)
async def writing_to_file(name_function):
with open(path_to_logs_functions_txt, 'a', encoding='utf-8') as f:
f.write(name_function + ' ')
async def get_log(user_id):
user = (await db.get(user_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
ns = NetSchoolAPI(site)
log = await ns.login(sgo_login, sgo_password, school)
return log
async def islogged(id_user):
if await db.get(id_user):
user = (await db.get(id_user))[0]
is_auth = user[-1]
if is_auth == 'Yes':
return True
else:
return False
else:
return False
async def beauty_text(list_lessons):
res, result = "", []
for lesson in list_lessons[1:]:
if lesson != "":
n_patterns = ['\n\n📕 ', '\n\u2800\u2800📚 ', '\n\u2800\u2800📝 ']
lesson = lesson.strip()
subject = lesson[:lesson.find(':')]
if len(subject) > 17:
subject = subject[:18] + '...'
if lesson[-8:] != 'Оценка: ':
mark = lesson[lesson.rfind(':') + 1:]
else:
mark = ''
homework = lesson[lesson.find(':') + 2:lesson.find(' Оценка: ')].replace('Оценка', '')
n_patterns[0] += subject
n_patterns[1] += homework
n_patterns[2] += mark
for i in n_patterns:
res += i
return res
async def debugging(type_func, printed):
with open(path_to_finction_debug_txt, 'a') as debug_file:
debug_file.write(
f"Data: {datetime.datetime.today().strftime('%d-%m-%Y %H:%M:%S')}\n"
f"Type: {type_func}\n\n"
f"Printed: {printed}"
)
debug_file.close()
async def detection_days(msg):
monday, monday_another_w = '', ''
if not msg[:1].isnumeric():
if msg.count("| Сегодня") > 0:
real_day = datetime.date.today()
elif msg.count("| Завтра") > 0:
real_day = datetime.date.today() + timedelta(days=1)
elif msg.count("| Послезавтра") > 0:
real_day = datetime.date.today() + timedelta(days=2)
else:
monday = datetime.date.today() - timedelta(days=datetime.date.today().weekday())
real_day = monday + timedelta(days=daya[msg[msg.rfind(' ') + 1:]])
else:
another_w_day = msg.split(' ')[0] + '.' + str(datetime.datetime.today().year)
another_w_day = datetime.datetime.strptime(another_w_day, "%d.%m.%Y").date()
monday_another_w = another_w_day - timedelta(days=another_w_day.weekday())
real_day = another_w_day
return monday_another_w, real_day, monday
@bot.on.private_message(payload={'logged': 'menu'})
async def logged_menu(message: Message):
user = (await db.get(message.from_id))[0][-2]
try:
await bot.state_dispenser.delete(message.peer_id)
except:
pass
if user == 'МОУ гимназия № 10':
paylo = {'logged': 'schedule'}
else:
paylo = {'schedule': 'week'}
keyboard = (
Keyboard(inline=False, one_time=False)
.add(Text('Boпpосы пo РДШ/Группе', {'menu': 'question'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('📚 Дневник на текущую неделю', {'schedule': 'full_week'}), color=KeyboardButtonColor.POSITIVE)
.row()
.add(Text('📖 Дневник', {'logged': 'diary'}), color=KeyboardButtonColor.POSITIVE)
.row()
.add(Text('📅 Расписание', payload=paylo), color=KeyboardButtonColor.PRIMARY)
.add(Text('📝 Отчет', {'menu': 'reports'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('⚙ Настройки', {'logged': 'settings'}), color=KeyboardButtonColor.SECONDARY)
)
if not await islogged(message.from_id):
text = '👋 Добро пожаловать в тестовый режим!\n\nВ нем вы можете протестировать функции, кнопочки и всё необходимое.\n' \
'Будет показываться выдуманное расписание с выдуманными предметами, заданиями и оценками.\n\n' \
'Для входа в свой дневник воспользуйтесь соответствующей кнопкой ниже = )'
keyboard.row().add(Text('🔑 Войти в свой дневник', {'variant': 'login'}),
color=KeyboardButtonColor.POSITIVE)
else:
text = 'Меню...'
if message.from_id == developer_id:
keyboard.row().add(Text('Отчет', {'admin_report_week': 'global_admin_report'}),
color=KeyboardButtonColor.SECONDARY)
await message.answer(
message=text, keyboard=keyboard
)
@bot.on.message(payload={'homework': 'day'})
async def homework_day(message: Message):
first = time.time()
res = '💤 Нет уроков, отдыхай = )'
detected = await detection_days(message.text)
monday_another_w, real_day, monday = detected[0], detected[1], detected[2]
data = {}
msg = ''
mark = ' Оценка: '
user = (await db.get(message.from_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
if await islogged(message.from_id):
try:
ns = NetSchoolAPI(site)
await message.answer('Авторизация в СГО...')
# Logging at NetSchoolAPI with Users Login And Password and getting result
await ns.login(sgo_login,
sgo_password,
school)
if not message.text[:1].isnumeric():
# NOT Other days at this week
if message.text[:2] != 'ДЗ':
# Not Sunday or Saturday -> Simple Diary
if datetime.datetime.today().strftime("%A") not in ['Sunday', 'Saturday']:
result = await ns.diary()
else:
if datetime.datetime.today().strftime("%A") == 'Sunday':
day_x = (datetime.date.today() + timedelta(days=1))
result = await ns.diary(start=day_x)
date = day_x
else:
if message.text.count('| Сегодня') > 0:
result = await ns.diary()
else:
day_x = (datetime.date.today() + timedelta(days=2))
result = await ns.diary(start=day_x)
else:
result = await ns.diary()
else:
result = await ns.diary(start=monday_another_w)
await ns.logout()
await message.answer('Генерация дневника...')
# Creating week as list
for days in result.schedule:
data[str(days.day)] = []
msg += '\n\n' + str(days.day) + 'koli'
for lesson in days.lessons:
if len(lesson.assignments) > 0:
for i in range(len(lesson.assignments)):
if lesson.assignments[i].mark:
mark += str(lesson.assignments[i].mark)
else:
mark += ''
msg += '\n' + lesson.subject + ': ' + lesson.assignments[0].content + mark + 'koli'
else:
msg += '\n' + lesson.subject + ': Не задано' + mark + 'koli'
mark = ' Оценка: '
data[str(days.day)] = msg.split("koli")
msg = ''
res = data[str(real_day)]
except:
await logged_menu(message)
else:
real_day = await detection_days(message.text)
res = test_week[real_day[1].strftime("%A")]
if real_day[1].strftime("%A") == 'Sunday':
res = '💤 Нет уроков, отдыхай = )'
# Sending list of lessons to func, creating image
if res != '💤 Нет уроков, отдыхай = )':
if await islogged(message.from_id):
keyboard = (Keyboard(one_time=False, inline=False))\
.add(Callback('ℹ Подробности', {'homework': 'details', 'day': real_day.strftime('%d-%m-%y')}),
color=KeyboardButtonColor.PRIMARY)\
.row()\
.add(Text('Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.SECONDARY)
else:
keyboard = (Keyboard(one_time=False,
inline=False)).add(Text('🏡 Назад в меню', {'logged': 'menu'}),
color=KeyboardButtonColor.SECONDARY)
if output_type == 'Изображение':
msg = 'Подробный текст домашнего задания:\n\n'
await message.answer('Генерируем изображение...')
total_data = create_img(res, message.from_id)
image = total_data[0]
if total_data[1]:
for lesson in total_data[1]:
msg += f'{list(lesson[0].items())[0][0]}: {list(lesson[0].items())[0][1]}\n\n'
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=image, peer_id=message.peer_id
)
if msg == 'Подробный текст домашнего задания:\n\n':
msg = '\xa0'
await message.answer(message=msg, attachment=doc, keyboard=keyboard)
os.remove(image)
elif output_type == 'Текст':
await message.answer('Генерируем текстовое сообщение...')
date = datetime.datetime.strptime(res[0].strip(), "%Y-%m-%d").date()
weekday = w_daya[date.weekday()]
res = '\n\n\n✅ ' + weekday + await beauty_text(res)
await message.answer(message=res, keyboard=keyboard)
else:
await message.answer(res)
await write_online(message.from_id)
await writing_to_file('homework_day')
@bot.on.message(text=['Начать'])
@bot.on.message(command='start')
async def start(message: Message):
user = await db.get(message.from_id)
if not user:
user_info = await bot.api.users.get(message.from_id)
first = user_info[0].first_name
sec = user_info[0].last_name
await db.adding_user(message.from_id, first, sec)
await bot.api.messages.send(peer_id=feedback_chat, random_id=0, message=f'Added @id{message.from_id}')
await message.answer('👋 Приветствую в системе!\n'
'Выбери дальнейший вариант развития событий:\n\n\n'
'P.S. в данный момент проводится Бета-Тест, в случае каких-то неполадок воспользуйтесь '
'пунктом "Жалоба/Предложение" в настройках = )',
keyboard=(Keyboard(inline=False, one_time=False)
.add(Text('🚪 Тестовый Вариант (Без входа в дневник)', {'logged': 'menu'}),
color=KeyboardButtonColor.PRIMARY)
.add(Text('🔐 Войти в свой дневник', {'variant': 'login'}),
color=KeyboardButtonColor.PRIMARY)
)
)
await message.answer('При наличии вопросов по использованию бота и его функциям: ⬇',
keyboard=Keyboard(one_time=False, inline=True)
.add(Text('Помощь', {'menu': 'help'}), color=KeyboardButtonColor.NEGATIVE))
else:
await logged_menu(message)
@bot.on.private_message(lev='Вoйти в систему')
@bot.on.private_message(payload={'variant': 'login'})
async def login(message: Message):
await db.set_site_and_school(message.from_id, 'МОУ гимназия № 10')
await bot.state_dispenser.set(message.peer_id, States.login)
await message.answer('❓ Чтобы получать Ваше домашнее задание из ВК нужно авторизоваться в системе.\n'
'\n\n\n'
'❗❗❗ ВНИМАНИЕ ❗❗❗\n'
'Вводя свои данные данные Вы соглашаетесь с Пользовательским соглашением, доступным по ссылке:\n'
'vk.com/@gymnasium_10_vlg-politika-v-otnoshenii-obrabotki-personalnyh-dannyh\n\n'
'🔒 Введите Ваш логин, как при входе в "Сетевой Город.Образование" (Госуслуги не работают): ',
keyboard=Keyboard(one_time=True, inline=False)
.add(Callback('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.NEGATIVE)
)
@bot.on.private_message(state=States.login)
async def password(message: Message):
ctx.set('login', message.text)
await bot.state_dispenser.set(message.peer_id, States.password)
await message.answer('🔑 Введите Ваш пароль, как при входе в "Сетевой Город.Образование":',
keyboard=Keyboard(one_time=True, inline=False)
.add(Callback('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.NEGATIVE))
@bot.on.private_message(state=States.password)
async def result_login(message: Message):
try:
name = ctx.get('login')
ctx.set('password', message.text)
await bot.state_dispenser.delete(message.peer_id)
id_ans = await message.answer(f'❗ Проверьте Ваши данные: \n\n'
f'🔒 Логин: {name}\n'
f'🔑 Пароль: {message.text}\n\n'
f'В случае, если вы из другой школы, воспользуйтесь кнопкой "Другие настройки"\n',
keyboard=(Keyboard(inline=False, one_time=True)
.add(Text('✅ Все верно!', {'choose': 'output'}),
color=KeyboardButtonColor.POSITIVE)
.add(Text('🔄 Заполнить заново', {'variant': 'login'}),
color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('⚙ Дрyгие нaстpойки', {'logged': 'other_settings'}),
color=KeyboardButtonColor.SECONDARY))
)
ctx.set('id_answ', id_ans.message_id)
except Exception as e:
await message.answer('❗ Произошла ошибка! Разработчики уже оповещены о проблеме. Приносим свои извинения.')
await bot.api.messages.send(developer_id, random_id=0, message=f'Error with {message.from_id}!\n {e}')
await logged_menu(message)
@bot.on.private_message(lev='Дрyгие нaстpойки')
@bot.on.private_message(payload={'logged': 'other_settings'})
async def site_settings(message: Message):
await bot.state_dispenser.set(message.peer_id, States.school)
await message.answer(message='✍ Введите название своей школы (Точь-в-точь, как при выборе школы): \n\n'
'Пример: "МОУ гимназия №10", "МОУ СОШ №57"',
keyboard=Keyboard(one_time=True, inline=False)
.add(Callback('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.NEGATIVE))
await writing_to_file('site_settings')
@bot.on.private_message(state=States.school)
async def school_settings(message: Message):
await bot.state_dispenser.delete(message.peer_id)
name = ctx.get('login')
password = ctx.get('password')
await db.set_site_and_school(message.from_id, message.text)
res = await message.answer(message='❗ Проверьте данные: \n'
f'🔒 Имя: {name}\n'
f'🔑 Пароль: {password}\n'
f'🏫 Школа: {message.text}',
keyboard=(Keyboard(inline=False, one_time=True)
.add(Text('✅ Все верно!', {'choose': 'output'}),
color=KeyboardButtonColor.POSITIVE)
.add(Text('🔄 Заполнить заново', {'logged': 'other_settings'}),
color=KeyboardButtonColor.PRIMARY)
)
)
await sleep(30)
await bot.api.messages.delete(res.message_id, peer_id=message.peer_id, delete_for_all=True)
await writing_to_file('school_settings')
@bot.on.private_message(payload={'choose': 'output'})
async def choose_output(message: Message):
await message.answer('🔄 Пытаемся авторизироваться с Вашими данными...')
name = ctx.get('login')
password = ctx.get('password')
man = (await db.get(message.from_id))[0]
site, school = man[-3], man[-2]
id_n = ctx.get('id_answ')
try:
ns = NetSchoolAPI(site)
await ns.login(name, password, school)
await ns.diary()
except Exception as e:
id_ans = await message.answer(f'❗ Произошла ошибка! Проверьте свои данные!\n\n'
f'🔒 Логин: {name}\n'
f'🔑 Пароль: {password}\n'
f'🏫 Школа: {school}\n'
f'🕸 Сайт: {site}',
keyboard=Keyboard(inline=False, one_time=True)
.add(Text('🔄 Заполнить заново', {'variant': 'login'}),
color=KeyboardButtonColor.PRIMARY))
await sleep(30)
await bot.api.messages.delete(peer_id=message.from_id,
message_ids=id_ans.message_id,
delete_for_all=True)
await bot.api.messages.delete(peer_id=message.from_id,
message_ids=id_n,
delete_for_all=True)
else:
await db.update(message.from_id, name, password)
await db.set_authorize(message.from_id, 'Yes')
await message.answer('✅ Успешно!')
await message.answer(message='Выберите способ отображения домашнего задания:',
keyboard=(Keyboard(one_time=True, inline=False)
.add(Text('💬 Текст', {'choose_output': 'Done'}), color=KeyboardButtonColor.PRIMARY)
.add(Text('🖼 Изображение', {'choose_output': 'Done'}),
color=KeyboardButtonColor.PRIMARY)
)
)
await bot.api.messages.delete(peer_id=message.from_id,
message_ids=id_n,
delete_for_all=True)
@bot.on.private_message(payload={'choose': 'output_l'})
async def choose_output_l(message: Message):
await message.answer(message='Выберите способ отображения домашнего задания:',
keyboard=(
Keyboard(one_time=True, inline=False)
.add(Text('💬 Текст', {'choose_output': 'Done'}), color=KeyboardButtonColor.PRIMARY)
.add(Text('🖼 Изображение', {'choose_output': 'Done'}),
color=KeyboardButtonColor.PRIMARY)
)
)
@bot.on.private_message(payload={'choose_output': 'Done'})
async def go_to_menu(message: Message):
await db.set_output_type(message.from_id, message.text.split()[1])
await message.answer(message=f'✅ Принято! Вы будете видеть домашнее задание как {message.text}.\n'
f'Выбор можно изменить в любой момент в настройках = )',
keyboard=(Keyboard(one_time=True, inline=False)
.add(Text('🏡 В меню', {'logged': 'menu'}))
)
)
@bot.on.private_message(payload={'schedule': 'full_week'})
async def full_week(message: Message):
data = {}
msg = ''
mark = ' Оценка: '
user = (await db.get(message.from_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
if await islogged(message.from_id):
ns = NetSchoolAPI(site)
await ns.login(sgo_login, sgo_password, school)
schedule = await ns.diary()
for days in schedule.schedule:
data[str(days.day)] = []
msg += '\n\n' + str(days.day) + 'koli'
for lesson in days.lessons:
if len(lesson.assignments) > 0:
for i in range(len(lesson.assignments)):
if lesson.assignments[i].mark:
mark += str(lesson.assignments[i].mark)
else:
mark += ''
msg += '\n' + lesson.subject + ': ' + lesson.assignments[0].content + mark + 'koli'
else:
msg += '\n' + lesson.subject + ': Не задано' + mark + 'koli'
mark = ' Оценка: '
data[str(days.day)] = msg.split("koli")
msg = ''
result = data
else:
result = dict(itertools.islice(test_week.items(), 6))
if output_type == 'Изображение':
num = 0
path_list = []
pic_list = []
await message.answer('Генерируем изображения...')
for day in result.keys():
day = result[day]
image = create_img(day, str(message.from_id) + f'_{num}')[0]
pic_list.append(image)
path_list += image + ', '
num += 1
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=image, peer_id=message.peer_id
)
path_list.append(doc)
await message.answer(message='\xa0', attachment=path_list)
for pic in pic_list:
os.remove(pic)
elif output_type == 'Текст':
res = ''
for day in result.keys():
day = result[day]
date = datetime.datetime.strptime(day[0].strip(), "%Y-%m-%d").date()
weekday = w_daya[date.weekday()]
res += '\n\n\n✅ ' + weekday + await beauty_text(day) + '\n'
await message.answer(res)
await write_online(message.from_id)
await writing_to_file('full_week')
async def homework_details(user_id, date_str):
user = (await db.get(user_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
try:
ns = NetSchoolAPI(site)
# Logging at NetSchoolAPI with Users Login And Password and getting result
await ns.login(sgo_login,
sgo_password,
school)
date = datetime.datetime.strptime(date_str, '%d-%m-%y')
result = await ns.diary(start=date, end=date)
date_local = date.strftime('%d.%m.%Y')[:date.strftime('%d.%m.%Y').rfind('.')]
lessons_list, result_list = [], []
for days in result.schedule:
for lesson in days.lessons:
if lesson.assignments:
family = await ns.details(lesson.assignments[0].id)
if family['description']:
description = family['description']
else:
description = None
if family['attachments']:
attachments = await ns.download_attachment(family['attachments'])
else:
attachments = None
if lesson.subject.count('Элективный курс') > 0:
if len(lesson.subject.strip('Элективный курс ')) > 30:
scopes = lesson.subject[lesson.subject.find('"'):lesson.subject.rfind(""'') + 1].split(' ')
subject = 'Эл.курс' + scopes[0] + '..' + scopes[-1]
else:
subject = lesson.subject.strip('Элективный курс ')
else:
if len(f'{date_local} | {lesson.subject}') < 39:
subject = lesson.subject
else:
subject = f'{lesson.subject.split()[0]}...{lesson.subject.split()[-1]}'
if subject in lessons_list:
pos_les = 0
for work in range(len(lessons_list)):
if lessons_list[work].count(subject) > 0:
pos_les = work
if lessons_list[pos_les][-1] == ')' and lessons_list[pos_les][-2].isnumeric():
subject = subject + str(int(lessons_list[pos_les][-2]) + 1)
else:
subject += '(1)'
lessons_list.append(subject)
if attachments or description:
result_list.append(subject)
keyboard = Keyboard(one_time=True, inline=False)
if result_list:
for attach in range(len(result_list)):
if attach != len(result_list) - 1:
keyboard.add(Text(f'{date_local} | {result_list[attach]}', {'lessons': 'attachments'}),
color=KeyboardButtonColor.POSITIVE)
keyboard.row()
else:
keyboard.add(Text(f'{date_local} | {result_list[attach]}', {'lessons': 'attachments'}),
color=KeyboardButtonColor.POSITIVE)
return ('Показаны только те дни, у которых есть подробности\n\n'
'Выберите день, у которого хотите узнать подробности:\n',
keyboard)
else:
return 'Нет подробностей...', []
except Exception as e:
return ('❗ Произошла ошибка! Разработчики уже оповещены о проблеме.\n'
'❗ Приносим свои извинения, попробуйте еще раз', traceback.format_exc())
@bot.on.private_message(payload={'lessons': 'attachments'})
async def lessons_attachment(message: Message):
await message.answer('🔄 Загрузка подробностей...')
subject = message.text[message.text.find('| ') + 2:]
result_dict, total_lesson = {}, ''
date = message.text[:message.text.find(' ')] + '.' + str(datetime.date.today().year)
real_date = datetime.datetime.strptime(date, '%d.%m.%Y')
user = (await db.get(message.from_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
ns = NetSchoolAPI(site)
await ns.login(sgo_login, sgo_password, school)
result = await ns.diary(start=real_date, end=real_date)
for lesson in result.schedule[0].lessons:
if lesson.assignments:
data[lesson.subject] = lesson.assignments[0].id
if subject[-2].isnumeric() and subject[-1] == ')':
for work in data.keys():
if subject[:-3] in work or (subject[:-3].split('...')[0] in work and subject[:-3].split('...')[1]):
result_dict[work] = data[work]
key = int(subject[-2]) - 1
total_lesson = list(result_dict.keys())[key]
else:
for work in data.keys():
if subject in work or subject.split('...')[0] in work and subject.split('...')[1]:
total_lesson = data[work]
family = await ns.details(total_lesson)
loguru.logger.info(f'{family} {message.from_id}')
if family['description']:
description = '🖹 Подробности от учителя: \n' + family['description'] + '\n'
else:
description = '🤷 Нет подробностей от учителя...\n'
if family['attachments']:
doc_list = []
attachments = await ns.download_attachment_as_bytes(family['attachments'])
for file in attachments:
doc = await DocMessagesUploader(bot.api).upload(
title=file['name'],
file_source=file['file'],
peer_id=message.from_id
)
doc_list.append(doc)
files = '\n📎 Прикрепленные файлы:'
else:
doc_list = []
files = '\n🤷 Нет прикрепленных файлов = ('
await message.answer(message=description + files, attachment=doc_list)
await logged_menu(message)
await writing_to_file('lessons_attachment')
@bot.on.raw_event(GroupEventType.MESSAGE_EVENT, dataclass=MessageEvent)
async def on_settings(event: MessageEvent):
if event.object.payload != {'bot_news': 'True'}:
try:
await bot.state_dispenser.delete(event.peer_id)
except:
pass
if list(event.payload.keys())[0] != 'homework' and list(event.payload.values())[0] != 'details':
if (await db.get(event.user_id))[0][-2] == 'МОУ гимназия № 10':
paylo = {'logged': 'schedule'}
else:
paylo = {'schedule': 'week'}
keyboard = (
Keyboard(inline=False, one_time=False)
.add(Text('Boпpосы пo РДШ/Группе', {'menu': 'question'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('📚 Дневник на текущую неделю', {'schedule': 'full_week'}), color=KeyboardButtonColor.POSITIVE)
.row()
.add(Text('📖 Дневник', {'logged': 'diary'}), color=KeyboardButtonColor.POSITIVE)
.row()
.add(Text('📅 Расписание', payload=paylo), color=KeyboardButtonColor.PRIMARY)
.add(Text('📝 Отчет', {'menu': 'reports'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('⚙ Настройки', {'logged': 'settings'}), color=KeyboardButtonColor.SECONDARY)
)
if not await islogged(event.peer_id):
text = '👋 Добро пожаловать в тестовый режим!\nВы можете протестировать функции, кнопочки и всё необходимое.\n' \
'👋 Будет показываться выдуманное расписание с выдуманными предметами, заданиями и оценками.\n\n' \
'👋 Для входа в свой дневник воспользуйтесь соответствующей кнопкой ниже = )'
keyboard.row().add(Text('Войти в свой дневник', {'variant': 'login'}),
color=KeyboardButtonColor.POSITIVE)
else:
text = '...'
if event.user_id == developer_id:
keyboard.row().add(Text('Отчет', {'admin_report_week': 'global_admin_report'}), color=KeyboardButtonColor.SECONDARY)
await event.send_message(
message=text, keyboard=str(keyboard)
)
else:
if await islogged(event.user_id):
result = await homework_details(event.user_id, list(event.payload.values())[1])
setattr(event.object, 'payload', {})
if result[0] == '❗ Произошла ошибка! Разработчики уже оповещены о проблеме.\n❗ Приносим свои извинения, попробуйте еще раз':
await bot.api.messages.send(peer_ids=feedback_chat, random_id=0,
message=f'Ошибка у пользователя {event.user_id}:\n\n'
f'{result[1]}')
await event.send_message(message=result[0], random_id=0)
await on_settings(event)
elif result[0] == 'Показаны только те дни, у которых есть подробности\n\nВыберите день, у которого хотите узнать подробности:\n':
await event.send_message(message=result[0], keyboard=result[1], random_id=0)
else:
await event.send_message(message=result[0], random_id=0)
else:
await event.send_message(message='В тестовом режиме недоступны подробности', random_id=0,)
await on_settings(event)
await event.show_snackbar(text='Выполнено!')
else:
ctx.set('cms', event.object.conversation_message_id)
await event.show_snackbar('Секунду...')
await bot.state_dispenser.set(peer_id=event.peer_id, state=States.wall_news_header)
await bot.api.messages.send(user_id=site_manager_id, random_id=0, message='Введите заголовок: ')
@bot.on.message(payload={'homework': 'chooseday_l'})
async def choose_day(message: Message):
await message.answer(
'Выберите день:',
keyboard=(
Keyboard(inline=False, one_time=False)
.row()
.add(Text('ДЗ | Пн', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text('ДЗ | Вт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text('ДЗ | Ср', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.row()
.add(Text('ДЗ | Чт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text('ДЗ | Пт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text('ДЗ | Сб', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.row()
.add(Text('Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.PRIMARY)
)
)
await writing_to_file('choose_day')
@bot.on.private_message(payload={'logged': 'diary'})
async def diary(message: Message):
await message.answer(message='...',
keyboard=(
Keyboard(inline=False, one_time=False)
.add(Text(
f'{list(daya.keys())[list(daya.values()).index(datetime.date.today().weekday())]} | Сегодня',
{'homework': 'day'}), color=KeyboardButtonColor.POSITIVE)
.add(Text(
f'{list(daya.keys())[list(daya.values()).index((datetime.date.today() + timedelta(days=1)).weekday())]} | Завтра',
{'homework': 'day'}), color=KeyboardButtonColor.POSITIVE)
.add(Text(
f'{list(daya.keys())[list(daya.values()).index((datetime.date.today() + timedelta(days=2)).weekday())]} | Послезавтра',
{'homework': 'day'}), color=KeyboardButtonColor.POSITIVE)
.row()
.add(Text('📅 Другие дни', {'homework': 'chooseday_l'}), color=KeyboardButtonColor.PRIMARY)
.add(Text('📅 Дрyгaя недeля', {'homework': 'another_week'}),
color=KeyboardButtonColor.PRIMARY))
.row()
.add(Text('🧐 Посмотреть долги по предметам', {'menu': 'dept'}), color=KeyboardButtonColor.NEGATIVE)
.row()
.add(Text('🏡 В меню', {'logged': 'menu'}))
)
await writing_to_file('diary')
@bot.on.private_message(payload={'homework': 'another_week'})
async def another_week(message: Message):
monday = datetime.date.today() - timedelta(days=datetime.date.today().weekday())
list_mondays = [((monday + timedelta(days=7) - timedelta(days=(i - 1) * 7)).strftime("%d-%m-%Y"),
(monday + timedelta(days=7) - timedelta(days=(i - 1) * 7) + timedelta(days=6)).strftime(
"%d-%m-%Y")) for i in range(5)]
list_mondays = list(reversed(list_mondays))
keyboard = Keyboard(inline=False, one_time=False)
for i in range(len(list_mondays)):
if i == 2:
condition = 'Текущ.'
color = KeyboardButtonColor.POSITIVE
elif i == 1:
condition = 'Прошл'
color = KeyboardButtonColor.SECONDARY
elif i == 0:
condition = 'Позапрошл.'
color = KeyboardButtonColor.SECONDARY
elif i == 3:
condition = 'След.'
color = KeyboardButtonColor.SECONDARY
else:
condition = 'Последующ.'
color = KeyboardButtonColor.SECONDARY
keyboard.add(
Text(list_mondays[i][0].replace('-', '.') + '-' + list_mondays[i][1].replace('-', '.') + f' ({condition})',
{'another_week': 'day'}), color=color).row()
await message.answer(message='...',
keyboard=keyboard.add(Text('🏡 В меню', {'logged': 'menu'}), color=KeyboardButtonColor.PRIMARY
)
)
await writing_to_file('another_week')
@bot.on.private_message(payload={'another_week': "day"})
async def another_week_day(message: Message):
right_monday = message.text.split('-')[0]
date_monday = datetime.datetime.strptime(right_monday, '%d.%m.%Y').date()
list_days = [date_monday + timedelta(days=i) for i in range(6)]
list_days = [i.strftime('%d.%m.%Y').replace('-', '.')[:i.strftime('%d.%m.%Y').replace('-', '.').rfind('.')] for i in
list_days]
await message.answer(
'Выберите день:',
keyboard=(
Keyboard(inline=False, one_time=False)
.row()
.add(Text(f'{str(list_days[0])} ДЗ | Пн', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text(f'{str(list_days[1])} ДЗ | Вт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text(f'{str(list_days[2])} ДЗ | Ср', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.row()
.add(Text(f'{str(list_days[3])} ДЗ | Чт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text(f'{str(list_days[4])} ДЗ | Пт', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.add(Text(f'{str(list_days[5])} ДЗ | Сб', {'homework': 'day'}), color=KeyboardButtonColor.SECONDARY)
.row()
.add(Text('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.PRIMARY)
)
)
await writing_to_file('another_week_day')
@bot.on.private_message(payload={'logged': 'schedule'})
async def schedule(message: Message):
if await islogged(message.from_id):
await message.answer(message='Выберите расписание: ', keyboard=Keyboard(one_time=True, inline=False)
.add(Text('🎒 Уроков', {'schedule': 'week'}), color=KeyboardButtonColor.PRIMARY)
.add(Text('🔔 Звонков', {'schedule': 'rings'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.SECONDARY))
else:
await schedule_week(message)
@bot.on.private_message(payload={'schedule': 'rings'})
async def schedule_rings(message: Message):
if datetime.date.today().weekday() == 0:
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=os.getcwd() + path_to_monday_jpg, peer_id=message.peer_id
)
now_day = 'на понедельник'
else:
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=os.getcwd() + path_to_other_days_jpg, peer_id=message.peer_id
)
now_day = ''
await message.answer(message=f'🔔 Расписание звонков{now_day}',
keyboard=Keyboard(one_time=True, inline=False)
.add(Text('🔄 Другой день', {'rings': 'day'}), color=KeyboardButtonColor.PRIMARY)
.row()
.add(Text('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.SECONDARY), attachment=doc)
await writing_to_file('rings_day')
@bot.on.private_message(payload={'rings': 'day'})
async def rings_day(message: Message):
if datetime.date.today().weekday() != 0:
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=os.getcwd() + path_to_monday_jpg, peer_id=message.peer_id
)
now_day = ' на понедельник'
else:
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=os.getcwd() + path_to_other_days_jpg, peer_id=message.peer_id
)
now_day = ''
await message.answer(message=f'🔔 Расписание звонков {now_day}', attachment=doc)
await logged_menu(message)
await writing_to_file('rings_another_day')
@bot.on.private_message(payload={'schedule': 'week'})
async def schedule_week(message: Message):
res = ''
data = {}
if await islogged(message.from_id):
user = (await db.get(message.from_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
ns = NetSchoolAPI(site)
await ns.login(sgo_login, sgo_password, school)
result = await ns.diary()
# Generating dict of diary
for days in result.schedule:
day = w_daya[days.day.weekday()]
data[day] = ''
lessons = days.lessons
for lesson in lessons:
subject = lesson.subject
data[day] += '\u2800' + subject + '\n81679am'
else:
for i in test_week.keys():
if i != 'Sunday':
data[eng_daya[i]] = ''
for lesson in test_week[i][1:-1]:
subject = lesson[:lesson.find(":")]
data[eng_daya[i]] += '\u2800' + subject.strip() + '\n81679am'
# Generating answer
if data != {}:
for i in data.keys():
data[i] = data[i].split('81679am')
for i in data.keys():
res += '\n📅 ' + i + '\n'
for num in range(len(data[i]) - 1):
res += str(num + 1) + ') ' + data[i][num]
await message.answer(res)
else:
await message.answer('💤 Нет уроков, отдыхай = )')
await logged_menu(message)
await writing_to_file('schedule_week')
@bot.on.private_message(payload={'report': 'parent'})
async def parent_report(message: Message):
user = (await db.get(message.from_id))[0]
sgo_login, sgo_password, output_type, site, school = user[2], user[3], user[4], user[7], user[8]
ns = NetSchoolAPI(site)
if await islogged(message.from_id):
term = int(message.text)
await ns.login(sgo_login, sgo_password, school)
report = await ns.parentReport(term=term)
await ns.logout()
else:
report = test_report
# Generating answer
if output_type == 'Изображение':
await message.answer(' 🖼 Генерируем отчет...')
path = create_report(report, message.from_id)
doc = await PhotoMessageUploader(bot.api).upload(
title='image.jpg', file_source=path, peer_id=message.peer_id
)
await message.answer(message='...', attachment=doc, keyboard=Keyboard(one_time=False, inline=False)
.add(Text('🧐 Посмотреть долги по предметам', {'menu': 'dept'}),
color=KeyboardButtonColor.NEGATIVE)
.row()
.add(Text('🏡 Назад в меню', {'logged': 'menu'}), color=KeyboardButtonColor.PRIMARY))
os.remove(path)
elif output_type == 'Текст':
result = f"🔘Общие:\n5️⃣: {report['total']['5']}\n4️⃣: {report['total']['4']}\n3️⃣: {report['total']['3']}\n2️⃣: " \
f"{report['total']['2']}\n〰️Средняя: {report['total']['average']}\n" \
f"🗒Средняя за четверть: {report['total']['average_term']}\n\n"
for subject in report['subjects'].keys():