-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
527 lines (383 loc) · 17.9 KB
/
bot.py
File metadata and controls
527 lines (383 loc) · 17.9 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
import random
import asyncio
from datetime import datetime, timedelta
from typing import Optional
import uuid
from aiogram import Bot, Dispatcher, F
from aiogram.types import Message, CallbackQuery, InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.filters import Command, CommandObject
from aiogram.enums import ParseMode
from aiogram.exceptions import TelegramBadRequest
from config import BOT_TOKEN, ADMIN_IDS, DEFAULT_REGISTRATION_HOURS
from database import db, Queue, Participant, QueuePhase, ParticipantStatus
bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()
close_tasks: dict[str, asyncio.Task] = {}
# ========== УТИЛИТЫ ==========
def generate_queue_id() -> str:
return uuid.uuid4().hex[:8]
def mention_user(p: Participant) -> str:
if p.username:
return f"@{p.username}"
return f"[{p.full_name}](tg://user?id={p.user_id})"
def get_keyboard(queue: Queue, is_admin: bool = False) -> InlineKeyboardMarkup:
buttons = []
if queue.phase in (QueuePhase.REGISTRATION, QueuePhase.ADDITIONAL_REGISTRATION):
buttons.append([
InlineKeyboardButton(text="✋ Записаться", callback_data=f"join:{queue.id}"),
InlineKeyboardButton(text="🚪 Выйти", callback_data=f"leave:{queue.id}")
])
if queue.phase == QueuePhase.ACTIVE:
buttons.append([
InlineKeyboardButton(text="❌ Отказаться от места", callback_data=f"decline:{queue.id}")
])
buttons.append([
InlineKeyboardButton(text="📋 Показать список", callback_data=f"list:{queue.id}")
])
if is_admin and queue.phase == QueuePhase.ACTIVE:
buttons.append([
InlineKeyboardButton(text="🔄 Донабор", callback_data=f"additional:{queue.id}"),
InlineKeyboardButton(text="🔒 Закрыть", callback_data=f"close_final:{queue.id}")
])
return InlineKeyboardMarkup(inline_keyboard=buttons)
def format_message(queue: Queue, show_list: bool = False) -> str:
phase_text = {
QueuePhase.REGISTRATION: "🟢 Идёт запись",
QueuePhase.ACTIVE: "🟡 Запись закрыта",
QueuePhase.ADDITIONAL_REGISTRATION: "🟠 Донабор",
QueuePhase.CLOSED: "🔴 Закрыта"
}
if queue.phase in (QueuePhase.REGISTRATION, QueuePhase.ADDITIONAL_REGISTRATION):
# Режим записи — показываем записавшихся
participants = [p for p in db.get_participants(queue.id) if p.status != ParticipantStatus.DECLINED]
count = len(participants)
text = (
f"📋 **Очередь: {queue.name}**\n\n"
f"Статус: {phase_text[queue.phase]}\n"
f"Мест: {queue.main_slots} + {queue.reserve_slots} резерв\n"
f"Записалось: {count} чел.\n"
f"⏰ Закрытие: {queue.closes_at.strftime('%d.%m %H:%M')}"
)
if show_list and participants:
text += "\n\n**Записались:**\n"
for i, p in enumerate(participants, 1):
text += f"{i}. {p.full_name}\n"
else:
# Режим результатов
main_list = db.get_main_participants(queue.id)
reserve_list = db.get_reserve_participants(queue.id)
text = f"🎲 **Очередь: {queue.name}**\n\n"
text += f"Статус: {phase_text[queue.phase]}\n\n"
text += "**📌 Основной список:**\n"
if main_list:
for i, p in enumerate(main_list, 1):
icon = " ✅" if p.status == ParticipantStatus.PROMOTED else ""
text += f"{i}. {mention_user(p)}{icon}\n"
else:
text += "(пусто)\n"
if queue.reserve_slots > 0:
text += "\n**🔄 Резерв:**\n"
if reserve_list:
for i, p in enumerate(reserve_list, 1):
text += f"{i}. {mention_user(p)}\n"
else:
text += "(пусто)\n"
free_main = queue.main_slots - len(main_list)
if free_main > 0 and queue.phase != QueuePhase.CLOSED:
text += f"\n⚠️ **Свободно мест: {free_main}**"
return text
async def update_message(queue: Queue, show_list: bool = False):
try:
text = format_message(queue, show_list)
keyboard = get_keyboard(queue, is_admin=True)
await bot.edit_message_text(
chat_id=queue.chat_id,
message_id=queue.message_id,
text=text,
reply_markup=keyboard if queue.phase != QueuePhase.CLOSED else None,
parse_mode=ParseMode.MARKDOWN
)
except TelegramBadRequest:
pass
# ========== СОЗДАНИЕ ОЧЕРЕДИ ==========
@dp.message(Command("create"))
async def create_queue(message: Message, command: CommandObject):
chat_id = message.chat.id
user_id = message.from_user.id
if user_id not in ADMIN_IDS:
return await message.answer("⛔ Только админ может создавать очереди")
args = command.args.split() if command.args else []
if len(args) < 3:
return await message.answer(
"❌ **Формат:**\n"
"`/create <название> <мест> <резерв> [часов]`\n\n"
"**Пример:** `/create Матан 5 2`",
parse_mode=ParseMode.MARKDOWN
)
try:
name = args[0]
main_slots = int(args[1])
reserve_slots = int(args[2])
hours = float(args[3]) if len(args) > 3 else DEFAULT_REGISTRATION_HOURS
except ValueError:
return await message.answer("❌ Неверные параметры")
if main_slots < 1 or reserve_slots < 0 or hours <= 0:
return await message.answer("❌ Некорректные значения")
existing = db.find_queue_by_name(chat_id, name)
if existing:
return await message.answer(f"❌ Очередь '{name}' уже существует")
now = datetime.now()
queue = Queue(
id=generate_queue_id(),
name=name,
chat_id=chat_id,
message_id=None,
main_slots=main_slots,
reserve_slots=reserve_slots,
phase=QueuePhase.REGISTRATION,
created_at=now,
closes_at=now + timedelta(hours=hours)
)
db.create_queue(queue)
msg = await message.answer(
format_message(queue),
reply_markup=get_keyboard(queue),
parse_mode=ParseMode.MARKDOWN
)
queue.message_id = msg.message_id
db.update_queue(queue)
schedule_auto_close(queue)
try:
await message.delete()
except:
pass
def schedule_auto_close(queue: Queue):
delay = (queue.closes_at - datetime.now()).total_seconds()
if delay > 0:
task = asyncio.create_task(auto_close_queue(queue.id, delay))
close_tasks[queue.id] = task
async def auto_close_queue(queue_id: str, delay: float):
await asyncio.sleep(delay)
queue = db.get_queue(queue_id)
if queue and queue.phase == QueuePhase.REGISTRATION:
await finalize_registration(queue)
elif queue and queue.phase == QueuePhase.ADDITIONAL_REGISTRATION:
await finalize_additional(queue)
# ========== ЗАПИСЬ ==========
@dp.callback_query(F.data.startswith("join:"))
async def join_queue(callback: CallbackQuery):
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
if not queue:
return await callback.answer("❌ Очередь не найдена", show_alert=True)
if queue.phase not in (QueuePhase.REGISTRATION, QueuePhase.ADDITIONAL_REGISTRATION):
return await callback.answer("❌ Запись закрыта", show_alert=True)
user = callback.from_user
existing = db.get_participant(queue_id, user.id)
if existing and existing.status != ParticipantStatus.DECLINED:
return await callback.answer("✅ Вы уже записаны!", show_alert=True)
participant = Participant(
id=0,
queue_id=queue_id,
user_id=user.id,
username=user.username,
full_name=user.full_name,
position=None,
status=ParticipantStatus.PENDING,
joined_at=datetime.now()
)
db.add_participant(participant)
await update_message(queue)
count = db.count_participants(queue_id)
await callback.answer(f"✅ Вы записаны! Всего: {count}", show_alert=True)
@dp.callback_query(F.data.startswith("leave:"))
async def leave_queue(callback: CallbackQuery):
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
if not queue:
return await callback.answer("❌ Очередь не найдена", show_alert=True)
if queue.phase not in (QueuePhase.REGISTRATION, QueuePhase.ADDITIONAL_REGISTRATION):
return await callback.answer("❌ Используйте 'Отказаться от места'", show_alert=True)
if not db.remove_participant(queue_id, callback.from_user.id):
return await callback.answer("❌ Вы не записаны", show_alert=True)
await update_message(queue)
await callback.answer("🚪 Вы вышли из очереди", show_alert=True)
@dp.callback_query(F.data.startswith("list:"))
async def show_list(callback: CallbackQuery):
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
if not queue:
return await callback.answer("❌ Очередь не найдена", show_alert=True)
await update_message(queue, show_list=True)
await callback.answer()
# ========== ЗАКРЫТИЕ ЗАПИСИ ==========
@dp.message(Command("close"))
async def close_queue_command(message: Message, command: CommandObject):
chat_id = message.chat.id
user_id = message.from_user.id
if user_id not in ADMIN_IDS:
return await message.answer("⛔ Только админ")
if not command.args:
queues_list = db.get_active_queues(chat_id)
if not queues_list:
return await message.answer("❌ Нет активных очередей")
lines = ["**Активные очереди:**"]
for q in queues_list:
lines.append(f"• `{q.name}`")
return await message.answer("\n".join(lines), parse_mode=ParseMode.MARKDOWN)
name = command.args.strip()
queue = db.find_queue_by_name(chat_id, name) or db.get_queue(name)
if not queue or queue.chat_id != chat_id:
return await message.answer("❌ Очередь не найдена")
if queue.phase == QueuePhase.REGISTRATION:
await finalize_registration(queue)
elif queue.phase == QueuePhase.ADDITIONAL_REGISTRATION:
await finalize_additional(queue)
else:
return await message.answer("❌ Очередь уже закрыта для записи")
try:
await message.delete()
except:
pass
async def finalize_registration(queue: Queue):
if queue.id in close_tasks:
close_tasks[queue.id].cancel()
del close_tasks[queue.id]
participants = db.get_pending_participants(queue.id)
random.shuffle(participants)
for i, p in enumerate(participants):
if i < queue.main_slots:
status = ParticipantStatus.MAIN
elif i < queue.main_slots + queue.reserve_slots:
status = ParticipantStatus.RESERVE
else:
status = ParticipantStatus.WAITING
db.update_participant_status(queue.id, p.user_id, status, position=i + 1)
queue.phase = QueuePhase.ACTIVE
db.update_queue(queue)
await update_message(queue)
# ========== ОТКАЗ ОТ МЕСТА ==========
@dp.callback_query(F.data.startswith("decline:"))
async def decline_spot(callback: CallbackQuery):
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
user_id = callback.from_user.id
if not queue:
return await callback.answer("❌ Очередь не найдена", show_alert=True)
if queue.phase not in (QueuePhase.ACTIVE, QueuePhase.ADDITIONAL_REGISTRATION):
return await callback.answer("❌ Нельзя отказаться сейчас", show_alert=True)
participant = db.get_participant(queue_id, user_id)
if not participant:
return await callback.answer("❌ Вы не в очереди", show_alert=True)
if participant.status in (ParticipantStatus.DECLINED, ParticipantStatus.WAITING, ParticipantStatus.PENDING):
return await callback.answer("❌ Вы не в основном списке/резерве", show_alert=True)
was_main = participant.status in (ParticipantStatus.MAIN, ParticipantStatus.PROMOTED)
db.update_participant_status(queue_id, user_id, ParticipantStatus.DECLINED)
await callback.answer("✅ Вы отказались от места", show_alert=True)
if was_main:
await promote_reserve(queue)
await update_message(queue)
async def promote_reserve(queue: Queue):
reserve = db.get_first_reserve(queue.id)
if not reserve:
return
main_list = db.get_main_participants(queue.id)
new_position = len(main_list) + 1
db.update_participant_status(queue.id, reserve.user_id, ParticipantStatus.PROMOTED, position=new_position)
# Уведомление резервисту
try:
await bot.send_message(
reserve.user_id,
f"🎉 Вы продвинуты в основной список очереди **{queue.name}**!",
parse_mode=ParseMode.MARKDOWN
)
except:
pass
# ========== ДОНАБОР ==========
@dp.callback_query(F.data.startswith("additional:"))
async def start_additional(callback: CallbackQuery):
if callback.from_user.id not in ADMIN_IDS:
return await callback.answer("⛔ Только админ", show_alert=True)
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
if not queue or queue.phase != QueuePhase.ACTIVE:
return await callback.answer("❌ Донабор недоступен", show_alert=True)
main_list = db.get_main_participants(queue.id)
free_slots = queue.main_slots - len(main_list)
if free_slots <= 0:
return await callback.answer("✅ Все места заняты", show_alert=True)
queue.phase = QueuePhase.ADDITIONAL_REGISTRATION
queue.closes_at = datetime.now() + timedelta(hours=DEFAULT_REGISTRATION_HOURS)
db.update_queue(queue)
schedule_auto_close(queue)
await update_message(queue)
await callback.answer(f"🔄 Донабор открыт на {free_slots} мест", show_alert=True)
async def finalize_additional(queue: Queue):
if queue.id in close_tasks:
close_tasks[queue.id].cancel()
del close_tasks[queue.id]
pending = db.get_pending_participants(queue.id)
random.shuffle(pending)
main_list = db.get_main_participants(queue.id)
free_slots = queue.main_slots - len(main_list)
for i, p in enumerate(pending):
if i < free_slots:
db.update_participant_status(queue.id, p.user_id, ParticipantStatus.PROMOTED, position=len(main_list) + i + 1)
else:
db.update_participant_status(queue.id, p.user_id, ParticipantStatus.WAITING)
queue.phase = QueuePhase.ACTIVE
db.update_queue(queue)
await update_message(queue)
# ========== ЗАКРЫТИЕ ПОЛНОЕ ==========
@dp.callback_query(F.data.startswith("close_final:"))
async def close_final(callback: CallbackQuery):
if callback.from_user.id not in ADMIN_IDS:
return await callback.answer("⛔ Только админ", show_alert=True)
queue_id = callback.data.split(":")[1]
queue = db.get_queue(queue_id)
if not queue:
return await callback.answer("❌ Не найдена", show_alert=True)
queue.phase = QueuePhase.CLOSED
db.update_queue(queue)
await update_message(queue)
await callback.answer("🔒 Очередь закрыта", show_alert=True)
# ========== СЛУЖЕБНЫЕ ==========
@dp.message(Command("queues"))
async def list_queues(message: Message):
queues_list = db.get_active_queues(message.chat.id)
if not queues_list:
return await message.answer("📋 Нет активных очередей")
lines = ["**📋 Активные очереди:**"]
for q in queues_list:
count = db.count_participants(q.id)
lines.append(f"• **{q.name}** — {count} чел.")
await message.answer("\n".join(lines), parse_mode=ParseMode.MARKDOWN)
@dp.message(Command("help", "start"))
async def help_command(message: Message):
text = "**🎲 Бот для очередей**\n\n"
if message.from_user.id in ADMIN_IDS:
text += (
"`/create <имя> <мест> <резерв> [часов]`\n"
"`/close <имя>` — закрыть досрочно\n"
"`/queues` — список очередей\n\n"
"**Пример:** `/create Матан 5 2`"
)
else:
text += "Нажмите кнопку под сообщением очереди чтобы записаться."
await message.answer(text, parse_mode=ParseMode.MARKDOWN)
async def restore_timers():
for queue in db.get_registration_queues():
delay = (queue.closes_at - datetime.now()).total_seconds()
if delay > 0:
schedule_auto_close(queue)
else:
if queue.phase == QueuePhase.REGISTRATION:
await finalize_registration(queue)
elif queue.phase == QueuePhase.ADDITIONAL_REGISTRATION:
await finalize_additional(queue)
async def main():
print("Запуск бота...")
await restore_timers()
await dp.start_polling(bot)
if __name__ == "__main__":
asyncio.run(main())