From 27d2a3d92bea9b18ffe6ba0dd087d1c68abdac06 Mon Sep 17 00:00:00 2001 From: Alexei Date: Tue, 16 May 2023 10:50:20 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=BE=D0=B2.=20=D0=9F=D0=BE?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=B5=20=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=B0=D0=B5=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_modules/mod_table_operate.py | 52 +++--- bot_modules/projects.py | 340 ++++++++------------------------------- bot_sys/aiogram_bot.py | 8 +- bot_sys/interfaces.py | 4 +- main.py | 23 ++- template/bd_item.py | 36 ++--- template/bd_item_add.py | 71 ++++---- template/bd_item_delete.py | 28 ++-- template/bd_item_edit.py | 36 ++--- template/bd_item_select.py | 30 ++-- template/bd_item_view.py | 24 ++- template/simple_message.py | 9 +- 12 files changed, 224 insertions(+), 437 deletions(-) diff --git a/bot_modules/mod_table_operate.py b/bot_modules/mod_table_operate.py index 825972b..96e70c6 100644 --- a/bot_modules/mod_table_operate.py +++ b/bot_modules/mod_table_operate.py @@ -3,9 +3,9 @@ # Модуль для редактирования и просмотра таблицы в БД -from bot_sys import keyboard, user_access -from bot_modules import access_utils, mod_interface -from template import simple_message, bd_item +from bot_sys import keyboard, user_access, bd_table +from bot_modules import access_utils, mod_simple_message +from template import simple_message, bd_item, bd_item_select, bd_item_view, bd_item_delete, bd_item_add, bd_item_edit from enum import Enum from enum import auto @@ -48,13 +48,9 @@ class FSMs: self.m_FSMEditPhoto = a_FSMEditPhoto self.m_FSMEditAccess = a_FSMEditAccess -# Предназначение поля в таблице -class TableFieldDestiny(Enum): - KEY = auto() - class TableOperateModule(mod_simple_message.SimpleMessageModule): def __init__(self, a_Table, a_Messages, a_Buttons, a_FSMs, a_ParentModName, a_ChildModName, a_InitAccess, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): - super().__init__(a_Messages[0], a_Buttons[0], a_InitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + super().__init__(a_Messages[Messages.START], a_Buttons[ButtonNames.START], a_InitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) self.m_Table = a_Table self.m_FSMs = a_FSMs self.m_EditModuleNameList = a_EditModuleNameList @@ -78,12 +74,12 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return self.GetButtonNameAndKeyValueAndAccess(a_Item) self.m_GetButtonNameAndKeyValueAndAccessFunc = GetButtonNameAndKeyValueAndAccess - async def PreDelete(a_CallbackQuery : types.CallbackQuery, a_Item): - return self.PreDelete(a_Item) + async def PreDelete(a_CallbackQuery, a_Item): + return await self.PreDelete(a_Item) self.m_PreDeleteFunc = PreDelete - async def PostDelete(a_CallbackQuery : types.CallbackQuery, a_ItemID): - return self.PostDelete(a_Item) + async def PostDelete(a_CallbackQuery, a_ItemID): + return await self.PostDelete(a_Item) self.m_PostDeleteFunc = PostDelete def AddBDItemFunc(a_ItemData, a_UserID): @@ -141,12 +137,12 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): def GetButtonNameAndKeyValueAndAccess(self, a_Item): return \ - a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.NAME)], - a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.KEY)], + a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.NAME)],\ + a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.KEY)],\ a_Item[self.m_Table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS)] - def ShowMessageTemplate(self, a_MessageName : Message, keyboard_template_func = None): - async def ShowMessage(a_CallbackQuery : types.CallbackQuery, a_Item): + def ShowMessageTemplate(self, a_MessageName : Messages, keyboard_template_func = None): + async def ShowMessage(a_CallbackQuery, a_Item): if len(a_Item) < self.m_Table.GetFieldsCount(): return simple_message.WorkFuncResult(self.GetMessage(Messages.ERROR_FIND)) @@ -161,7 +157,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): return ShowMessage # TODO: delete? - def SimpleMessageTemplate(self, a_MessageName : Message): + def SimpleMessageTemplate(self, a_MessageName : Messages): async def ShowMessage(a_CallbackQuery, a_Item): return simple_message.WorkFuncResult(self.GetMessage(a_MessageName)) return ShowMessage @@ -250,17 +246,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): GetButtonNameAndKeyValueAndAccess = self.m_GetButtonNameAndKeyValueAndAccessFunc GetAccess = self.m_GetAccessFunc - defaul_keyboard_func = self.m_GetStartTaskKeyboardButtonsFunc - - sql_request.RequestToBDRegisterHandlers( - self.m_Bot, - self.m_SqlRequestButtonName, - self.m_RequestStartMessage, - FSMRequestToBDAccess, - self.m_GetStartKeyboardButtonsFunc, - user_access.AccessMode.EDIT, - self.m_GetAccessFunc - ) + defaul_keyboard_func = self.m_GetStartKeyboardButtonsFunc # Список a_ButtonName = self.GetButton(ButtonNames.LIST) @@ -302,7 +288,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): a_ButtonName = self.GetButton(ButtonNames.ADD) if a_ButtonName: a_Prefix = self.RegisterSelect(a_ButtonName, user_access.AccessMode.ADD) - bd_item_add.AddBDItem3RegisterHandlers(self.m_Bot, \ + bd_item_add.AddBDItem3RegisterHandlers(self.m_Bot, \ bd_item.GetCheckForPrefixFunc(a_Prefix), \ self.m_FSMs.m_FSMCreate, \ self.m_FSMs.m_FSMCreate.name,\ @@ -321,11 +307,11 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): photo_field, \ GetButtonNameAndKeyValueAndAccess, \ GetAccess, \ - self.m_GetStartTaskKeyboardButtonsFunc\ + self.m_GetStartKeyboardButtonsFunc\ ) # Редактирование - edit_keyboard_func = self.m_GetEditTaskKeyboardButtonsFunc + edit_keyboard_func = self.m_GetEditKeyboardButtonsFunc def RegisterEdit(a_ButtonName, a_FSM, a_EditMessage, a_FieldName, a_FieldType, a_AccessMode = user_access.AccessMode.EDIT): if not a_ButtonName: return @@ -351,9 +337,11 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): a_ButtonName = self.GetButton(ButtonNames.EDIT) if a_ButtonName: self.m_Bot.RegisterMessageHandler(\ - simple_message.InfoMessageTemplateLegacy(\ + simple_message.InfoMessageTemplate(\ + self.m_Bot,\ self.GetMessage(Messages.START_EDIT),\ edit_keyboard_func,\ + None,\ GetAccess,\ access_mode = user_access.AccessMode.EDIT),\ bd_item.GetCheckForTextFunc(a_ButtonName)\ diff --git a/bot_modules/projects.py b/bot_modules/projects.py index 799311f..0f884a6 100644 --- a/bot_modules/projects.py +++ b/bot_modules/projects.py @@ -3,16 +3,11 @@ # Проекты -from bot_sys import bot_bd, log, keyboard, user_access, user_messages -from bot_modules import start, access, groups, tasks, needs, comments -from template import bd_item_view, simple_message, bd_item_delete, bd_item_edit, bd_item, bd_item_add - -from aiogram import types +from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_modules import mod_table_operate from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters.state import State, StatesGroup -from aiogram.dispatcher import Dispatcher -import sqlite3 class FSMCreateProject(StatesGroup): name = State() @@ -25,7 +20,7 @@ class FSMEditProjectPhotoItem(StatesGroup): class FSMEditProjectNameItem(StatesGroup): item_field = State() -class FSMEditProjectDeskItem(StatesGroup): +class FSMEditProjectDescItem(StatesGroup): item_field = State() class FSMEditProjectAccessItem(StatesGroup): @@ -42,314 +37,117 @@ photo_field = 'projectPhoto' access_field = 'projectAccess' create_datetime_field = 'projectCreateDateTime' -init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}( - {key_name} INTEGER PRIMARY KEY, - {name_field} TEXT, - {desc_field} TEXT, - {photo_field} TEXT, - {access_field} TEXT, - {create_datetime_field} TEXT - )''', -f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_new}=va', '{user_access.user_access_group_new}=va');" -] +table = bd_table.Table(table_name, [ + bd_table.TableField(key_name, bd_table.TableFieldDestiny.KEY, bd_table.TableFieldType.INT), + bd_table.TableField(name_field, bd_table.TableFieldDestiny.NAME, bd_table.TableFieldType.STR), + bd_table.TableField(desc_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), + bd_table.TableField(photo_field, bd_table.TableFieldDestiny.PHOTO, bd_table.TableFieldType.STR), + bd_table.TableField(access_field, bd_table.TableFieldDestiny.ACCESS, bd_table.TableFieldType.STR), + bd_table.TableField(create_datetime_field, bd_table.TableFieldDestiny.CREATE_DATE, bd_table.TableFieldType.STR), + ]) -def MSG(a_MessageName, a_MessageDesc): - def UpdateMSG(a_Message : user_messages.Message): - print(a_Message.m_MessageName, a_Message.m_MessageDesc) - globals()[a_Message.m_MessageName] = a_Message - user_messages.MSG(a_MessageName, a_MessageDesc, UpdateMSG, log.GetTimeNow()) +init_access = f'{user_access.user_access_group_new}=va' -# --------------------------------------------------------- -# Сообщения +fsm = mod_table_operate.FSMs(FSMCreateProject, FSMEditProjectNameItem, FSMEditProjectDescItem, FSMEditProjectPhotoItem, FSMEditProjectAccessItem) -projects_button_name = "🟥 Проекты" -MSG('base_project_message',''' +# --------------------------------------------------------- +# Сообщения и кнопки + +button_names = { + mod_table_operate.ButtonNames.START: "🟥 Проекты", + mod_table_operate.ButtonNames.LIST: "📃 Список проектов", + mod_table_operate.ButtonNames.ADD: "✅ Добавить проект", + mod_table_operate.ButtonNames.EDIT: "🛠 Редактировать проект", + mod_table_operate.ButtonNames.EDIT_PHOTO: "☐ Изменить изображение в проекте", + mod_table_operate.ButtonNames.EDIT_NAME: "≂ Изменить название в проекте", + mod_table_operate.ButtonNames.EDIT_DESC: "𝌴 Изменить описание в проекте", + mod_table_operate.ButtonNames.EDIT_ACCESS: "✋ Изменить доступ к проекту", + mod_table_operate.ButtonNames.DEL: "❌ Удалить проект", +} + +messages = { + mod_table_operate.Messages.START: ''' 🟥 Проекты -''') - -list_project_button_name = "📃 Список проектов" -MSG('select_project_message',''' +''', + mod_table_operate.Messages.SELECT: ''' Пожалуйста, выберите проект: -''') - -MSG('error_find_proj_message',''' +''', + mod_table_operate.Messages.ERROR_FIND: ''' ❌ Ошибка, проект не найден -''') - -MSG('project_open_message',f''' +''', + mod_table_operate.Messages.OPEN: f''' Проект: #{name_field} #{desc_field} Время создания: #{create_datetime_field} -''') - -# Создание проекта - -add_project_button_name = "✅ Добавить проект" -MSG('project_create_name_message',''' +''', + mod_table_operate.Messages.CREATE_NAME: ''' Создание проекта. Шаг №1 Введите название проекта: -''') - -MSG('project_create_desc_message',''' +''', + mod_table_operate.Messages.CREATE_DESC: ''' Создание проекта. Шаг №2 Введите описание проекта: -''') - -MSG('project_create_photo_message',''' +''', + mod_table_operate.Messages.CREATE_PHOTO: ''' Создание проекта. Шаг №3 Загрузите обложку для проекта (Фото): Она будет отображаться в его описании. -''') - -MSG('project_success_create_message','''✅ Проект успешно добавлен!''') - -# Редактирование проекта. - -edit_project_button_name = "🛠 Редактировать проект" -MSG('project_start_edit_message', ''' +''', + mod_table_operate.Messages.SUCCESS_CREATE: '''✅ Проект успешно добавлен!''', + mod_table_operate.Messages.START_EDIT: ''' Пожалуйста, выберите действие: -''') - -MSG('project_select_to_edit_message',''' +''', + mod_table_operate.Messages.SELECT_TO_EDIT: ''' Выберите проект, который вы хотите отредактировать. -''') - -edit_project_photo_button_name = "☐ Изменить изображение в проекте" -MSG('project_edit_photo_message',''' +''', + mod_table_operate.Messages.EDIT_PHOTO: ''' Загрузите новую обложку для проекта (Фото): Она будет отображаться в его описании. -''') - -edit_project_name_button_name = "≂ Изменить название в проекте" -MSG('project_edit_name_message',f''' +''', + mod_table_operate.Messages.EDIT_NAME: f''' Текущее название проекта: #{name_field} Введите новое название проекта: -''') - -edit_project_desc_button_name = "𝌴 Изменить описание в проекте" -MSG('project_edit_desc_message',f''' +''', + mod_table_operate.Messages.EDIT_DESC: f''' Текущее описание проекта: #{desc_field} Введите новое описание проекта: -''') - -edit_project_access_button_name = "✋ Изменить доступ к проекту" -MSG('project_edit_access_message',f''' +''', + mod_table_operate.Messages.EDIT_ACCESS: f''' Текущий доступ к проекту: #{access_field} {user_access.user_access_readme} Введите новую строку доступа: -''') - -MSG('project_success_edit_message','''✅ Проект успешно отредактирован!''') - -# Удаление проекта - -del_project_button_name = "❌ Удалить проект" -MSG('project_select_to_delete_message',''' +''', + mod_table_operate.Messages.SUCCESS_EDIT: '''✅ Проект успешно отредактирован!''', + mod_table_operate.Messages.SELECT_TO_DELETE: ''' Выберите проект, который вы хотите удалить. Все задачи и потребности в этом проекте так же будут удалены! -''') - -MSG('project_success_delete_message','''✅ Проект успешно удалён!''') +''', + mod_table_operate.Messages.SUCCESS_DELETE: '''✅ Проект успешно удалён!''', +} -# --------------------------------------------------------- -# Работа с кнопками - -def GetEditProjectKeyboardButtons(a_Message, a_UserGroups): - cur_buttons = GetModuleButtons() + [ - keyboard.ButtonWithAccess(edit_project_photo_button_name, user_access.AccessMode.EDIT, GetAccess()), - keyboard.ButtonWithAccess(edit_project_name_button_name, user_access.AccessMode.EDIT, GetAccess()), - keyboard.ButtonWithAccess(edit_project_desc_button_name, user_access.AccessMode.EDIT, GetAccess()), - keyboard.ButtonWithAccess(edit_project_access_button_name, user_access.AccessMode.ACCEES_EDIT, GetAccess()), - ] - mods = [start] - return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups) +class ModuleProjects(mod_table_operate.TableOperateModule): + def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): + super().__init__(table, messages, button_names, fsm, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) -def GetStartProjectKeyboardButtons(a_Message, a_UserGroups): - cur_buttons = [ - keyboard.ButtonWithAccess(list_project_button_name, user_access.AccessMode.VIEW, GetAccess()), - keyboard.ButtonWithAccess(add_project_button_name, user_access.AccessMode.ADD, GetAccess()), - keyboard.ButtonWithAccess(del_project_button_name, user_access.AccessMode.DELETE, GetAccess()), - keyboard.ButtonWithAccess(edit_project_button_name, user_access.AccessMode.EDIT, GetAccess()) - ] - mods = [start, tasks, needs, comments] - return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups) + def GetName(self): + return module_name -def GetViewItemInlineKeyboardTemplate(a_ItemID): - def GetViewItemInlineKeyboard(a_Message, a_UserGroups): - cur_buttons = [ - keyboard.InlineButtonWithAccess(tasks.list_task_button_name, tasks.select_tasks_prefix, a_ItemID, GetAccess(), user_access.AccessMode.VIEW), + def GetModuleButtons(self): + return super().GetModuleButtons() + [ + keyboard.ButtonWithAccess(self.GetButton(ButtonNames.LIST), user_access.AccessMode.VIEW, self.GetAccess()), ] - return keyboard.MakeInlineKeyboard(cur_buttons, a_UserGroups) - return GetViewItemInlineKeyboard - -# --------------------------------------------------------- -# Обработка сообщений - -# стартовое сообщение -async def ProjectsOpen(a_Message : types.message, state = None): - return simple_message.WorkFuncResult(base_project_message) - -def GetButtonNameAndKeyValueAndAccess(a_Item): - # projectName projectID projectAccess - return a_Item[1], a_Item[0], a_Item[4] - -def ShowMessageTemplate(a_StringMessage, keyboard_template_func = None): - async def ShowMessage(a_CallbackQuery : types.CallbackQuery, a_Item): - if (len(a_Item) < 6): - return simple_message.WorkFuncResult(error_find_proj_message) - - msg = str(a_StringMessage).\ - replace(f'#{name_field}', a_Item[1]).\ - replace(f'#{desc_field}', a_Item[2]).\ - replace(f'#{create_datetime_field}', a_Item[5]).\ - replace(f'#{access_field}', a_Item[4]) - keyboard_func = None - if keyboard_template_func: - keyboard_func = keyboard_template_func(a_Item[0]) - return simple_message.WorkFuncResult(msg, photo_id = a_Item[3], item_access = a_Item[4], keyboard_func = keyboard_func) - return ShowMessage - -def SimpleMessageTemplateLegacy(a_StringMessage): - async def ShowMessage(a_CallbackQuery : types.CallbackQuery, a_Item): - return simple_message.WorkFuncResult(a_StringMessage) - return ShowMessage - -# Удаление проекта - -async def ProjectPreDelete(a_CallbackQuery : types.CallbackQuery, a_Item): - if (len(a_Item) < 6): - return simple_message.WorkFuncResult(error_find_proj_message) - access = a_Item[4] - return simple_message.WorkFuncResult('', None, item_access = access) - -async def ProjectPostDelete(a_CallbackQuery : types.CallbackQuery, a_ItemID): - log.Success(f'Проект №{a_ItemID} был удалён пользователем {a_CallbackQuery.from_user.id}.') - #TODO: удалить вложенные - return simple_message.WorkFuncResult(project_success_delete_message) - -# --------------------------------------------------------- -# Работа с базой данных проектов - -def AddBDItemFunc(a_ItemData, a_UserID): - res, error = bot_bd.SQLRequestToBD(f'INSERT INTO {table_name}({photo_field}, {name_field}, {desc_field}, {access_field}, {create_datetime_field}) VALUES(?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()})', - commit = True, return_error = True, param = (a_ItemData[photo_field], a_ItemData[name_field], a_ItemData[desc_field], access.GetItemDefaultAccessForModule(module_name) + f";{a_UserID}=+")) - - if error: - log.Error(f'Пользоватлель {a_UserID}. Ошибка добавления записи в таблицу {table_name} ({a_ItemData[photo_field]}, {a_ItemData[name_field]}, {a_ItemData[desc_field]}, {access.GetItemDefaultAccessForModule(module_name)}).') - else: - log.Success(f'Пользоватлель {a_UserID}. Добавлена запись в таблицу {table_name} ({a_ItemData[photo_field]}, {a_ItemData[name_field]}, {a_ItemData[desc_field]}, {access.GetItemDefaultAccessForModule(module_name)}).') - - return res, error - -# --------------------------------------------------------- -# API - -# Инициализация БД -def GetInitBDCommands(): - return init_bd_cmds - -def GetAccess(): - return access.GetAccessForModule(module_name) - -# Доступные кнопки -def GetModuleButtons(): - return [ - keyboard.ButtonWithAccess(projects_button_name, user_access.AccessMode.VIEW, GetAccess()), - keyboard.ButtonWithAccess(list_project_button_name, user_access.AccessMode.VIEW, GetAccess()), - ] - -# Обработка кнопок -def RegisterHandlers(dp : Dispatcher): - defaul_keyboard_func = GetStartProjectKeyboardButtons - - # Список проектов - dp.register_message_handler(simple_message.SimpleMessageTemplateLegacy(ProjectsOpen, defaul_keyboard_func, GetAccess), text = projects_button_name) - bd_item_view.FirstSelectAndShowBDItemRegisterHandlers(dp, \ - list_project_button_name, \ - table_name, \ - key_name, \ - ShowMessageTemplate(project_open_message, GetViewItemInlineKeyboardTemplate), \ - GetButtonNameAndKeyValueAndAccess, \ - select_project_message, \ - GetAccess, \ - defaul_keyboard_func\ - ) - - # Удаление проекта - bd_item_delete.DeleteBDItemRegisterHandlers(dp, \ - None, \ - bd_item.GetCheckForTextFunc(del_project_button_name), \ - table_name, \ - key_name, \ - None, \ - ProjectPreDelete, \ - ProjectPostDelete, \ - GetButtonNameAndKeyValueAndAccess, \ - select_project_message, \ - GetAccess, \ - defaul_keyboard_func\ - ) - - # Добавление проекта - bd_item_add.AddBDItem3RegisterHandlers(dp, \ - bd_item.GetCheckForTextFunc(add_project_button_name), \ - FSMCreateProject,\ - FSMCreateProject.name,\ - FSMCreateProject.desc, \ - FSMCreateProject.photo,\ - AddBDItemFunc, \ - SimpleMessageTemplateLegacy(project_create_name_message), \ - SimpleMessageTemplateLegacy(project_create_desc_message), \ - SimpleMessageTemplateLegacy(project_create_photo_message), \ - SimpleMessageTemplateLegacy(project_success_create_message), \ - None,\ - None, \ - None, \ - name_field, \ - desc_field, \ - photo_field, \ - GetButtonNameAndKeyValueAndAccess, \ - GetAccess, \ - GetStartProjectKeyboardButtons\ - ) - - # Редактирование проекта - edit_keyboard_func = GetEditProjectKeyboardButtons - def RegisterEdit(a_ButtonName, a_FSM, a_EditMessage, a_FieldName, a_FieldType, a_AccessMode = user_access.AccessMode.EDIT): - bd_item_edit.EditBDItemRegisterHandlers(dp, \ - None, \ - a_FSM, \ - bd_item.GetCheckForTextFunc(a_ButtonName), \ - project_select_to_edit_message, \ - ShowMessageTemplate(a_EditMessage), \ - ShowMessageTemplate(project_success_edit_message), \ - table_name, \ - key_name, \ - None, \ - a_FieldName, \ - GetButtonNameAndKeyValueAndAccess, \ - GetAccess, \ - edit_keyboard_func, \ - access_mode = a_AccessMode, \ - field_type = a_FieldType\ - ) - dp.register_message_handler(simple_message.InfoMessageTemplateLegacy(project_start_edit_message, edit_keyboard_func, GetAccess, access_mode = user_access.AccessMode.EDIT), text = edit_project_button_name) - RegisterEdit(edit_project_photo_button_name, FSMEditProjectPhotoItem, project_edit_photo_message, photo_field, bd_item.FieldType.photo) - RegisterEdit(edit_project_name_button_name, FSMEditProjectNameItem, project_edit_name_message, name_field, bd_item.FieldType.text) - RegisterEdit(edit_project_desc_button_name, FSMEditProjectDeskItem, project_edit_desc_message, desc_field, bd_item.FieldType.text) - RegisterEdit(edit_project_access_button_name, FSMEditProjectAccessItem, project_edit_access_message, access_field, bd_item.FieldType.text) diff --git a/bot_sys/aiogram_bot.py b/bot_sys/aiogram_bot.py index 7974aae..c13656c 100644 --- a/bot_sys/aiogram_bot.py +++ b/bot_sys/aiogram_bot.py @@ -71,17 +71,17 @@ class AiogramBot(interfaces.IBot): reply_markup = base_keyboard ) - def RegisterMessageHandler(self, a_MessageHandler, a_CheckFunc, commands=None, regexp=None, content_types=None, state=None): + def RegisterMessageHandler(self, a_MessageHandler, a_CheckFunc=None, commands=None, regexp=None, content_types=None, state=None): if a_CheckFunc: self.m_Dispatcher.register_message_handler(a_MessageHandler, a_CheckFunc, commands=commands, regexp=regexp, content_types=content_types, state=state) else: self.m_Dispatcher.register_message_handler(a_MessageHandler, commands=commands, regexp=regexp, content_types=content_types, state=state) - def RegisterCallbackHandler(self, a_CallbackHandler, a_CheckFunc, commands=None, regexp=None, content_types=None, state=None): + def RegisterCallbackHandler(self, a_CallbackHandler, a_CheckFunc=None, commands=None, regexp=None, content_types=None, state=None): if a_CheckFunc: - self.register_callback_query_handler.register_message_handler(a_CallbackHandler, a_CheckFunc, commands=commands, regexp=regexp, content_types=content_types, state=state) + self.m_Dispatcher.register_callback_query_handler(a_CallbackHandler, a_CheckFunc, commands=commands, regexp=regexp, content_types=content_types, state=state) else: - self.register_callback_query_handler.register_message_handler(a_CallbackHandler, commands=commands, regexp=regexp, content_types=content_types, state=state) + self.m_Dispatcher.register_callback_query_handler(a_CallbackHandler, commands=commands, regexp=regexp, content_types=content_types, state=state) def StartPolling(self): executor.start_polling(self.m_Dispatcher) diff --git a/bot_sys/interfaces.py b/bot_sys/interfaces.py index 2cf5681..e65a760 100644 --- a/bot_sys/interfaces.py +++ b/bot_sys/interfaces.py @@ -25,11 +25,11 @@ class IBot(ABC): pass @abstractmethod - def RegisterMessageHandler(self, a_MessageHandler, a_CheckFunc, commands=None, regexp=None, content_types=None, state=None): + def RegisterMessageHandler(self, a_MessageHandler, a_CheckFunc=None, commands=None, regexp=None, content_types=None, state=None): pass @abstractmethod - def RegisterCallbackHandler(self, a_CallbackHandler, a_CheckFunc, commands=None, regexp=None, content_types=None, state=None): + def RegisterCallbackHandler(self, a_CallbackHandler, a_CheckFunc=None, commands=None, regexp=None, content_types=None, state=None): pass @abstractmethod diff --git a/main.py b/main.py index ec5c5e7..1b5ec47 100644 --- a/main.py +++ b/main.py @@ -6,7 +6,7 @@ log_start_message = 'Бот успешно запущен!' import os from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages, bd_table -from bot_modules import mod_agregator, start, profile, backup, groups, access #, projects, , access, , tasks, needs, comments, messages, , languages +from bot_modules import mod_agregator, start, profile, backup, groups, access, projects #, projects, , access, , tasks, needs, comments, messages, , languages g_Log = log g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log) @@ -19,24 +19,35 @@ g_BotButtons = bot_messages.BotMessages(default_language) g_ModuleAgregator = mod_agregator.ModuleAgregator() mod_start_name = 'start' +mod_tasks_name = 'tasks' +mod_needs_name = 'needs' +mod_comments_name = 'comments' +mod_projects_name = 'projects' -mod_access = access.ModuleAccess([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +start_mod_list = [mod_start_name] + +mod_access = access.ModuleAccess(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_access) -mod_groups = groups.ModuleGroups([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +mod_groups = groups.ModuleGroups(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_groups) -mod_profile = profile.ModuleProfile([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +mod_profile = profile.ModuleProfile(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_profile) -mod_backup = backup.ModuleBackup([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +mod_backup = backup.ModuleBackup(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_backup) -start_mod_name_list = [#, 'projects', 'groups', 'access', , 'languages'] +start_mod_name_list = [mod_start_name, mod_tasks_name, mod_needs_name, mod_comments_name] +mod_project = projects.ModuleProjects(None, None, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +g_ModuleAgregator.AddModule(mod_project) + +start_mod_name_list = [#, '', , '', , 'languages'] mod_profile.GetName(), mod_backup.GetName(), mod_groups.GetName(), mod_access.GetName(), + mod_project.GetName(), ] mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_start) diff --git a/template/bd_item.py b/template/bd_item.py index 3ff6add..695030e 100644 --- a/template/bd_item.py +++ b/template/bd_item.py @@ -4,7 +4,7 @@ # Работа с элементом в БД from enum import Enum -from bot_sys import user_access, bot_bd, keyboard, log +from bot_sys import user_access, bot_bd, keyboard, bot_messages from bot_modules import groups_utils, access_utils from template import simple_message @@ -20,7 +20,7 @@ canсel_button_name = "🚫 Отменить" def HashPrefix(a_Str): # callback data в сообщении имеет ограниченную длину, поэтому сокращаем префикс - #log.Info(f'HashPrefix {md5(a_Str)[0:8]}: - {a_Str}') + #a_Bot.GetLog().Info(f'HashPrefix {md5(a_Str)[0:8]}: - {a_Str}') return f'{md5(a_Str)[0:8]}:' class FieldType(Enum): @@ -47,7 +47,7 @@ def GetCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): cur_buttons = [ keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()), ] - return keyboard.MakeKeyboard(cur_buttons, a_UserGroups) + return keyboard.MakeInlineKeyboardButtons(cur_buttons, a_UserGroups) return GetCancelKeyboardButtons def GetSkipAndCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): @@ -56,46 +56,46 @@ def GetSkipAndCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): keyboard.ButtonWithAccess(skip_button_name, a_AccessMode, a_AccessFunc()), keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()), ] - return keyboard.MakeKeyboard(cur_buttons, a_UserGroups) + return keyboard.MakeInlineKeyboardButtons(cur_buttons, a_UserGroups) return GetSkipAndCancelKeyboardButtons -def GetAllItemsTemplate(a_TableName): +def GetAllItemsTemplate(a_Bot, a_TableName): def GetAllItems(): - return bot_bd.SelectBDTemplate(a_TableName)() + return bot_bd.SelectBDTemplate(a_Bot, a_TableName)() return GetAllItems -def GetBDItemsTemplate(a_TableName : str, a_KeyName : str): +def GetBDItemsTemplate(a_Bot, a_TableName : str, a_KeyName : str): def GetBDItem(a_KeyValue): - return bot_bd.SQLRequestToBD(f'SELECT * FROM {a_TableName} WHERE {a_KeyName} = ?', param = ([a_KeyValue])) + return a_Bot.SQLRequest(f'SELECT * FROM {a_TableName} WHERE {a_KeyName} = ?', param = ([a_KeyValue])) return GetBDItem -def DeleteBDItemInTableTemplate(a_TableName : str, a_KeyName : str): +def DeleteBDItemInTableTemplate(a_Bot, a_TableName : str, a_KeyName : str): def DeleteBDItem(a_KeyValue): - return bot_bd.SQLRequestToBD(f'DELETE FROM {a_TableName} WHERE {a_KeyName} = ?', commit = True, return_error = True, param = ([a_KeyValue])) + return a_Bot.SQLRequest(f'DELETE FROM {a_TableName} WHERE {a_KeyName} = ?', commit = True, return_error = True, param = ([a_KeyValue])) return DeleteBDItem -def EditBDItemInTableTemplate(a_TableName : str, a_KeyName : str, a_FieldName : str): +def EditBDItemInTableTemplate(a_Bot, a_TableName : str, a_KeyName : str, a_FieldName : str): def EditBDItemInTable(a_KeyValue, a_FieldValue): - return bot_bd.SQLRequestToBD(f'UPDATE {a_TableName} SET {a_FieldName}=? WHERE {a_KeyName} = ?', commit = True, return_error = True, param = ([a_FieldValue, a_KeyValue])) + return a_Bot.SQLRequest(f'UPDATE {a_TableName} SET {a_FieldName}=? WHERE {a_KeyName} = ?', commit = True, return_error = True, param = ([a_FieldValue, a_KeyValue])) return EditBDItemInTable -def CheckAccessBDItemTemplate(a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_AccessMode : user_access.AccessMode): +def CheckAccessBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_AccessMode : user_access.AccessMode): async def CheckAccessBDItem(a_CallbackQuery : types.CallbackQuery): user_id = str(a_CallbackQuery.from_user.id) - user_groups = groups_utils.GetUserGroupData(user_id) + user_groups = groups_utils.GetUserGroupData(a_Bot, user_id) item_id = a_KeyValue - item = GetBDItemsTemplate(a_TableName, a_KeyName)(item_id) + item = GetBDItemsTemplate(a_Bot, a_TableName, a_KeyName)(item_id) if len(item) < 1: msg = item_not_found.replace('{item_id}', str(item_id)).replace('{a_TableName}', a_TableName) - log.Error(msg) - return simple_message.WorkFuncResult(msg), None + a_Bot.GetLog().Error(msg) + return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(msg)), None result_work_func = await a_WorkFunc(a_CallbackQuery, item[0]) if result_work_func is None or result_work_func.string_message is None: return result_work_func, result_work_func if not result_work_func.item_access is None and not user_access.CheckAccessString(result_work_func.item_access, user_groups, a_AccessMode): - return simple_message.WorkFuncResult(access_utils.access_denied_message), None + return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(access_utils.access_denied_message)), None return None, result_work_func return CheckAccessBDItem diff --git a/template/bd_item_add.py b/template/bd_item_add.py index 84fe313..394a950 100644 --- a/template/bd_item_add.py +++ b/template/bd_item_add.py @@ -3,23 +3,18 @@ # Добавление элемента в БД -from bot_sys import user_access, bot_bd, log -from bot_modules import access, groups +from bot_sys import user_access, bot_bd, bot_messages +from bot_modules import access_utils, groups_utils from template import simple_message, bd_item_select, bd_item -from aiogram import types -from aiogram.dispatcher import FSMContext -from aiogram.dispatcher.filters.state import State, StatesGroup - - cancel_message = ''' 🚫 Добавление отменено ''' -def StartAddBDItemTemplate(a_FSM, a_FSMStart, a_MessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.ADD): - async def StartAddBDItem(a_CallbackQuery : types.CallbackQuery, state : FSMContext): +def StartAddBDItemTemplate(a_Bot, a_FSM, a_FSMStart, a_MessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.ADD): + async def StartAddBDItem(a_CallbackQuery, state): user_id = str(a_CallbackQuery.from_user.id) - user_groups = groups.GetUserGroupData(user_id) + user_groups = groups.GetUserGroupData(a_Bot, user_id) parent_id = bd_item.GetKeyDataFromCallbackMessage(a_CallbackQuery, a_Prefix) res_of_work_func = None check = None @@ -30,7 +25,7 @@ def StartAddBDItemTemplate(a_FSM, a_FSMStart, a_MessageFunc, a_ParentTableName, item_data[a_ParentKeyFieldName] = parent_id if parent_id: - check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_CallbackQuery) + check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_Bot, a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_CallbackQuery) else: res_of_work_func = await a_MessageFunc(a_CallbackQuery, None) @@ -39,36 +34,36 @@ def StartAddBDItemTemplate(a_FSM, a_FSMStart, a_MessageFunc, a_ParentTableName, check.keyboard_func = a_FinishButtonFunc return check return res_of_work_func - return simple_message.SimpleMessageTemplateLegacy(StartAddBDItem, a_ButtonFunc, a_AccessFunc, access_mode) + return simple_message.SimpleMessageTemplate(a_Bot, StartAddBDItem, a_ButtonFunc, None, a_AccessFunc, access_mode) -def FinishAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): - return FinishOrNextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_ButtonFunc, True, access_mode = access_mode, field_type = field_type) +def FinishAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): + return FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_ButtonFunc, True, access_mode = access_mode, field_type = field_type) -def NextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): - return FinishOrNextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, False, access_mode = access_mode, field_type = field_type) +def NextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): + return FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, False, access_mode = access_mode, field_type = field_type) -def FinishOrNextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, a_Finish, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): - async def FinishAddBDItem(a_Message : types.CallbackQuery, state : FSMContext): +def FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, a_Finish, access_mode = user_access.AccessMode.ADD, field_type = bd_item.FieldType.text): + async def FinishAddBDItem(a_Message, state): state_func = None if a_Finish: state_func = state.finish else: state_func = a_FSM.next user_id = str(a_Message.from_user.id) - user_groups = groups.GetUserGroupData(user_id) + user_groups = groups.GetUserGroupData(a_Bot, user_id) error = None res_of_work_func = None check = None async with state.proxy() as item_data: if a_Message.text == bd_item.canсel_button_name: await state.finish() - return simple_message.WorkFuncResult(cancel_message, keyboard_func = a_FinishButtonFunc) + return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(cancel_message), keyboard_func = a_FinishButtonFunc) parent_id = None if a_ParentKeyFieldName: parent_id = item_data[a_ParentKeyFieldName] if parent_id: - check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_Message) + check, res_of_work_func = await bd_item.CheckAccessBDItemTemplate(a_Bot, a_ParentTableName, a_ParentKeyFieldName, parent_id, a_MessageFunc, access_mode)(a_Message) else: res_of_work_func = await a_MessageFunc(a_Message, None) @@ -83,7 +78,7 @@ def FinishOrNextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_P else: if a_Message.photo == None or len(a_Message.photo) == 0: await state.finish() - return simple_message.WorkFuncResult(error_photo_type_message, keyboard_func = a_FinishButtonFunc) + return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(error_photo_type_message), keyboard_func = a_FinishButtonFunc) field_value = a_Message.photo[0].file_id else: field_value = a_Message.text @@ -92,31 +87,31 @@ def FinishOrNextAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_P res, error = a_AddBDItemFunc(item_data, user_id) await state_func() if error: - return simple_message.WorkFuncResult(error) + return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(error)) return res_of_work_func - return simple_message.SimpleMessageTemplateLegacy(FinishAddBDItem, a_ButtonFunc, a_AccessFunc, access_mode) + return simple_message.SimpleMessageTemplate(a_Bot, FinishAddBDItem, a_ButtonFunc, None, a_AccessFunc, access_mode) -def AddBDItem3RegisterHandlers(dp, a_StartCheckFunc, a_FSM, a_FSMName, a_FSMDesc, a_FSMPhoto, a_AddBDItemFunc, a_AddNameMessageFunc, a_AddDescMessageFunc, a_AddPhotoMessageFunc, a_FinishMessageFunc, a_ParentPrefix, a_ParentTableName : str, a_ParentKeyFieldName, a_NameField, a_DescField, a_PhotoField, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.ADD): +def AddBDItem3RegisterHandlers(a_Bot, a_StartCheckFunc, a_FSM, a_FSMName, a_FSMDesc, a_FSMPhoto, a_AddBDItemFunc, a_AddNameMessageFunc, a_AddDescMessageFunc, a_AddPhotoMessageFunc, a_FinishMessageFunc, a_ParentPrefix, a_ParentTableName : str, a_ParentKeyFieldName, a_NameField, a_DescField, a_PhotoField, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.ADD): keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_AccessFunc, access_mode) keyboard_skip_and_cancel = bd_item.GetSkipAndCancelKeyboardButtonsTemplate(a_AccessFunc, access_mode) - reg_func = dp.register_message_handler + reg_func = a_Bot.RegisterMessageHandler if a_ParentTableName: - reg_func = dp.register_callback_query_handler - reg_func(StartAddBDItemTemplate(a_FSM, a_FSMName, a_AddNameMessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_ParentPrefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), a_StartCheckFunc) + reg_func = a_Bot.RegisterCallbackHandler + reg_func(StartAddBDItemTemplate(a_Bot, a_FSM, a_FSMName, a_AddNameMessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_ParentPrefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), a_StartCheckFunc) - dp.register_message_handler(NextAddBDItemTemplate(a_FSM, None, a_ParentTableName, a_ParentKeyFieldName, a_NameField, a_AddDescMessageFunc, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.text), state = a_FSMName) - dp.register_message_handler(NextAddBDItemTemplate(a_FSM, None, a_ParentTableName, a_ParentKeyFieldName, a_DescField, a_AddPhotoMessageFunc, a_AccessFunc, keyboard_skip_and_cancel, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.text), state = a_FSMDesc) - dp.register_message_handler(FinishAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_PhotoField, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.photo), content_types = ['photo', 'text'], state = a_FSMPhoto) + a_Bot.RegisterMessageHandler(NextAddBDItemTemplate(a_Bot, a_FSM, None, a_ParentTableName, a_ParentKeyFieldName, a_NameField, a_AddDescMessageFunc, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.text), state = a_FSMName) + a_Bot.RegisterMessageHandler(NextAddBDItemTemplate(a_Bot, a_FSM, None, a_ParentTableName, a_ParentKeyFieldName, a_DescField, a_AddPhotoMessageFunc, a_AccessFunc, keyboard_skip_and_cancel, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.text), state = a_FSMDesc) + a_Bot.RegisterMessageHandler(FinishAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_PhotoField, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = bd_item.FieldType.photo), content_types = ['photo', 'text'], state = a_FSMPhoto) -def AddBDItem1RegisterHandlers(dp, a_StartCheckFunc, a_FSM, a_AddBDItemFunc, a_AddMessageFunc, a_FinishMessageFunc, a_ParentPrefix, a_ParentTableName : str, a_ParentKeyFieldName, a_FieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, a_FieldType, access_mode = user_access.AccessMode.ADD): +def AddBDItem1RegisterHandlers(a_Bot, a_StartCheckFunc, a_FSM, a_AddBDItemFunc, a_AddMessageFunc, a_FinishMessageFunc, a_ParentPrefix, a_ParentTableName : str, a_ParentKeyFieldName, a_FieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, a_FieldType, access_mode = user_access.AccessMode.ADD): keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_AccessFunc, access_mode) - reg_func = dp.register_message_handler + reg_func = a_Bot.RegisterMessageHandler if a_ParentTableName: - reg_func = dp.register_callback_query_handler - reg_func(StartAddBDItemTemplate(a_FSM, a_FSM.bd_item, a_AddMessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_ParentPrefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), a_StartCheckFunc) - finish_handler = FinishAddBDItemTemplate(a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = a_FieldType) + reg_func = a_Bot.RegisterCallbackHandler + reg_func(StartAddBDItemTemplate(a_Bot, a_FSM, a_FSM.bd_item, a_AddMessageFunc, a_ParentTableName, a_ParentKeyFieldName, a_ParentPrefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), a_StartCheckFunc) + finish_handler = FinishAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableName, a_ParentKeyFieldName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = a_FieldType) if a_FieldType == bd_item.FieldType.photo: - dp.register_message_handler(finish_handler, content_types = ['photo', 'text'], state = a_FSM.bd_item) + a_Bot.RegisterMessageHandler(finish_handler, content_types = ['photo', 'text'], state = a_FSM.bd_item) else: - dp.register_message_handler(finish_handler, state = a_FSM.bd_item) + a_Bot.RegisterMessageHandler(finish_handler, state = a_FSM.bd_item) diff --git a/template/bd_item_delete.py b/template/bd_item_delete.py index 6167bea..4228e7e 100644 --- a/template/bd_item_delete.py +++ b/template/bd_item_delete.py @@ -4,40 +4,38 @@ # удаление элемента в БД from bot_sys import user_access, bot_bd, keyboard -from bot_modules import access, groups +from bot_modules import access_utils, groups_utils from template import simple_message, bd_item_select, bd_item -from aiogram import types - -def DeleteBDItemTemplate(a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, delete = True, access_mode = user_access.AccessMode.DELETE): - async def DeleteBDItem(a_CallbackQuery : types.CallbackQuery, state = None): +def DeleteBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, delete = True, access_mode = user_access.AccessMode.DELETE): + async def DeleteBDItem(a_CallbackQuery, state = None): user_id = str(a_CallbackQuery.from_user.id) - user_groups = groups.GetUserGroupData(user_id) + user_groups = groups.GetUserGroupData(a_Bot, user_id) item_id = str(a_CallbackQuery.data).replace(a_Prefix, '') - check, res_of_pre_del = await bd_item.CheckAccessBDItemTemplate(a_TableName, a_KeyName, item_id, a_PreDeleteWorkFunc, access_mode)(a_CallbackQuery) + check, res_of_pre_del = await bd_item.CheckAccessBDItemTemplate(a_Bot, a_TableName, a_KeyName, item_id, a_PreDeleteWorkFunc, access_mode)(a_CallbackQuery) if not check is None: return check if not delete: return res_of_pre_del - result, error = bd_item.DeleteBDItemInTableTemplate(a_TableName, a_KeyName)(item_id) + result, error = bd_item.DeleteBDItemInTableTemplate(a_Bot, a_TableName, a_KeyName)(item_id) if not error is None: msg = error - log.Error(error) + a_Bot.GetLog().Error(error) return simple_message.WorkFuncResult(error) return await a_PostDeleteWorkFunc(a_CallbackQuery, item_id) - return simple_message.SimpleMessageTemplateLegacy(DeleteBDItem, a_ButtonFunc, a_AccessFunc, access_mode) + return simple_message.SimpleMessageTemplate(a_Bot, DeleteBDItem, a_ButtonFunc, None, a_AccessFunc, access_mode) -def DeleteBDItemRegisterHandlers(dp, a_PrevPrefix, a_StartCheckFunc, a_TableName : str, a_KeyName, a_ParentIDFieldName,a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.DELETE): - reg_func = dp.register_message_handler +def DeleteBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_StartCheckFunc, a_TableName : str, a_KeyName, a_ParentIDFieldName,a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.DELETE): + reg_func = a_Bot.RegisterMessageHandler if a_ParentIDFieldName: - reg_func = dp.register_callback_query_handler + reg_func = a_Bot.RegisterCallbackHandler a_Prefix = bd_item.HashPrefix(f'delete_{a_TableName}_{a_KeyName}:') - sel_handler = bd_item_select.SelectDBItemTemplate(a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode) + sel_handler = bd_item_select.SelectDBItemTemplate(a_Bot, a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode) reg_func(sel_handler, a_StartCheckFunc) - dp.register_callback_query_handler(DeleteBDItemTemplate(a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), bd_item.GetCheckForPrefixFunc(a_Prefix)) + a_Bot.RegisterCallbackHandler(DeleteBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), bd_item.GetCheckForPrefixFunc(a_Prefix)) diff --git a/template/bd_item_edit.py b/template/bd_item_edit.py index 99e3e44..aa3fec4 100644 --- a/template/bd_item_edit.py +++ b/template/bd_item_edit.py @@ -3,14 +3,10 @@ # Редактирование элемента в БД -from bot_sys import user_access, bot_bd, log -from bot_modules import access, groups +from bot_sys import user_access, bot_bd +from bot_modules import access_utils, groups_utils from template import simple_message, bd_item_select, bd_item, bd_item_add -from aiogram import types -from aiogram.dispatcher import FSMContext -from aiogram.dispatcher.filters.state import State, StatesGroup - cancel_message = ''' 🚫 Редактирование отменено ''' @@ -19,33 +15,33 @@ error_photo_type_message = ''' 🚫 Фотографий не найдено ''' -def StartEditBDItemTemplate(a_FSM, a_MessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.EDIT): - return bd_item_add.StartAddBDItemTemplate(a_FSM, a_FSM.item_field, a_MessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = access_mode) +def StartEditBDItemTemplate(a_Bot, a_FSM, a_MessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = user_access.AccessMode.EDIT): + return bd_item_add.StartAddBDItemTemplate(a_Bot, a_FSM, a_FSM.item_field, a_MessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, a_ButtonFunc, a_FinishButtonFunc, access_mode = access_mode) -def FinishEditBDItemTemplate(a_FSM, a_TableName, a_KeyName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = bd_item.FieldType.text): +def FinishEditBDItemTemplate(a_Bot, a_FSM, a_TableName, a_KeyName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = bd_item.FieldType.text): def EditBDItemFunc(a_ItemData, a_UserID): item_id = a_ItemData[a_KeyName] field_value = a_ItemData[a_FieldName] - res, error = bd_item.EditBDItemInTableTemplate(a_TableName, a_KeyName, a_FieldName)(item_id, field_value) + res, error = bd_item.EditBDItemInTableTemplate(a_Bot, a_TableName, a_KeyName, a_FieldName)(item_id, field_value) if error: - log.Error(f'Пользователю {a_UserID} не удалось изменить поле в таблице {a_TableName} ключу {a_KeyName}={item_id}. Новое значение поля {a_FieldName}={field_value}. Ошибка: {error}') + a_Bot.GetLog().Error(f'Пользователю {a_UserID} не удалось изменить поле в таблице {a_TableName} ключу {a_KeyName}={item_id}. Новое значение поля {a_FieldName}={field_value}. Ошибка: {error}') else: - log.Success(f'Пользователь {a_UserID} изменил поле в таблице {a_TableName} ключу {a_KeyName}={item_id}. Новое значение поля {a_FieldName}={field_value}.') + a_Bot.GetLog().Success(f'Пользователь {a_UserID} изменил поле в таблице {a_TableName} ключу {a_KeyName}={item_id}. Новое значение поля {a_FieldName}={field_value}.') return res, error - return bd_item_add.FinishAddBDItemTemplate(a_FSM, EditBDItemFunc, a_TableName, a_KeyName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode, field_type = field_type) + return bd_item_add.FinishAddBDItemTemplate(a_Bot, a_FSM, EditBDItemFunc, a_TableName, a_KeyName, a_FieldName, a_MessageFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode, field_type = field_type) -def EditBDItemRegisterHandlers(dp, a_PrevPrefix, a_FSM, a_StartCheckFunc, a_StartMessage, a_EditMessageFunc, a_FinishMessageFunc, a_TableName : str, a_KeyName, a_ParentIDFieldName, a_FieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = bd_item.FieldType.text): - reg_func = dp.register_message_handler +def EditBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_FSM, a_StartCheckFunc, a_StartMessage, a_EditMessageFunc, a_FinishMessageFunc, a_TableName : str, a_KeyName, a_ParentIDFieldName, a_FieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = bd_item.FieldType.text): + reg_func = a_Bot.RegisterMessageHandler if a_ParentIDFieldName: - reg_func = dp.register_callback_query_handler + reg_func = a_Bot.RegisterCallbackHandler keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_AccessFunc, access_mode) a_Prefix = bd_item.HashPrefix(f'edit_{a_TableName}_{a_KeyName}_{a_FieldName}:') - sel_handler = bd_item_select.SelectDBItemTemplate(a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode) + sel_handler = bd_item_select.SelectDBItemTemplate(a_Bot, a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode) reg_func(sel_handler, a_StartCheckFunc) - dp.register_callback_query_handler(StartEditBDItemTemplate(a_FSM, a_EditMessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), bd_item.GetCheckForPrefixFunc(a_Prefix)) + a_Bot.RegisterCallbackHandler(StartEditBDItemTemplate(a_Bot, a_FSM, a_EditMessageFunc, a_TableName, a_KeyName, a_Prefix, a_AccessFunc, keyboard_cancel, a_ButtonFunc, access_mode), bd_item.GetCheckForPrefixFunc(a_Prefix)) if field_type == bd_item.FieldType.photo: - dp.register_message_handler(FinishEditBDItemTemplate(a_FSM, a_TableName, a_KeyName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = field_type), content_types = ['photo', 'text'], state = a_FSM.item_field) + a_Bot.RegisterMessageHandler(FinishEditBDItemTemplate(a_Bot, a_FSM, a_TableName, a_KeyName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = field_type), content_types = ['photo', 'text'], state = a_FSM.item_field) else: - dp.register_message_handler(FinishEditBDItemTemplate(a_FSM, a_TableName, a_KeyName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = field_type), state = a_FSM.item_field) + a_Bot.RegisterMessageHandler(FinishEditBDItemTemplate(a_Bot, a_FSM, a_TableName, a_KeyName, a_FieldName, a_FinishMessageFunc, a_AccessFunc, a_ButtonFunc, access_mode, field_type = field_type), state = a_FSM.item_field) diff --git a/template/bd_item_select.py b/template/bd_item_select.py index a39a00f..0109ee5 100644 --- a/template/bd_item_select.py +++ b/template/bd_item_select.py @@ -4,19 +4,17 @@ # Просмотр элемента в БД from bot_sys import user_access, bot_bd, keyboard -from bot_modules import access, groups +from bot_modules import access_utils, groups_utils from template import simple_message, bd_item -from aiogram import types - -def GetBDItemsListKeyboardButtonsTemplate(a_TableName : str, a_ParentIDFieldName, a_PrevPrefix, a_NextPrefix : str, a_GetButtonNameAndKeyValueAndAccessFunc, access_mode = user_access.AccessMode.VIEW): +def GetBDItemsListKeyboardButtonsTemplate(a_Bot, a_TableName : str, a_ParentIDFieldName, a_PrevPrefix, a_NextPrefix : str, a_GetButtonNameAndKeyValueAndAccessFunc, access_mode = user_access.AccessMode.VIEW): def GetBDItemsListKeyboardButtons(a_Message, a_UserGroups): parent_id = bd_item.GetKeyDataFromCallbackMessage(a_Message, a_PrevPrefix) items = [] if a_ParentIDFieldName and parent_id and parent_id != '': - items = bd_item.GetBDItemsTemplate(a_TableName, a_ParentIDFieldName)(parent_id) + items = bd_item.GetBDItemsTemplate(a_Bot, a_TableName, a_ParentIDFieldName)(parent_id) else: - items = bd_item.GetAllItemsTemplate(a_TableName)() + items = bd_item.GetAllItemsTemplate(a_Bot, a_TableName)() items_button_list = [] for t in items: @@ -26,26 +24,26 @@ def GetBDItemsListKeyboardButtonsTemplate(a_TableName : str, a_ParentIDFieldName if bname: b = keyboard.InlineButtonWithAccess(bname, a_NextPrefix, key_value, access, access_mode) items_button_list += [b] - return keyboard.MakeInlineKeyboard(items_button_list, a_UserGroups) + return keyboard.MakeInlineKeyboardButtons(items_button_list, a_UserGroups) return GetBDItemsListKeyboardButtons -def SelectDBItemTemplate(a_TableName : str, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_NextPrefix, access_mode = user_access.AccessMode.VIEW): - keyboard_func = GetBDItemsListKeyboardButtonsTemplate(a_TableName, a_ParentIDFieldName, a_PrevPrefix, a_NextPrefix, a_GetButtonNameAndKeyValueAndAccessFunc) - return simple_message.InfoMessageTemplateLegacy(a_StartMessage, keyboard_func, a_AccessFunc, access_mode) +def SelectDBItemTemplate(a_Bot, a_TableName : str, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_NextPrefix, access_mode = user_access.AccessMode.VIEW): + keyboard_func = GetBDItemsListKeyboardButtonsTemplate(a_Bot, a_TableName, a_ParentIDFieldName, a_PrevPrefix, a_NextPrefix, a_GetButtonNameAndKeyValueAndAccessFunc) + return simple_message.InfoMessageTemplate(a_Bot, a_StartMessage, keyboard_func, None, a_AccessFunc, access_mode) -def FirstSelectBDItemRegisterHandlers(dp, a_PrefixBase, a_ButtonName, a_TableName : str, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): +def FirstSelectBDItemRegisterHandlers(a_Bot, a_PrefixBase, a_ButtonName, a_TableName : str, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): a_Prefix = bd_item.HashPrefix(f'first_select_{a_TableName}_{a_KeyName}_in_base_{a_PrefixBase}:') - sel_handler = SelectDBItemTemplate(a_TableName, None, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, None, a_Prefix, access_mode = access_mode) - dp.register_message_handler(sel_handler, text = a_ButtonName) + sel_handler = SelectDBItemTemplate(a_Bot, a_TableName, None, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, None, a_Prefix, access_mode = access_mode) + a_Bot.RegisterMessageHandler(sel_handler, bd_item.GetCheckForTextFunc(a_ButtonName)) return a_Prefix -def NextSelectBDItemRegisterHandlers(dp, a_PrevPrefix, a_ParentIDFieldName, a_TableName : str, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): +def NextSelectBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_ParentIDFieldName, a_TableName : str, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): a_Prefix = bd_item.HashPrefix(f'next_select_{a_TableName}_{a_KeyName}_{a_ParentIDFieldName}_after_prefix_{a_PrevPrefix}:') - sel_handler = SelectDBItemTemplate(a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode = access_mode) - dp.register_callback_query_handler(sel_handler, bd_item.GetCheckForPrefixFunc(a_PrevPrefix)) + sel_handler = SelectDBItemTemplate(a_Bot, a_TableName, a_ParentIDFieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_PrevPrefix, a_Prefix, access_mode = access_mode) + a_Bot.RegisterCallbackHandler(sel_handler, bd_item.GetCheckForPrefixFunc(a_PrevPrefix)) return a_Prefix diff --git a/template/bd_item_view.py b/template/bd_item_view.py index 6e896be..e40b06f 100644 --- a/template/bd_item_view.py +++ b/template/bd_item_view.py @@ -4,21 +4,19 @@ # Просмотр элемента в БД from bot_sys import user_access, bot_bd, keyboard -from bot_modules import access, groups +from bot_modules import access_utils, groups_utils from template import simple_message, bd_item_select, bd_item_delete, bd_item -from aiogram import types +def ShowBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): + return bd_item_delete.DeleteBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_WorkFunc, None, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = access_mode, delete = False) -def ShowBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): - return bd_item_delete.DeleteBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, None, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = access_mode, delete = False) +def ShowBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): + a_Bot.RegisterCallbackHandler(ShowBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_ShowItemWorkFunc, a_PrevPrefix, a_AccessFunc, a_ButtonFunc, access_mode = access_mode), bd_item.GetCheckForPrefixFunc(a_PrevPrefix)) -def ShowBDItemRegisterHandlers(dp, a_PrevPrefix, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): - dp.register_callback_query_handler(ShowBDItemTemplate(a_TableName, a_KeyName, a_ShowItemWorkFunc, a_PrevPrefix, a_AccessFunc, a_ButtonFunc, access_mode = access_mode), bd_item.GetCheckForPrefixFunc(a_PrevPrefix)) +def FirstSelectAndShowBDItemRegisterHandlers(a_Bot, a_ButtonName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): + a_Prefix = bd_item_select.FirstSelectBDItemRegisterHandlers(a_Bot, '', a_ButtonName, a_TableName, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = access_mode) + ShowBDItemRegisterHandlers(a_Bot, a_Prefix, a_TableName, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode) -def FirstSelectAndShowBDItemRegisterHandlers(dp, a_ButtonName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): - a_Prefix = bd_item_select.FirstSelectBDItemRegisterHandlers(dp, '', a_ButtonName, a_TableName, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = access_mode) - ShowBDItemRegisterHandlers(dp, a_Prefix, a_TableName, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode) - -def LastSelectAndShowBDItemRegisterHandlers(dp, a_PrevPrefix, a_ParentIDFieldName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): - a_Prefix = bd_item_select.NextSelectBDItemRegisterHandlers(dp, a_PrevPrefix, a_ParentIDFieldName, a_TableName, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = access_mode) - ShowBDItemRegisterHandlers(dp, a_Prefix, a_TableName, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode) +def LastSelectAndShowBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_ParentIDFieldName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): + a_Prefix = bd_item_select.NextSelectBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_ParentIDFieldName, a_TableName, a_KeyName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, access_mode = access_mode) + ShowBDItemRegisterHandlers(a_Bot, a_Prefix, a_TableName, a_KeyName, a_ShowItemWorkFunc, a_AccessFunc, a_ButtonFunc, access_mode = access_mode) diff --git a/template/simple_message.py b/template/simple_message.py index ba4c85a..957cf6b 100644 --- a/template/simple_message.py +++ b/template/simple_message.py @@ -29,9 +29,10 @@ async def AccessDeniedMessage(a_Bot, a_GetButtonsFunc, a_UserID, a_Message, user return await SendMessage(a_Bot, bot_messages.MakeBotMessage(access_utils.access_denied_message), a_GetButtonsFunc, None, a_UserID, a_Message, user_groups) class WorkFuncResult(): - def __init__(self, a_BotMessage, item_access = None): + def __init__(self, a_BotMessage, keyboard_func = None, item_access = None): self.m_BotMessage = a_BotMessage self.item_access = item_access + self.keyboard_func = keyboard_func def InfoMessageTemplate(a_Bot, a_HelpMessage, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): async def GetMessage(a_Message : types.message, state = None): @@ -51,6 +52,10 @@ def SimpleMessageTemplate(a_Bot, a_WorkFunc, a_GetButtonsFunc, a_GetInlineButton if res is None: return + keyboard_func = a_GetInlineButtonsFunc + if res.keyboard_func: + keyboard_func = res.keyboard_func + msg = res.m_BotMessage if msg is None: return @@ -65,6 +70,6 @@ def SimpleMessageTemplate(a_Bot, a_WorkFunc, a_GetButtonsFunc, a_GetInlineButton msg.GetDesc(), msg.GetPhotoID(), ProxyGetButtonsTemplate(a_GetButtonsFunc)(a_Message, user_groups), - ProxyGetButtonsTemplate(a_GetInlineButtonsFunc)(a_Message, user_groups) + ProxyGetButtonsTemplate(keyboard_func)(a_Message, user_groups) ) return SimpleMessage