-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
2218 lines (1905 loc) · 91.1 KB
/
bot.py
File metadata and controls
2218 lines (1905 loc) · 91.1 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
# Copyright NGGT.LightKeeper. All Rights Reserved.
import os
import django
from functools import wraps
import datetime
import re
import io
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment
# --- Django Setup ---
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'telegram_bot_django.settings')
django.setup()
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from settings.settings import BOT_TOKEN, NAME_BTN_BACK
from telegram_bot_db.models import (
TelegramUser, MessageHistory, Group, Student,
Lesson, AttendanceType, AttendanceJournal
)
from django.db.models import ProtectedError
# Check if BOT_TOKEN is provided. If not, the bot cannot start.
if not BOT_TOKEN:
raise ValueError("Bot token is not provided! Please set BOT_TOKEN in settings/settings.py")
# Initialize the bot using the token from settings.
bot = telebot.TeleBot(BOT_TOKEN)
# A dictionary to track the current state of each user's conversation.
# This is crucial for handling multi-step operations like adding a new student.
# Example: {'user_id': {'state': 'awaiting_group_name', 'data': {}}}
user_states = {}
# --- Decorators ---
def escape_markdown(text: str) -> str:
"""
Escapes characters that have a special meaning in Telegram's Markdown.
Args:
text: The text to escape.
Returns:
The escaped text, safe for sending in a Markdown-formatted message.
"""
if not text:
return ""
# A list of characters to escape for the legacy Markdown mode.
escape_chars = r'[_*`[]'
# Use re.sub to add a backslash before every special character.
return re.sub(f'({escape_chars})', r'\\\1', str(text))
def admin_required(func):
"""
Decorator to restrict access to a handler to bot administrators only.
It checks if the user sending the command is marked as an admin in the
database. If not, it sends an access denied message.
"""
@wraps(func)
def wrapper(m_or_c):
user_id = m_or_c.from_user.id
try:
user = TelegramUser.objects.get(user_id=user_id)
if not user.is_bot_admin:
error_text = "❌ You do not have sufficient rights to execute this command."
if isinstance(m_or_c, telebot.types.CallbackQuery):
bot.answer_callback_query(m_or_c.id, error_text, show_alert=True)
else:
bot.reply_to(m_or_c, error_text)
return
except TelegramUser.DoesNotExist:
error_text = "❌ Your user is not registered. Please use /start first."
if isinstance(m_or_c, telebot.types.CallbackQuery):
bot.answer_callback_query(m_or_c.id, error_text, show_alert=True)
else:
bot.reply_to(m_or_c, error_text)
return
return func(m_or_c)
return wrapper
def export_permission_required(func):
"""
Decorator that checks if a user has rights to export data.
Access is granted to bot administrators (`is_bot_admin`) or users with
the specific export permission (`is_export`).
"""
@wraps(func)
def wrapper(m_or_c):
user_id = m_or_c.from_user.id
try:
user = TelegramUser.objects.get(user_id=user_id)
# Grant access if the user is an admin OR has the export flag.
if not user.is_bot_admin and not user.is_export:
error_text = "❌ You do not have permission to export data."
if isinstance(m_or_c, telebot.types.CallbackQuery):
bot.answer_callback_query(m_or_c.id, error_text, show_alert=True)
else:
bot.reply_to(m_or_c, error_text)
return
except TelegramUser.DoesNotExist:
error_text = "❌ Your user is not registered. Please use /start first."
if isinstance(m_or_c, telebot.types.CallbackQuery):
bot.answer_callback_query(m_or_c.id, error_text, show_alert=True)
else:
bot.reply_to(m_or_c, error_text)
return
return func(m_or_c)
return wrapper
# --- Command Handlers ---
@bot.message_handler(commands=['start'])
def handle_start(message):
"""
Handles the /start command.
Registers a new user in the database or updates their information if they
already exist. Sends a welcome message.
"""
user_data = message.from_user
# get_or_create is an efficient way to handle user registration.
user, created = TelegramUser.objects.get_or_create(
user_id=user_data.id,
defaults={
'first_name': user_data.first_name,
'last_name': user_data.last_name,
'username': user_data.username,
}
)
if created:
welcome_text = (f"Hello, {user.first_name}! 👋\n\n"
"Welcome to the attendance tracking bot. I have registered you in the system.\n"
"You can view your profile information using the /profile command.")
else:
# If the user already exists, update their data in case it changed in Telegram.
user.first_name = user_data.first_name
user.last_name = user_data.last_name
user.username = user_data.username
user.save()
welcome_text = (f"Welcome back, {user.first_name}! 👋\n\n"
"You are already registered. Use /profile to view your data or /menu to access admin commands.")
bot.reply_to(message, welcome_text)
@bot.message_handler(commands=['profile'])
def handle_profile(message):
"""
Handles the /profile command.
Displays the user's registered information, such as name, username, and
admin status.
"""
try:
user = TelegramUser.objects.get(user_id=message.from_user.id)
is_admin_str = "Yes" if user.is_bot_admin else "No"
if user.is_export:
is_export_str = "Yes"
elif user.is_bot_admin:
is_export_str = "Yes"
else:
is_export_str = "No"
# Escape user-provided data to prevent Markdown parsing errors.
first_name = escape_markdown(user.first_name)
last_name = escape_markdown(user.last_name or 'Not specified')
username = escape_markdown(user.username or 'Not specified')
profile_text = (
f"👤 **Your Profile**\n\n"
f"**Telegram ID:** `{user.user_id}`\n"
f"**First Name:** {first_name}\n"
f"**Last Name:** {last_name}\n"
f"**Username:** @{username}\n"
f"**Bot Administrator:** {is_admin_str}\n"
f"**Can Export Data:** {is_export_str}\n"
f"**Registered on:** {user.created_at.strftime('%Y-%m-%d %H:%M:%S')}"
)
bot.reply_to(message, profile_text, parse_mode='Markdown')
except TelegramUser.DoesNotExist:
bot.reply_to(message, "You are not registered yet. Please use the /start command first.")
def send_admin_menu(chat_id: int, message_id: int = None):
"""
Sends or edits the main administrative menu.
This menu provides buttons to access different management sections.
Args:
chat_id: The ID of the chat to send the menu to.
message_id: The ID of the message to edit. If None, a new message is sent.
"""
markup = InlineKeyboardMarkup(row_width=2)
buttons = [
InlineKeyboardButton("Groups", callback_data="manage_groups"),
InlineKeyboardButton("Students", callback_data="manage_students"),
InlineKeyboardButton("Lessons", callback_data="manage_lessons"),
InlineKeyboardButton("Attendance Types", callback_data="manage_attendance_types"),
InlineKeyboardButton("Attendance Journal", callback_data="manage_journal"),
]
markup.add(*buttons)
text = "Welcome to the Admin Menu. Please choose a section to manage:"
if message_id:
try:
# Edit the existing message to avoid cluttering the chat.
bot.edit_message_text(text, chat_id, message_id, reply_markup=markup)
except telebot.apihelper.ApiTelegramException:
# If editing fails (e.g., message is too old), send a new one.
bot.send_message(chat_id, text, reply_markup=markup)
else:
bot.send_message(chat_id, text, reply_markup=markup)
@bot.message_handler(commands=['menu'])
@admin_required
def handle_menu_command(message):
"""
Handles the /menu command, which displays the admin menu.
"""
send_admin_menu(message.chat.id)
@bot.callback_query_handler(func=lambda call: call.data == 'main_menu')
@admin_required
def main_menu_callback(call):
"""
Handles the 'main_menu' callback, which is used by "Back" buttons
to return to the main admin menu.
"""
# Clear any saved page numbers when returning to the main menu.
state = user_states.get(call.from_user.id, {})
for key in list(state.keys()):
if key.endswith('_page'):
state.pop(key, None)
send_admin_menu(call.message.chat.id, call.message.message_id)
# --- Export to XLSX ---
def get_groups_for_export_markup(page: int = 1) -> InlineKeyboardMarkup:
"""
Creates an inline keyboard for selecting a group to export, with pagination.
Args:
page: The current page number for pagination.
Returns:
An InlineKeyboardMarkup object with group buttons.
"""
markup = InlineKeyboardMarkup()
groups = Group.objects.order_by('name')
# Paginate the results to keep the keyboard from becoming too long.
page_size = 5
start_index = (page - 1) * page_size
end_index = start_index + page_size
paginated_groups = groups[start_index:end_index]
for group in paginated_groups:
markup.add(InlineKeyboardButton(group.name, callback_data=f"export_select_group_{group.id}"))
# Add pagination buttons if necessary.
row = []
if start_index > 0:
row.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"export_groups_page_{page-1}"))
if end_index < groups.count():
row.append(InlineKeyboardButton("Next ➡️", callback_data=f"export_groups_page_{page+1}"))
if row:
markup.row(*row)
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data="main_menu"))
return markup
@bot.message_handler(commands=['export'])
@export_permission_required
def handle_export(message):
"""
Starts the process of exporting attendance data to an XLSX file.
It begins by asking the admin to select a group.
"""
markup = get_groups_for_export_markup()
bot.send_message(message.chat.id, "Select a group to export attendance data:", reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.startswith('export_groups_page_'))
@export_permission_required
def export_groups_page_callback(call):
"""Handles pagination for the group selection list during export."""
page = int(call.data.split('_')[-1])
markup = get_groups_for_export_markup(page)
bot.edit_message_reply_markup(
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('export_select_group_'))
@export_permission_required
def export_select_group_callback(call):
"""
Handles the selection of a group for export and prompts the user for
the start date of the reporting period.
"""
group_id = int(call.data.split('_')[-1])
user_id = call.from_user.id
# Set the user's state to await date input.
user_states[user_id] = {'state': 'awaiting_export_start_date', 'group_id': group_id}
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("❌ Cancel", callback_data="main_menu"))
bot.edit_message_text(
"Please enter the start date for the report (e.g., YYYY-MM-DD):",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
# --- State-related helpers ---
def clear_user_state(user_id: int):
"""
Clears the state for a given user, ending any multi-step conversation.
Args:
user_id: The ID of the user whose state should be cleared.
"""
user_states.pop(user_id, None)
def generate_attendance_report(group_id: int, start_date: datetime.date, end_date: datetime.date):
"""
Generates an XLSX report of student attendance for a specific group and
date range.
Args:
group_id: The ID of the group to generate the report for.
start_date: The start date of the reporting period.
end_date: The end date of the reporting period.
Returns:
A tuple containing the file stream (BytesIO) and the suggested filename.
"""
group = Group.objects.get(id=group_id)
students = Student.objects.filter(group=group).order_by('last_name', 'first_name')
lessons = Lesson.objects.filter(
group=group,
lesson_date__range=[start_date, end_date]
).order_by('lesson_date', 'lesson_time')
# Create a workbook and select the active worksheet
wb = Workbook()
ws = wb.active
ws.title = f"Attendance_{group.name}"
# --- Header Formatting ---
header_font = Font(bold=True)
center_alignment = Alignment(horizontal='center', vertical='center')
# --- Populate Headers ---
# Set width for the first column (student names)
ws.column_dimensions['A'].width = 30
# Populate lesson headers (date and topic)
for col_idx, lesson in enumerate(lessons, start=2):
# Row 1: Date
date_cell = ws.cell(row=1, column=col_idx, value=lesson.lesson_date.strftime('%d.%m.%Y'))
date_cell.font = header_font
date_cell.alignment = center_alignment
# Row 2: Lesson Topic
topic_cell = ws.cell(row=2, column=col_idx, value=lesson.topic)
topic_cell.font = header_font
topic_cell.alignment = center_alignment
ws.column_dimensions[chr(65 + col_idx - 1)].width = 20 # Adjust column width for readability
# --- Populate Student Data ---
# Create a map of student IDs to row numbers for efficient cell access.
student_row_map = {student.id: i for i, student in enumerate(students, start=3)}
for student_id, row_idx in student_row_map.items():
student = Student.objects.get(id=student_id)
ws.cell(row=row_idx, column=1, value=f"{student.last_name} {student.first_name} {student.patronymic or ''}".strip())
# --- Populate Attendance Data ---
# Create a map of lesson IDs to column numbers.
lesson_col_map = {lesson.id: i for i, lesson in enumerate(lessons, start=2)}
attendance_records = AttendanceJournal.objects.filter(
lesson__in=lessons,
student__in=students
).select_related('status')
# Create a dictionary for quick lookups of attendance status.
attendance_map = {}
for record in attendance_records:
attendance_map[(record.student_id, record.lesson_id)] = record.status.name
# Fill the grid with attendance statuses.
for student in students:
for lesson in lessons:
row_idx = student_row_map[student.id]
col_idx = lesson_col_map[lesson.id]
status = attendance_map.get((student.id, lesson.id), "+") # Default to "+" if not found
cell = ws.cell(row=row_idx, column=col_idx, value=status)
cell.alignment = center_alignment
# Save the workbook to a BytesIO stream to be sent as a file.
file_stream = io.BytesIO()
wb.save(file_stream)
file_stream.seek(0)
return file_stream, f"attendance_{group.name}_{start_date}_to_{end_date}.xlsx"
# --- Group Management ---
def get_groups_markup(page: int = 1) -> InlineKeyboardMarkup:
"""
Creates an inline keyboard for the group list, with pagination.
"""
markup = InlineKeyboardMarkup()
groups = Group.objects.order_by('name')
page_size = 5
start_index = (page - 1) * page_size
end_index = start_index + page_size
paginated_groups = groups[start_index:end_index]
for group in paginated_groups:
# Pass the current page number in the callback to remember it.
markup.add(InlineKeyboardButton(group.name, callback_data=f"view_group_{group.id}_{page}"))
row = []
if start_index > 0:
row.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"groups_page_{page-1}"))
if end_index < groups.count():
row.append(InlineKeyboardButton("Next ➡️", callback_data=f"groups_page_{page+1}"))
if row:
markup.row(*row)
markup.add(InlineKeyboardButton("➕ Add New Group", callback_data="add_group"))
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data="main_menu"))
return markup
@bot.callback_query_handler(func=lambda call: call.data == 'manage_groups' or call.data == 'back_to_groups')
@admin_required
def manage_groups_callback(call):
"""Displays the list of groups for management."""
user_id = call.from_user.id
state = user_states.get(user_id, {})
page = 1
# If returning from a group view, use the saved page number.
if call.data == 'back_to_groups':
page = state.get('last_groups_page', 1)
# Otherwise, starting from the main menu, clear any saved page.
elif user_id in user_states:
user_states[user_id].pop('last_groups_page', None)
markup = get_groups_markup(page=page)
try:
bot.edit_message_text(
"📚 Manage Groups",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
except telebot.apihelper.ApiTelegramException:
bot.send_message(call.message.chat.id, "📚 Manage Groups", reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.startswith('groups_page_'))
@admin_required
def groups_page_callback(call):
"""Handles pagination for the group list."""
page = int(call.data.split('_')[-1])
markup = get_groups_markup(page)
bot.edit_message_reply_markup(
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data == 'add_group')
@admin_required
def add_group_callback(call):
"""Prompts the user to enter a name for a new group."""
user_id = call.from_user.id
user_states[user_id] = {'state': 'awaiting_group_name'}
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("❌ Cancel", callback_data="back_to_groups"))
bot.edit_message_text(
"Please enter the name for the new group:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('view_group_'))
@admin_required
def view_group_callback(call):
"""Displays details for a specific group and options to edit or delete."""
parts = call.data.split('_')
group_id = int(parts[2])
page = int(parts[3])
user_id = call.from_user.id
# Store the page number so we can return to it.
if user_id not in user_states:
user_states[user_id] = {}
user_states[user_id]['last_groups_page'] = page
try:
group = Group.objects.select_related('default_attendance_status').get(id=group_id)
default_status_name = group.default_attendance_status.name if group.default_attendance_status else "Not specified"
text = (f"**Group:** {group.name}\n"
f"**Default Status:** {default_status_name}\n\n"
f"Select an action:")
markup = InlineKeyboardMarkup(row_width=2)
markup.add(InlineKeyboardButton("✏️ Edit Name", callback_data=f"edit_group_{group_id}"))
markup.add(InlineKeyboardButton("🏷️ Set Default Status", callback_data=f"set_default_status_{group_id}"))
markup.add(InlineKeyboardButton("🗑 Delete Group", callback_data=f"delete_group_{group_id}"))
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data="back_to_groups"))
bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
except Group.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Group not found.", show_alert=True)
manage_groups_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('set_default_status_'))
@admin_required
def set_default_status_callback(call):
"""Displays a list of attendance types to set as the default for a group."""
group_id = int(call.data.split('_')[-1])
try:
group = Group.objects.get(id=group_id)
attendance_types = AttendanceType.objects.all()
markup = InlineKeyboardMarkup(row_width=1)
for att_type in attendance_types:
markup.add(InlineKeyboardButton(att_type.name, callback_data=f"confirm_set_default_status_{group_id}_{att_type.id}"))
markup.add(InlineKeyboardButton("🗑️ Remove Default Status", callback_data=f"confirm_set_default_status_{group_id}_none"))
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data=f"view_group_{group_id}"))
bot.edit_message_text(
f"Select the default attendance status for group **{group.name}**:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup,
parse_mode='Markdown'
)
except Group.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Group not found.", show_alert=True)
manage_groups_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('confirm_set_default_status_'))
@admin_required
def confirm_set_default_status_callback(call):
"""Sets or removes the default attendance status for a group."""
parts = call.data.split('_')
group_id = int(parts[4])
status_id_str = parts[5]
try:
group = Group.objects.get(id=group_id)
if status_id_str == 'none':
group.default_attendance_status = None
bot.answer_callback_query(call.id, "✅ Default status removed.")
else:
status_id = int(status_id_str)
attendance_type = AttendanceType.objects.get(id=status_id)
group.default_attendance_status = attendance_type
bot.answer_callback_query(call.id, f"✅ Default status set to '{attendance_type.name}'.")
group.save()
# Go back to the group view to show the change.
call.data = f"view_group_{group_id}"
view_group_callback(call)
except (Group.DoesNotExist, AttendanceType.DoesNotExist):
bot.answer_callback_query(call.id, "Error: Group or Status not found.", show_alert=True)
manage_groups_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('edit_group_'))
@admin_required
def edit_group_callback(call):
"""Prompts the user to enter a new name for the group."""
group_id = int(call.data.split('_')[-1])
user_id = call.from_user.id
user_states[user_id] = {'state': 'awaiting_group_name_edit', 'group_id': group_id}
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("❌ Cancel", callback_data=f"view_group_{group_id}"))
bot.edit_message_text(
"Please enter the new name for the group:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('delete_group_'))
@admin_required
def delete_group_callback(call):
"""Asks for confirmation before deleting a group."""
group_id = int(call.data.split('_')[-1])
try:
group = Group.objects.get(id=group_id)
text = f"⚠️ Are you sure you want to delete the group **{group.name}**? This action cannot be undone."
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("✅ Yes, Delete", callback_data=f"confirm_delete_group_{group_id}"))
markup.add(InlineKeyboardButton("❌ No, Cancel", callback_data=f"view_group_{group_id}"))
bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
except Group.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Group not found.", show_alert=True)
manage_groups_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('confirm_delete_group_'))
@admin_required
def confirm_delete_group_callback(call):
"""Deletes the group from the database after confirmation."""
group_id = int(call.data.split('_')[-1])
try:
group = Group.objects.get(id=group_id)
group_name = group.name
group.delete()
bot.answer_callback_query(call.id, f"Group '{group_name}' has been deleted.")
manage_groups_callback(call)
except Group.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Group not found.", show_alert=True)
manage_groups_callback(call)
except ProtectedError:
# This occurs if the group has foreign key relations (e.g., students).
bot.answer_callback_query(
call.id,
"This group cannot be deleted because it has students or lessons associated with it.",
show_alert=True
)
# Return to the group view.
call.data = f"view_group_{group_id}"
view_group_callback(call)
# --- Student Management ---
def get_student_groups_markup(page: int = 1) -> InlineKeyboardMarkup:
"""
Creates an inline keyboard for selecting a group to manage its students.
"""
markup = InlineKeyboardMarkup()
groups = Group.objects.order_by('name')
page_size = 5
start_index = (page - 1) * page_size
end_index = start_index + page_size
paginated_groups = groups[start_index:end_index]
for group in paginated_groups:
markup.add(InlineKeyboardButton(group.name, callback_data=f"student_manage_group_{group.id}_{page}"))
row = []
if start_index > 0:
row.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"student_group_list_page_{page-1}"))
if end_index < groups.count():
row.append(InlineKeyboardButton("Next ➡️", callback_data=f"student_group_list_page_{page+1}"))
if row:
markup.row(*row)
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data="main_menu"))
return markup
@bot.callback_query_handler(func=lambda call: call.data.startswith('student_group_list_page_'))
@admin_required
def student_group_list_page_callback(call):
"""Paginates through the group list for student management."""
page = int(call.data.split('_')[-1])
markup = get_student_groups_markup(page)
bot.edit_message_reply_markup(
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
def get_students_for_group_markup(group_id: int, page: int = 1) -> InlineKeyboardMarkup:
"""
Creates an inline keyboard for the student list of a specific group, with pagination.
"""
markup = InlineKeyboardMarkup()
students = Student.objects.filter(group_id=group_id).select_related('group').order_by('last_name', 'first_name')
page_size = 5
start_index = (page - 1) * page_size
end_index = start_index + page_size
paginated_students = students[start_index:end_index]
for student in paginated_students:
markup.add(InlineKeyboardButton(f"{student.last_name} {student.first_name} {student.patronymic or ''}", callback_data=f"view_student_{student.id}_{page}"))
row = []
if start_index > 0:
row.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"students_for_group_page_{group_id}_{page-1}"))
if end_index < students.count():
row.append(InlineKeyboardButton("Next ➡️", callback_data=f"students_for_group_page_{group_id}_{page+1}"))
if row:
markup.row(*row)
markup.add(InlineKeyboardButton("➕ Add New Student", callback_data=f"add_student_{group_id}"))
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data="manage_students")) # Back to group list
return markup
@bot.callback_query_handler(func=lambda call: call.data == 'manage_students')
@admin_required
def manage_students_callback(call):
"""
Displays a list of groups to choose from for student management.
This is the main entry point for the "Manage Students" section.
"""
user_id = call.from_user.id
state = user_states.get(user_id, {})
# When coming from a student list, restore the group page.
page = state.get('last_student_groups_page', 1)
# Clear the inner list's page to ensure it starts from 1.
if user_id in user_states:
user_states[user_id].pop('last_students_for_group_page', None)
markup = get_student_groups_markup(page=page)
bot.edit_message_text(
"Please select a group to manage its students:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('student_manage_group_'))
@admin_required
def select_group_for_student_management_callback(call):
"""
Displays the list of students for the selected group.
This handler is entered in two ways:
1. From the group list: callback is `student_manage_group_{group_id}_{page}`.
- The group list page is saved.
- The student list is shown from page 1.
2. From a student view ('Back' button): callback is `student_manage_group_{group_id}`.
- The student list page is restored from the user's state.
"""
parts = call.data.split('_')
group_id = int(parts[3])
user_id = call.from_user.id
state = user_states.get(user_id, {})
page_to_show = 1
# Case 1: Coming from the group list.
if len(parts) > 4:
group_list_page = int(parts[4])
if user_id not in user_states:
user_states[user_id] = {}
user_states[user_id]['last_student_groups_page'] = group_list_page
# Case 2: Coming back from a student view.
else:
page_to_show = state.get('last_students_for_group_page', 1)
markup = get_students_for_group_markup(group_id=group_id, page=page_to_show)
try:
bot.edit_message_text(
"🧑🎓 Manage Students",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
except telebot.apihelper.ApiTelegramException:
bot.send_message(call.message.chat.id, "🧑🎓 Manage Students", reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.startswith('students_for_group_page_'))
@admin_required
def students_for_group_page_callback(call):
"""Handles pagination for the student list within a group."""
parts = call.data.split('_')
group_id = int(parts[4])
page = int(parts[5])
markup = get_students_for_group_markup(group_id, page)
bot.edit_message_reply_markup(
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('add_student_'))
@admin_required
def add_student_callback(call):
"""Starts the multi-step process of adding a new student to a specific group."""
group_id = int(call.data.split('_')[-1])
user_id = call.from_user.id
user_states[user_id] = {'state': 'awaiting_student_lastname', 'data': {'group_id': group_id}}
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("❌ Cancel", callback_data=f"student_manage_group_{group_id}"))
bot.edit_message_text(
"Please enter the student's **last name**:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup,
parse_mode='Markdown'
)
def get_group_selection_markup(page: int = 1, action_type: str = "add", student_id: int = None, user_id: int = None) -> InlineKeyboardMarkup:
"""
Creates a keyboard for selecting a group, used when adding or editing a student.
"""
markup = InlineKeyboardMarkup()
groups = Group.objects.order_by('name')
page_size = 5
start_index = (page - 1) * page_size
end_index = start_index + page_size
paginated_groups = groups[start_index:end_index]
for group in paginated_groups:
if action_type == "add":
# This part of the logic is now handled by the new student creation flow.
# We keep it for the edit flow.
callback_data = f"select_student_group_{group.id}"
else: # edit
callback_data = f"select_student_group_edit_{group.id}_{student_id}"
markup.add(InlineKeyboardButton(group.name, callback_data=callback_data))
row = []
if action_type == "add":
page_cb = "student_group_page_"
# The cancel callback should go back to the group's student list.
group_id = user_states.get(user_id, {}).get('data', {}).get('group_id')
cancel_cb = f"student_manage_group_{group_id}"
else:
page_cb = f"student_group_page_edit_{student_id}_"
cancel_cb = f"edit_student_{student_id}"
if start_index > 0:
row.append(InlineKeyboardButton("⬅️ Prev", callback_data=f"{page_cb}{page-1}"))
if end_index < groups.count():
row.append(InlineKeyboardButton("Next ➡️", callback_data=f"{page_cb}{page+1}"))
if row:
markup.row(*row)
markup.add(InlineKeyboardButton("❌ Cancel", callback_data=cancel_cb))
return markup
@bot.callback_query_handler(func=lambda call: call.data.startswith('student_group_page_'))
@admin_required
def student_group_page_callback(call):
"""Paginates through the group selection list when editing a student."""
user_id = call.from_user.id
parts = call.data.split('_')
action_type = "edit" # This handler is now only for editing
student_id = int(parts[4])
page = int(parts[5])
markup = get_group_selection_markup(page, "edit", student_id, user_id)
bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id, reply_markup=markup)
@bot.callback_query_handler(func=lambda call: call.data.startswith('select_student_group_edit_'))
@admin_required
def select_student_group_edit_callback(call):
"""Handles changing a student's group."""
parts = call.data.split('_')
group_id = int(parts[4])
student_id = int(parts[5])
try:
student = Student.objects.get(id=student_id)
group = Group.objects.get(id=group_id)
student.group = group
student.save()
bot.answer_callback_query(call.id, "✅ Student's group updated.")
# Go back to the student view.
call.data = f"view_student_{student_id}"
view_student_callback(call)
except (Student.DoesNotExist, Group.DoesNotExist):
bot.answer_callback_query(call.id, "Error updating student.", show_alert=True)
call.data = 'manage_students'
manage_students_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('view_student_'))
@admin_required
def view_student_callback(call):
"""Displays details for a specific student."""
parts = call.data.split('_')
student_id = int(parts[2])
page = int(parts[3])
user_id = call.from_user.id
# Store the student list page number.
if user_id not in user_states:
user_states[user_id] = {}
user_states[user_id]['last_students_for_group_page'] = page
try:
student = Student.objects.select_related('group').get(id=student_id)
text = (
f"🧑🎓 **Student Profile**\n\n"
f"**Last Name:** {student.last_name}\n"
f"**First Name:** {student.first_name}\n"
f"**Patronymic:** {student.patronymic or 'Not specified'}\n"
f"**Group:** {student.group.name}"
)
markup = InlineKeyboardMarkup(row_width=1)
markup.add(InlineKeyboardButton("✏️ Edit Student", callback_data=f"edit_student_{student_id}"))
markup.add(InlineKeyboardButton("🗑 Delete Student", callback_data=f"delete_student_{student_id}"))
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data=f"student_manage_group_{student.group.id}"))
bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
except Student.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Student not found.", show_alert=True)
manage_students_callback(call)
@bot.callback_query_handler(func=lambda call: call.data.startswith('edit_student_'))
@admin_required
def edit_student_callback(call):
"""Shows options for editing a student's details."""
student_id = int(call.data.split('_')[-1])
markup = InlineKeyboardMarkup(row_width=2)
markup.add(
InlineKeyboardButton("Last Name", callback_data=f"edit_student_field_lastname_{student_id}"),
InlineKeyboardButton("First Name", callback_data=f"edit_student_field_firstname_{student_id}")
)
markup.add(
InlineKeyboardButton("Patronymic", callback_data=f"edit_student_field_patronymic_{student_id}"),
InlineKeyboardButton("Group", callback_data=f"edit_student_field_group_{student_id}")
)
markup.add(InlineKeyboardButton(NAME_BTN_BACK, callback_data=f"view_student_{student_id}"))
bot.edit_message_text(
"Which field do you want to edit?",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('edit_student_field_'))
@admin_required
def edit_student_field_callback(call):
"""Handles editing a specific field of a student's profile."""
parts = call.data.split('_')
field = parts[3]
student_id = int(parts[4])
user_id = call.from_user.id
user_states[user_id] = {'state': f'awaiting_student_{field}_edit', 'student_id': student_id}
if field == 'group':
markup = get_group_selection_markup(1, "edit", student_id, user_id)
bot.edit_message_text(
"Select the new group for the student:",
call.message.chat.id,
call.message.message_id,
reply_markup=markup
)
else:
field_name_map = {
'lastname': 'last name',
'firstname': 'first name',
'patronymic': 'patronymic'
}
prompt = f"Please enter the new **{field_name_map[field]}**:"
markup = InlineKeyboardMarkup().add(InlineKeyboardButton("❌ Cancel", callback_data=f"edit_student_{student_id}"))
bot.edit_message_text(
prompt,
call.message.chat.id,
call.message.message_id,
reply_markup=markup,
parse_mode='Markdown'
)
@bot.callback_query_handler(func=lambda call: call.data.startswith('delete_student_'))
@admin_required
def delete_student_callback(call):
"""Asks for confirmation before deleting a student."""
student_id = int(call.data.split('_')[-1])
try:
student = Student.objects.get(id=student_id)
text = f"⚠️ Are you sure you want to delete the student **{student.last_name} {student.first_name}**? This action cannot be undone."
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton("✅ Yes, Delete", callback_data=f"confirm_delete_student_{student_id}"))
markup.add(InlineKeyboardButton("❌ No, Cancel", callback_data=f"view_student_{student_id}"))
bot.edit_message_text(text, call.message.chat.id, call.message.message_id, reply_markup=markup, parse_mode='Markdown')
except Student.DoesNotExist:
bot.answer_callback_query(call.id, "Error: Student not found.", show_alert=True)