import logging from aiogram import Router, F from aiogram.fsm.context import FSMContext from aiogram.types import CallbackQuery, FSInputFile, Message from templates import ban_words as tban_words from templates import commands as tcommands from utils.defs import delete_msg, create_xlsx from utils.db import Redis, Postgres router = Router() @router.callback_query(F.data == 'ban_words') async def ban_words_btn(call: CallbackQuery, state: FSMContext): """ Ловит кнопку 🚫 Стоп слова :param call: CallbackQuery :param state: FSMContext :return: """ state_data = await state.get_data() document_path = await create_xlsx() last_msg = await call.message.answer_document( document=FSInputFile(document_path), reply_markup=tban_words.actions_ikb() ) await delete_msg( msg=state_data.get('last_msg') ) await state.update_data( last_msg=last_msg ) @router.callback_query(F.data.startswith('ban_words_action_')) async def ban_words_action_btn(call: CallbackQuery, state: FSMContext): """ Ловит кнопки ➕ Добавить ➖ Удалить :param call: CallbackQuery :param state: FSMContext :return: """ state_data = await state.get_data() last_msg = await call.message.answer( text=tban_words.send_words_text, reply_markup=tban_words.send_words_ikb() ) await state.update_data( last_msg=last_msg, ban_words_action=call.data[17:] ) await state.set_state( state=tban_words.SendState.words ) await delete_msg( msg=state_data.get('last_msg') ) @router.message(tban_words.SendState.words, F.text) async def get_words(msg: Message, state: FSMContext): """ Ловит новое сообщение :param msg: Message :param state: FSMContext :return: """ state_data = await state.get_data() words = msg.text.split('\n') r = Redis() p = Postgres() redis_ban_words = await r.get_list( key='ban_words' ) if state_data['ban_words_action'] == 'add': msg_text = tban_words.success_text.format( action='добавлены' ) for word in words: await p.create_row( table_name='ban_words', data_to_insert={'word': word.lower()} ) redis_ban_words.append(word.lower()) else: msg_text = tban_words.success_text.format( action='удалены' ) not_deleted = [] for word in words: try: await p.query( query_text=f"DELETE FROM ban_words WHERE LOWER(word)='{word.lower()}'" ) redis_ban_words.remove(word.lower()) except Exception as e: logging.error(f'get_words {e}') not_deleted.append(word) if not_deleted: msg_text = tban_words.not_success_remove_text.format( words='\n'.join(not_deleted) ) await state_data['last_msg'].edit_text( text=msg_text, reply_markup=await tcommands.start_ikb() ) await msg.delete() await r.delete_key( 'ban_words' ) await r.update_list( 'ban_words', *redis_ban_words ) await state.set_state( state=None )