/
Noriyki
/
VibeCodeBot
Обзор
Документация
Войти
/
Noriyki
/
VibeCodeBot
Код
Запросы
2
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/handlers/admin.py
179 строк
7 KB
Chelovechec
feat(backend): создание репозитория для работы с командами
26 фев 2026, 18:33
26 фев 2026, 18:33
edde799
Код
Авторство
О чём код?
from telebot import types from config import ADMIN_IDS from src.DB.repositories import team_repo, user_repo from src.DB.exeptions import TeamAlreadyExistException, TeamNotFoundException def register_admin_handlers(bot): """Обработчики действий администратора.""" @bot.message_handler(func=lambda m: m.text == "📨Рассылка") def broadcast(message): if message.from_user.id not in ADMIN_IDS: bot.send_message(message.chat.id, "⛔ У вас нет прав доступа") return bot.send_message(message.chat.id, "Введите текст для рассылки:") bot.register_next_step_handler(message, broadcast_next) def broadcast_next(message): text_to_send = message.text users = user_repo.get_all_users() bot.send_message(message.chat.id, f"▶ Начинаю рассылку ({len(users)} пользователей)...") sent = 0 blocked = 0 for user in users: user_id = user[0] try: bot.send_message(user_id, f"<b>{text_to_send}</b>", parse_mode="HTML") sent += 1 except Exception as e: blocked += 1 print(f"Ошибка отправки пользователю {user_id}: {e}") bot.send_message( message.chat.id, f"✔ Рассылка завершена!\n" f"📨 Отправлено: {sent}\n" f"⛔ Заблокировали: {blocked}" ) @bot.message_handler(func=lambda m: m.text == "🧮Статистика") def users_stats(message): users = user_repo.get_users_with_team() if not users: bot.send_message(message.chat.id, "Статистика пользователей:\nПользователей нет.") return teams = {} for username, tasks_done, team in users: if team not in teams: teams[team] = [] teams[team].append((username, tasks_done)) text = "🧮 **Статистика пользователей** (по командам)\n\n" for team_idx, (team, team_users) in enumerate(teams.items(), 1): text += f"**{team_idx}. `{team}`**\n" for user_idx, (username, tasks_done) in enumerate(team_users, 1): tasks_emoji = "⭐" if tasks_done > 0 else "➖" text += f" {user_idx}. **@{username}**: {tasks_emoji} `{tasks_done}` задач\n" text += "\n" bot.send_message(message.chat.id, text, parse_mode='Markdown') def manage_teams(message): keyboard = types.InlineKeyboardMarkup(row_width=1) keyboard.add( types.InlineKeyboardButton("➕ Добавить команду", callback_data="admin_add_team"), types.InlineKeyboardButton("🗑️ Удалить команду", callback_data="admin_remove_team"), types.InlineKeyboardButton("📋 Список команд", callback_data="admin_list_teams") ) bot.send_message(message.chat.id, "Управление командами:", reply_markup=keyboard) @bot.message_handler(func=lambda m: m.text == "🏗️ Управление командами") def handle_manage_teams(message): if message.from_user.id not in ADMIN_IDS: bot.send_message(message.chat.id, "⛔ У вас нет прав доступа") return manage_teams(message) @bot.callback_query_handler(func=lambda c: c.data == "admin_add_team") def handle_add_team(call): if call.from_user.id not in ADMIN_IDS: return bot.answer_callback_query(call.id) msg = bot.send_message(call.message.chat.id, "Введите название новой команды:") bot.register_next_step_handler(msg, process_new_team_name) def process_new_team_name(message): new_team = message.text.strip() if not new_team: bot.send_message(message.chat.id, "❌ Название команды не может быть пустым") return try: team_repo.add_team(new_team) bot.send_message(message.chat.id, f"✅ Команда '{new_team}' успешно добавлена!") except TeamAlreadyExistException: bot.send_message(message.chat.id, f"❌ Команда '{new_team}' уже существует") @bot.callback_query_handler(func=lambda c: c.data == "admin_list_teams") def handle_list_teams(call): if call.from_user.id not in ADMIN_IDS: return bot.answer_callback_query(call.id) teams = team_repo.get_all_teams() if not teams: bot.send_message(call.message.chat.id, "📋 Список команд пуст") else: teams_text = "📋 Список команд:\n\n" for i, team in enumerate(teams, 1): teams_text += f"{i}. {team}\n" bot.send_message(call.message.chat.id, teams_text) @bot.callback_query_handler(func=lambda c: c.data == "admin_remove_team") def handle_remove_team(call): if call.from_user.id not in ADMIN_IDS: return bot.answer_callback_query(call.id) teams = team_repo.get_all_teams() if not teams: bot.send_message(call.message.chat.id, "❌ Нет команд для удаления") return keyboard = types.InlineKeyboardMarkup(row_width=1) for team in teams: keyboard.add( types.InlineKeyboardButton( f"❌ {team}", callback_data=f"admin_remove_team_confirm:{team}" ) ) bot.send_message(call.message.chat.id, "Выберите команду для удаления:", reply_markup=keyboard) @bot.callback_query_handler(func=lambda c: c.data.startswith("admin_remove_team_confirm:")) def handle_remove_team_confirm(call): if call.from_user.id not in ADMIN_IDS: return _, team_to_remove = call.data.split(":") bot.answer_callback_query(call.id) try: team_repo.delete_team(team_to_remove) bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"✅ Команда '{team_to_remove}' удалена!" ) except TeamNotFoundException: bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text=f"❌ Команда '{team_to_remove}' не найдена" )