From 2c64b6208d521194bb8868ced40894a4cffa1b0a Mon Sep 17 00:00:00 2001 From: Djimbo Date: Thu, 19 Jan 2023 05:31:54 +0300 Subject: [PATCH] Update --- main.py | 8 ++++---- tgbot/data/config.py | 1 + tgbot/routers/__init__.py | 14 +++++++------- tgbot/routers/admin/admin_menu.py | 14 +++++++------- tgbot/routers/main_errors.py | 3 ++- tgbot/routers/main_missed.py | 20 +++++++++++--------- tgbot/routers/main_start.py | 15 ++++++++++----- tgbot/routers/user/user_menu.py | 10 +++++----- tgbot/services/api_session.py | 2 +- tgbot/services/api_sqlite.py | 19 ++++++++----------- tgbot/utils/const_functions.py | 5 +++-- tgbot/utils/misc/bot_models.py | 4 ++-- tgbot/utils/misc_functions.py | 10 ++++++---- 13 files changed, 67 insertions(+), 58 deletions(-) diff --git a/main.py b/main.py index ffa8bb2..77af3a7 100644 --- a/main.py +++ b/main.py @@ -9,7 +9,7 @@ from aiogram import Bot, Dispatcher from tgbot.data.config import BOT_TOKEN, scheduler, get_admins from tgbot.middlewares import register_all_middlwares from tgbot.routers import register_all_routers -from tgbot.services.api_session import AsyncSession +from tgbot.services.api_session import RequestSession from tgbot.services.api_sqlite import create_dbx from tgbot.utils.misc.bot_commands import set_commands from tgbot.utils.misc.bot_logging import bot_logger @@ -28,7 +28,7 @@ async def scheduler_start(bot): async def main(): scheduler.start() # Запуск Шедулера dp = Dispatcher() # Образ Диспетчера - aSession = AsyncSession() # Пул асинхронной сессии запросов + rSession = RequestSession() # Пул асинхронной сессии запросов bot = Bot(token=BOT_TOKEN, parse_mode="HTML") # Образ Бота register_all_middlwares(dp) # Регистрация всех мидлварей @@ -48,9 +48,9 @@ async def main(): await bot.delete_webhook() await bot.get_updates(offset=-1) - await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types(), aSession=aSession) + await dp.start_polling(bot, allowed_updates=dp.resolve_used_update_types(), rSession=rSession) finally: - await aSession.close() + await rSession.close() await bot.session.close() diff --git a/tgbot/data/config.py b/tgbot/data/config.py index 37dbb5a..ccb9aa7 100644 --- a/tgbot/data/config.py +++ b/tgbot/data/config.py @@ -7,6 +7,7 @@ from apscheduler.schedulers.asyncio import AsyncIOScheduler BOT_TOKEN = configparser.ConfigParser() BOT_TOKEN.read("settings.ini") BOT_TOKEN = BOT_TOKEN['settings']['token'].strip().replace(' ', '') +BOT_TIMEZONE = "Europe/Moscow" # Временная зона бота # Пути к файлам PATH_DATABASE = "tgbot/data/database.db" # Путь к БД diff --git a/tgbot/routers/__init__.py b/tgbot/routers/__init__.py index 00c6c3c..bb7d82c 100644 --- a/tgbot/routers/__init__.py +++ b/tgbot/routers/__init__.py @@ -12,19 +12,19 @@ def register_all_routers(dp: Dispatcher): # Подключение фильтров main_errors.router.message.filter(F.chat.type == "private") main_start.router.message.filter(F.chat.type == "private") - main_missed.router.message.filter(F.chat.type == "private") user_menu.router.message.filter(F.chat.type == "private") - admin_menu.router.message.filter(F.chat.type == "private", IsAdmin()) + main_missed.router.message.filter(F.chat.type == "private") + # Подключение обязательных роутеров - dp.include_router(main_errors.router) - dp.include_router(main_start.router) + dp.include_router(main_errors.router) # Роутер ошибки + dp.include_router(main_start.router) # Роутер основных команд # Подключение пользовательских роутеров (юзеров и админов) - dp.include_router(user_menu.router) # Юзер хендлер - dp.include_router(admin_menu.router) # Админ хендлер + dp.include_router(user_menu.router) # Юзер роутер + dp.include_router(admin_menu.router) # Админ роутер # Подключение обязательных роутеров - dp.include_router(main_missed.router) + dp.include_router(main_missed.router) # Роутер пропущенных апдейтов diff --git a/tgbot/routers/admin/admin_menu.py b/tgbot/routers/admin/admin_menu.py index 067047d..b53ec03 100644 --- a/tgbot/routers/admin/admin_menu.py +++ b/tgbot/routers/admin/admin_menu.py @@ -14,7 +14,7 @@ router = Router() # Кнопка - Admin Inline @router.message(Text(text="Admin Inline")) -async def admin_button_inline(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_button_inline(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer("Click Button - Admin Inline", reply_markup=admin_inl) @@ -22,7 +22,7 @@ async def admin_button_inline(message: Message, bot: Bot, state: FSM, aSession: # Кнопка - Admin Reply @router.message(Text(text="Admin Reply")) -async def admin_button_reply(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_button_reply(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer("Click Button - Admin Reply", reply_markup=admin_rep) @@ -30,13 +30,13 @@ async def admin_button_reply(message: Message, bot: Bot, state: FSM, aSession: A # Колбэк - Admin X @router.callback_query(Text(text="admin_inline_x")) -async def admin_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): await call.answer(f"Click Admin X") # Колбэк - Admin @router.callback_query(Text(startswith="admin_inline:")) -async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): get_data = call.data.split(":")[1] await call.answer(f"Click Admin - {get_data}", True) @@ -44,7 +44,7 @@ async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, aSess # Получение Базы Данных @router.message(Command(commands=['db', 'database'])) -async def admin_database(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_database(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer_document(FSInputFile(PATH_DATABASE), @@ -54,7 +54,7 @@ async def admin_database(message: Message, bot: Bot, state: FSM, aSession: AS, m # Получение логов @router.message(Command(commands=['log', 'logs'])) -async def admin_log(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_log(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer_document(FSInputFile(PATH_LOGS), @@ -64,7 +64,7 @@ async def admin_log(message: Message, bot: Bot, state: FSM, aSession: AS, my_use # Очистить логи @router.message(Command(commands=['clear_log', 'clear_logs', 'log_clear', 'logs_clear'])) -async def admin_logs_clear(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def admin_logs_clear(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() with open(PATH_LOGS, "w") as file: diff --git a/tgbot/routers/main_errors.py b/tgbot/routers/main_errors.py index cf2a7dc..a274234 100644 --- a/tgbot/routers/main_errors.py +++ b/tgbot/routers/main_errors.py @@ -18,7 +18,8 @@ class MyHandler(ErrorHandler): # Ошибка с редактированием одинакового сообщения @router.errors(ExceptionMessageFilter( - "Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message")) + "Bad Request: message is not modified: specified new message content and reply markup are exactly the same as a current content and reply markup of the message") +) class MyHandler(ErrorHandler): async def handle(self): bot_logger.exception( diff --git a/tgbot/routers/main_missed.py b/tgbot/routers/main_missed.py index 7b405e5..a273e86 100644 --- a/tgbot/routers/main_missed.py +++ b/tgbot/routers/main_missed.py @@ -11,31 +11,33 @@ router = Router() # Колбэк с удалением сообщения @router.callback_query(Text(text="close_this")) -async def main_callback_close(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def main_callback_close(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): await call.message.delete() # Колбэк с обработкой кнопки @router.callback_query(Text(text="...")) -async def main_callback_answer(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): - await call.answer(cache_time=20) +async def main_callback_answer(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): + await call.answer(cache_time=30) # Колбэк с обработкой удаления сообщений потерявших стейт @router.callback_query() -async def main_callback_missed(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def main_callback_missed(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): try: await call.message.delete() except: pass - await call.message.answer("❌ Данные не были найдены из-за перезапуска скрипта.\n" - "♻ Выполните действие заново.", - reply_markup=menu_frep(call.from_user.id)) + await call.message.answer( + "❌ Данные не были найдены из-за перезапуска скрипта.\n" + "♻ Выполните действие заново.", + reply_markup=menu_frep(call.from_user.id), + ) # Обработка всех неизвестных команд @router.message() -async def main_message_missed(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def main_message_missed(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await message.answer("♦ Неизвестная команда.\n" - "▶ Введите /start") + "♦ Введите /start") diff --git a/tgbot/routers/main_start.py b/tgbot/routers/main_start.py index eaed047..ae8daeb 100644 --- a/tgbot/routers/main_start.py +++ b/tgbot/routers/main_start.py @@ -4,6 +4,7 @@ from aiogram.filters import Text, Command from aiogram.types import Message from tgbot.keyboards.reply_main import menu_frep +from tgbot.utils.const_functions import ded from tgbot.utils.misc.bot_models import FSM, AS router = Router() @@ -12,10 +13,14 @@ router = Router() # Открытие главного меню @router.message(Text(text=['🔙 Главное меню'])) @router.message(Command(commands=['start'])) -async def main_start(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def main_start(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() - await message.answer("🔸 Бот готов к использованию.\n" - "🔸 Если не появились вспомогательные кнопки\n" - "▶ Введите /start", - reply_markup=menu_frep(message.from_user.id)) + await message.answer( + ded(""" + 🔸 Бот готов к использованию. + 🔸 Если не появились вспомогательные кнопки + 🔸 Введите /start, + """), + reply_markup=menu_frep(message.from_user.id), + ) diff --git a/tgbot/routers/user/user_menu.py b/tgbot/routers/user/user_menu.py index 79a0571..f56800b 100644 --- a/tgbot/routers/user/user_menu.py +++ b/tgbot/routers/user/user_menu.py @@ -13,7 +13,7 @@ router = Router() # Кнопка - User Inline @router.message(Text(text="User Inline")) -async def user_button_inline(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def user_button_inline(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer("Click Button - User Inline", reply_markup=user_inl) @@ -21,7 +21,7 @@ async def user_button_inline(message: Message, bot: Bot, state: FSM, aSession: A # Кнопка - User Reply @router.message(Text(text="User Reply")) -async def user_button_reply(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def user_button_reply(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer("Click Button - User Reply", reply_markup=user_rep) @@ -29,7 +29,7 @@ async def user_button_reply(message: Message, bot: Bot, state: FSM, aSession: AS # Команда - /inline @router.message(Command(commands="inline")) -async def user_command_inline(message: Message, bot: Bot, state: FSM, aSession: AS, my_user): +async def user_command_inline(message: Message, bot: Bot, state: FSM, rSession: AS, my_user): await state.clear() await message.answer("Click command - /inline", reply_markup=menu_finl(message.from_user.id)) @@ -37,13 +37,13 @@ async def user_command_inline(message: Message, bot: Bot, state: FSM, aSession: # Колбэк - User X @router.callback_query(Text(text="user_inline_x")) -async def user_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def user_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): await call.answer(f"Click User X") # Колбэк - User @router.callback_query(Text(startswith="user_inline:")) -async def user_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, aSession: AS, my_user): +async def user_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, rSession: AS, my_user): get_data = call.data.split(":")[1] await call.answer(f"Click User - {get_data}", True) diff --git a/tgbot/services/api_session.py b/tgbot/services/api_session.py index 0218d8c..85c8e33 100644 --- a/tgbot/services/api_session.py +++ b/tgbot/services/api_session.py @@ -5,7 +5,7 @@ import aiohttp # Асинхронная сессия для запросов -class AsyncSession: +class RequestSession: def __init__(self) -> None: self._session: Optional[aiohttp.ClientSession] = None diff --git a/tgbot/services/api_sqlite.py b/tgbot/services/api_sqlite.py index adf2f0b..8eb1181 100644 --- a/tgbot/services/api_sqlite.py +++ b/tgbot/services/api_sqlite.py @@ -18,21 +18,18 @@ def dict_factory(cursor, row): #################################################################################################### ##################################### ФОРМАТИРОВАНИЕ ЗАПРОСОВ ###################################### # Форматирование запроса без аргументов -def update_format_with_args(sql, parameters: dict): - if "XXX" not in sql: - sql += " XXX " - +def update_format(sql, parameters: dict): values = ", ".join([ f"{item} = ?" for item in parameters ]) - sql = sql.replace("XXX", values) + sql += f" {values}" return sql, list(parameters.values()) # Форматирование запроса с аргументами -def update_format_args(sql, parameters: dict): - sql = f"{sql} WHERE " +def update_format_where(sql, parameters: dict): + sql += " WHERE " sql += " AND ".join([ f"{item} = ?" for item in parameters @@ -58,7 +55,7 @@ def get_userx(**kwargs): with sqlite3.connect(PATH_DATABASE) as con: con.row_factory = dict_factory sql = "SELECT * FROM storage_users" - sql, parameters = update_format_args(sql, kwargs) + sql, parameters = update_format_where(sql, kwargs) return con.execute(sql, parameters).fetchone() @@ -67,7 +64,7 @@ def get_usersx(**kwargs): with sqlite3.connect(PATH_DATABASE) as con: con.row_factory = dict_factory sql = "SELECT * FROM storage_users" - sql, parameters = update_format_args(sql, kwargs) + sql, parameters = update_format_where(sql, kwargs) return con.execute(sql, parameters).fetchall() @@ -84,7 +81,7 @@ def update_userx(user_id, **kwargs): with sqlite3.connect(PATH_DATABASE) as con: con.row_factory = dict_factory sql = f"UPDATE storage_users SET" - sql, parameters = update_format_with_args(sql, kwargs) + sql, parameters = update_format(sql, kwargs) parameters.append(user_id) con.execute(sql + "WHERE user_id = ?", parameters) @@ -94,7 +91,7 @@ def delete_userx(**kwargs): with sqlite3.connect(PATH_DATABASE) as con: con.row_factory = dict_factory sql = "DELETE FROM storage_users" - sql, parameters = update_format_args(sql, kwargs) + sql, parameters = update_format_where(sql, kwargs) con.execute(sql, parameters) diff --git a/tgbot/utils/const_functions.py b/tgbot/utils/const_functions.py index d7dccd5..fac717b 100644 --- a/tgbot/utils/const_functions.py +++ b/tgbot/utils/const_functions.py @@ -4,10 +4,11 @@ import time from datetime import datetime from typing import Union +import pytz from aiogram import Bot, types from aiogram.types import InlineKeyboardButton, KeyboardButton -from tgbot.data.config import get_admins +from tgbot.data.config import get_admins, BOT_TIMEZONE ######################################## AIOGRAM ######################################## @@ -120,7 +121,7 @@ def split_messages(get_list: list, count: int) -> list[list]: # Получение даты def get_date() -> str: - return datetime.today().replace(microsecond=0).strftime("%d.%m.%Y %H:%M:%S") + return datetime.now(pytz.timezone(BOT_TIMEZONE)).strftime("%d.%m.%Y %H:%M:%S") # Получение юникс даты diff --git a/tgbot/utils/misc/bot_models.py b/tgbot/utils/misc/bot_models.py index 624da26..493511d 100644 --- a/tgbot/utils/misc/bot_models.py +++ b/tgbot/utils/misc/bot_models.py @@ -1,7 +1,7 @@ # - *- coding: utf- 8 - *- from aiogram.fsm.context import FSMContext -from tgbot.services.api_session import AsyncSession +from tgbot.services.api_session import RequestSession FSM = FSMContext -AS = AsyncSession +AS = RequestSession diff --git a/tgbot/utils/misc_functions.py b/tgbot/utils/misc_functions.py index 69bced4..856736c 100644 --- a/tgbot/utils/misc_functions.py +++ b/tgbot/utils/misc_functions.py @@ -16,9 +16,11 @@ async def startup_notify(bot: Bot): async def autobackup_admin(bot: Bot): for admin in get_admins(): try: - await bot.send_document(admin, - FSInputFile(PATH_DATABASE), - caption=f"📦 AUTOBACKUP\n" - f"🕰 {get_date()}") + await bot.send_document( + admin, + FSInputFile(PATH_DATABASE), + caption=f"📦 AUTOBACKUP\n" + f"🕰 {get_date()}", + ) except: pass