import sqlite3 import telebot import telezab from backend_locks import db_lock, bot from bot_database import get_admins, is_whitelisted, format_regions_list, get_sorted_regions, log_user_event, \ get_user_subscribed_regions from config import DB_PATH from telezab import handle_my_subscriptions_button, handle_active_regions_button, handle_notification_mode_button from utilities.telegram_utilities import show_main_menu, show_settings_menu def handle_main_menu(message, chat_id, text): """Обработка команд в главном меню.""" if text == 'Регистрация': telezab.state.set_state(chat_id, "REGISTRATION") telezab.handle_register(message) elif text == 'Настройки': telezab.state.set_state(chat_id, "SETTINGS_MENU") telezab.show_settings_menu(chat_id) elif text == 'Помощь': telezab.handle_help(message) elif text == 'Активные события': telezab.handle_active_triggers(message) else: bot.send_message(chat_id, "Команда не распознана.") show_main_menu(chat_id) def handle_settings_menu(message, chat_id, text): """Обработка команд в меню настроек.""" admins_list = get_admins() if text.lower() == 'подписаться': telezab.state.set_state(chat_id, "SUBSCRIBE") handle_subscribe_button(message) elif text.lower() == 'отписаться': telezab.state.set_state(chat_id, "UNSUBSCRIBE") handle_unsubscribe_button(message) elif text.lower() == 'мои подписки': handle_my_subscriptions_button(message) elif text.lower() == 'активные регионы': handle_active_regions_button(message) elif text.lower() == "режим уведомлений": handle_notification_mode_button(message) elif text.lower() == 'назад': telezab.state.set_state(chat_id, "MAIN_MENU") show_main_menu(chat_id) else: bot.send_message(chat_id, "Команда не распознана.") show_settings_menu(chat_id) def handle_subscribe_button(message): chat_id = message.chat.id if not is_whitelisted(chat_id): bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.") return username = message.from_user.username if username: username = f"@{username}" else: username = "N/A" regions_list = format_regions_list(get_sorted_regions()) markup = telebot.types.InlineKeyboardMarkup() markup.add(telebot.types.InlineKeyboardButton(text="Отмена", callback_data=f"cancel_action")) bot.send_message(chat_id, f"Отправьте номера регионов через запятую:\n{regions_list}\n", reply_markup=markup) bot.register_next_step_handler_by_chat_id(chat_id, process_subscription_button, chat_id, username) def process_subscription_button(message, chat_id, username): subbed_regions = [] invalid_regions = [] if message.text.lower() == 'отмена': bot.send_message(chat_id, "Действие отменено.") telezab.state.set_state(chat_id, "SETTINGS_MENU") return show_settings_menu(chat_id) if not all(part.strip().isdigit() for part in message.text.split(',')): markup = telebot.types.InlineKeyboardMarkup() markup.add(telebot.types.InlineKeyboardButton(text="Отмена", callback_data=f"cancel_action")) bot.send_message(chat_id, "Неверный формат данных. Введите номер или номера регионов через запятую.", reply_markup=markup) bot.register_next_step_handler_by_chat_id(chat_id, process_subscription_button, chat_id, username) return region_ids = message.text.split(',') valid_region_ids = [region[0] for region in get_sorted_regions()] with db_lock: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() for region_id in region_ids: region_id = region_id.strip() if region_id not in valid_region_ids: invalid_regions.append(region_id) continue cursor.execute( 'INSERT OR IGNORE INTO subscriptions (chat_id, region_id, username, active) VALUES (?, ?, ?, TRUE)', (chat_id, region_id, username)) if cursor.rowcount == 0: cursor.execute('UPDATE subscriptions SET active = TRUE WHERE chat_id = ? AND region_id = ?', (chat_id, region_id)) subbed_regions.append(region_id) conn.commit() if len(invalid_regions) > 0: bot.send_message(chat_id, f"Регион с ID {', '.join(invalid_regions)} не существует. Введите корректные номера или 'отмена'.") bot.send_message(chat_id, f"Подписка на регионы: {', '.join(subbed_regions)} оформлена.") log_user_event(chat_id, username, f"Subscribed to regions: {', '.join(subbed_regions)}") telezab.state.set_state(chat_id, "SETTINGS_MENU") show_settings_menu(chat_id) def handle_unsubscribe_button(message): chat_id = message.chat.id if not is_whitelisted(chat_id): bot.send_message(chat_id, "Вы не авторизованы для использования этого бота.") telebot.logger.info(f"Unauthorized access attempt by {chat_id}") telezab.state.set_state(chat_id, "REGISTRATION") return show_main_menu(chat_id) username = message.from_user.username if username: username = f"@{username}" else: username = "N/A" # Получаем список подписок пользователя user_regions = get_user_subscribed_regions(chat_id) if not user_regions: bot.send_message(chat_id, "Вы не подписаны ни на один регион.") telezab.state.set_state(chat_id, "SETTINGS_MENU") return show_settings_menu(chat_id) regions_list = format_regions_list(user_regions) markup = telebot.types.InlineKeyboardMarkup() markup.add(telebot.types.InlineKeyboardButton(text="Отмена", callback_data=f"cancel_action")) bot.send_message(chat_id, f"Отправьте номер или номера регионов, от которых хотите отписаться (через запятую):\n{regions_list}\n", reply_markup=markup) bot.register_next_step_handler_by_chat_id(chat_id, process_unsubscription_button, chat_id, username) def process_unsubscription_button(message, chat_id, username): unsubbed_regions = [] invalid_regions = [] markup = telebot.types.InlineKeyboardMarkup() markup.add(telebot.types.InlineKeyboardButton(text="Отмена", callback_data=f"cancel_action")) if message.text.lower() == 'отмена': bot.send_message(chat_id, "Действие отменено.") telezab.state.set_state(chat_id, "SETTINGS_MENU") return show_settings_menu(chat_id) # Проверка, что введённая строка содержит только цифры и запятые if not all(part.strip().isdigit() for part in message.text.split(',')): bot.send_message(chat_id, "Некорректный формат. Введите номера регионов через запятую.", reply_markup=markup) bot.register_next_step_handler_by_chat_id(chat_id, process_unsubscription_button, chat_id, username) return region_ids = message.text.split(',') valid_region_ids = [region[0] for region in get_user_subscribed_regions(chat_id)] with db_lock: conn = sqlite3.connect(DB_PATH) cursor = conn.cursor() for region_id in region_ids: region_id = region_id.strip() if region_id not in valid_region_ids: invalid_regions.append(region_id) continue # Удаление подписки query = 'UPDATE subscriptions SET active = FALSE WHERE chat_id = ? AND region_id = ?' cursor.execute(query, (chat_id, region_id)) unsubbed_regions.append(region_id) conn.commit() if len(invalid_regions) > 0: bot.send_message(chat_id, f"Регион с ID {', '.join(invalid_regions)} не найден в ваших подписках.") bot.send_message(chat_id, f"Отписка от регионов: {', '.join(unsubbed_regions)} выполнена.") log_user_event(chat_id, username, f"Unsubscribed from regions: {', '.join(unsubbed_regions)}") telezab.state.set_state(chat_id, "SETTINGS_MENU") show_settings_menu(chat_id)