import asyncio import logging.config from aiogram import F, Router from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery import app.telegram.keyboards.inline as kbi import database.request as rq from app.telegram.tasks.tasks import add_stop_task, cancel_stop_task from logger_helper.logger_helper import LOGGING_CONFIG logging.config.dictConfig(LOGGING_CONFIG) logger = logging.getLogger("stop_trading") router_stop_trading = Router(name="stop_trading") @router_stop_trading.callback_query(F.data == "stop_trading") async def stop_all_trading(callback_query: CallbackQuery, state: FSMContext): try: await state.clear() cancel_stop_task(callback_query.from_user.id) conditional_data = await rq.get_user_conditional_settings( tg_id=callback_query.from_user.id ) timer_end = conditional_data.timer_end async def delay_start(): if timer_end > 0: await callback_query.message.edit_text( text=f"Торговля будет остановлена с задержкой {timer_end} мин.", reply_markup=kbi.cancel_timer_stop, ) await rq.set_stop_timer(tg_id=callback_query.from_user.id, timer_end=0) await asyncio.sleep(timer_end * 60) user_auto_trading_list = await rq.get_all_user_auto_trading( tg_id=callback_query.from_user.id ) if any(item.auto_trading for item in user_auto_trading_list): for active_auto_trading in user_auto_trading_list: if active_auto_trading.auto_trading: symbol = active_auto_trading.symbol req = await rq.set_auto_trading( tg_id=callback_query.from_user.id, symbol=symbol, auto_trading=False, ) if not req: await callback_query.message.edit_text( text="Произошла ошибка при остановке торговли", reply_markup=kbi.profile_bybit, ) return await callback_query.message.edit_text( text="Торговля остановлена", reply_markup=kbi.profile_bybit ) else: await callback_query.message.edit_text(text="Нет активной торговли") task = asyncio.create_task(delay_start()) await add_stop_task(user_id=callback_query.from_user.id, task=task) logger.debug( "Command stop_trading processed successfully for user: %s", callback_query.from_user.id, ) except Exception as e: await callback_query.answer(text="Произошла ошибка при остановке торговли") logger.error( "Error processing command stop_trading for user %s: %s", callback_query.from_user.id, e, ) @router_stop_trading.callback_query(F.data == "cancel_timer_stop") async def cancel_stop_trading(callback_query: CallbackQuery, state: FSMContext): try: await state.clear() cancel_stop_task(callback_query.from_user.id) await callback_query.message.edit_text( text="Таймер отменён.", reply_markup=kbi.profile_bybit ) except Exception as e: await callback_query.answer( text="Произошла ошибка при отмене остановки торговли" ) logger.error( "Error processing command cancel_timer_stop for user %s: %s", callback_query.from_user.id, e, )