Telezab/app/bot/processors/unsubscribe_processor.py
UdoChudo 60f77b39eb feat(subscription): add "subscribe all" and "unsubscribe all" buttons
feat(subscription): add check on unsubscribe to notify user if no active subscriptions

Signed-off-by: UdoChudo <stream@udochudo.ru>
2025-06-19 23:52:48 +05:00

103 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from flask import Flask
from telebot import TeleBot, logger
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from app import Subscriptions
from app.bot.constants import UserStates
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.states import UserStateManager
from app.bot.utils.helpers import get_user_subscribed_regions
from app.bot.utils.tg_audit import log_user_event
from app.extensions.db import db
def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_id: int, state_manager: UserStateManager):
unsubbed_regions = []
invalid_regions = []
username = f"{message.from_user.username}" if message.from_user.username else "N/A"
parts = [part.strip() for part in message.text.split(',')]
if not parts or not all(part.isdigit() for part in parts):
markup = InlineKeyboardMarkup()
markup.add(InlineKeyboardButton('Отмена', callback_data='cancel_input'))
bot.send_message(chat_id,
"Неверный ввод, введите число(а) через запятую, либо нажмите отмена.",
reply_markup=markup)
def delayed_handler(msg):
process_unsubscribe_button(msg, app, bot, chat_id, state_manager)
bot.register_next_step_handler(message, delayed_handler)
return
region_ids = [int(part) for part in parts]
try:
with app.app_context():
valid_region_ids = [int(region[0]) for region in get_user_subscribed_regions(chat_id)]
for region_id in region_ids:
if region_id not in valid_region_ids:
invalid_regions.append(str(region_id))
continue
subscription = Subscriptions.query.filter_by(chat_id=chat_id, region_id=region_id).first()
if subscription:
subscription.active = False
db.session.add(subscription)
unsubbed_regions.append(str(region_id))
db.session.commit()
except Exception as e:
bot.send_message(chat_id, "⚠ Произошла ошибка при обработке запроса. Попробуйте позже.")
logger.error(f"Unexpected Error: {e}")
return
if unsubbed_regions:
bot.send_message(chat_id, f"✅ Вы успешно отписались от регионов: {', '.join(unsubbed_regions)}")
log_user_event(chat_id, app, username, f"Отписался от регионов: {', '.join(unsubbed_regions)}")
if invalid_regions:
bot.send_message(chat_id,
f"⚠ Регионы с ID {', '.join(invalid_regions)} не найдены среди ваших подписок и не были изменены.")
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
bot.send_message(chat_id, "⚙ Вернулись в меню настроек.", reply_markup=get_settings_menu())
def process_unsubscribe_all_regions(call: CallbackQuery, app: Flask, bot: TeleBot, state_manager: UserStateManager):
chat_id = call.message.chat.id
username = f"{call.from_user.username}" if call.from_user.username else "N/A"
try:
with app.app_context():
subscriptions = Subscriptions.query.filter_by(chat_id=chat_id, active=True).all()
if not subscriptions:
bot.answer_callback_query(call.id, text="У вас нет активных подписок.")
return
for sub in subscriptions:
sub.active = False
db.session.add(sub)
db.session.commit()
log_user_event(chat_id, app, username, "Отписался от всех регионов")
bot.answer_callback_query(call.id)
bot.clear_step_handler_by_chat_id(chat_id)
bot.delete_message(chat_id, call.message.message_id)
bot.send_message(chat_id,
"✅ Вы успешно отписались от всех регионов.",
reply_markup=get_settings_menu())
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
except Exception as e:
state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
bot.send_message(chat_id, "⚠ Произошла ошибка при отписке. Попробуйте позже.",reply_markup=get_settings_menu())
return