Browse Source

В первом приближении редактирование проектов

test_bot
Alexei 2 years ago
parent
commit
2bf933281f
  1. 2
      bot_modules/profile.py
  2. 107
      bot_modules/projects.py
  3. 2
      bot_modules/start.py
  4. 61
      template/bd_item.py
  5. 41
      template/bd_item_delete.py
  6. 94
      template/bd_item_edit.py
  7. 14
      template/bd_item_select.py
  8. 12
      template/bd_item_view.py
  9. 7
      template/simple_message.py

2
bot_modules/profile.py

@ -45,7 +45,7 @@ def GetStartKeyboardButtons(a_UserGroups):
# ---------------------------------------------------------
# Обработка сообщений
async def ProfileOpen(a_Message):
async def ProfileOpen(a_Message, state = None):
user_info = GetUserInfo(a_Message.from_user.id)
msg = profile_message
if not user_info is None:

107
bot_modules/projects.py

@ -5,7 +5,7 @@
from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, access, groups
from template import bd_item_view, simple_message, bd_item_delete
from template import bd_item_view, simple_message, bd_item_delete, bd_item_edit
from aiogram import Bot, types
@ -33,12 +33,16 @@ module_name = 'projects'
table_name = 'projects'
key_name = 'projectID'
photo_field = 'projectPhoto'
name_field = 'projectName'
desc_field = 'projectDesc'
access_field = 'projectAccess'
init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}(
projectPhoto TEXT,
projectName TEXT,
projectDesc TEXT,
projectAccess TEXT,
{photo_field} TEXT,
{name_field} TEXT,
{desc_field} TEXT,
{access_field} TEXT,
{key_name} INTEGER PRIMARY KEY
)''',
f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=va', '{user_access.user_access_group_all}=va');"
@ -91,39 +95,31 @@ project_success_create_message = '✅ Проект успешно добавле
project_success_delete_message = '✅ Проект успешно удалён!'
project_success_edit_message = '✅ Проект успешно отредактирован!'
project_create_message_0= '''
Редактирование проекта.
# Редактирование проекта.
Пожалуйста, выберите проект:
project_start_edit_message= '''
Пожалуйста, выберите действие:
'''
project_edit_message_1 = '''
Редактирование проекта. Шаг 1
project_edit_photo_message = '''
Загрузите новую обложку для проекта (Фото):
Она будет отображаться в его описании.
'''
project_edit_message_2 = '''
Редактирование проекта. Шаг 2
project_edit_name_message = '''
Текущее название проекта:
@proj_name
Введите новое название проекта:
'''
project_edit_message_3 = '''
Редактирование проекта. Шаг 3
project_edit_desc_message = '''
Текущее описание проекта:
@proj_desc
Введите новое описание проекта:
'''
project_cancel_edit_message = '🚫 Редактирование проекта отменено'
project_select_to_edit_message = '''
Выберите проект, который вы хотите отредактировать.
'''
@ -139,20 +135,25 @@ list_project_button_name = "📃 Список проектов"
add_project_button_name = "✅ Добавить проект"
del_project_button_name = "❌ Удалить проект"
edit_project_button_name = "🛠 Редактировать проект"
projects_canсel_button_name = "🚫 Отменить"
projects_skip_button_name = "⏩ Пропустить"
# Префиксы
select_project_callback_prefix = 'sel_project:'
delete_project_callback_prefix = 'del_project:'
select_to_edit_project_callback_prefix = 'sel_to_edit_project:'
edit_project_photo_button_name = "🛠 Изменить изображение"
edit_project_name_button_name = "🛠 Изменить название"
edit_project_desc_button_name = "🛠 Изменить описание"
# ---------------------------------------------------------
# Работа с кнопками
def GetEditProjectKeyboardButtons(a_UserGroups):
cur_buttons = [
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()),
]
mods = [start]
return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups)
def GetStartProjectKeyboardButtons(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()),
@ -161,26 +162,6 @@ def GetEditProjectKeyboardButtons(a_UserGroups):
mods = [start]
return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups)
def GetCancelKeyboardButtons(a_UserGroups):
cur_buttons = [
keyboard.ButtonWithAccess(projects_canсel_button_name, user_access.AccessMode.VIEW, GetAccess()),
]
return keyboard.MakeKeyboard(cur_buttons, a_UserGroups)
def GetSkipAndCancelKeyboardButtons(a_UserGroups):
cur_buttons = [
keyboard.ButtonWithAccess(projects_skip_button_name, user_access.AccessMode.VIEW, GetAccess()),
keyboard.ButtonWithAccess(projects_canсel_button_name, user_access.AccessMode.VIEW, GetAccess()),
]
return keyboard.MakeKeyboard(cur_buttons, a_UserGroups)
def GetProjectsListKeyboardButtons(a_UserGroups, a_Prefix):
projects = GetProjectList()
projects_button_list = []
for t in projects:
projects_button_list += [keyboard.Button(str(t[1]), t[3])]
return keyboard.MakeInlineKeyboard(projects_button_list, a_Prefix)
# ---------------------------------------------------------
# Обработка сообщений
@ -188,6 +169,7 @@ def GetButtonNameAndKeyValueAndAccess(a_Item):
# projectName projectID projectAccess
return a_Item[1], a_Item[4], a_Item[3]
def ShowMessageTemplate(a_StringMessage):
async def ShowProject(a_CallbackQuery : types.CallbackQuery, a_Item):
if (len(a_Item) < 4):
return simple_message.WorkFuncResult(error_find_proj_message)
@ -196,18 +178,20 @@ async def ShowProject(a_CallbackQuery : types.CallbackQuery, a_Item):
name = a_Item[1]
desc = a_Item[2]
access = a_Item[3]
msg = project_open_message.replace('@proj_name', name).replace('@proj_desk', desc)
msg = a_StringMessage.replace('@proj_name', name).replace('@proj_desk', desc)
print(msg)
return simple_message.WorkFuncResult(msg, photo_id = photo_id, item_access = access)
return ShowProject
select_handler = 0
# стартовое сообщение
async def ProjectsOpen(a_Message : types.message):
async def ProjectsOpen(a_Message : types.message, state = None):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
await a_Message.answer(base_project_message, reply_markup = GetEditProjectKeyboardButtons(user_groups))
await a_Message.answer(base_project_message, reply_markup = GetStartProjectKeyboardButtons(user_groups))
await select_handler(a_Message)
return None
'''
# Создание нового проекта
def GetProjectData(a_ProjectID):
project = GetProject(a_ProjectID)
@ -340,7 +324,7 @@ async def ProjectEditDescLoad(a_Message : types.message, state : FSMContext):
log.Success(f'Изменён проект {prjName} пользователем {a_Message.from_user.id}.')
await state.finish()
await a_Message.answer(project_success_edit_message, reply_markup = GetEditProjectKeyboardButtons(user_groups))
'''
# Удаление проекта
async def ProjectPreDelete(a_CallbackQuery : types.CallbackQuery, a_Item):
@ -409,13 +393,14 @@ def GetModuleButtons():
# Обработка кнопок
def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(simple_message.SimpleMessageTemplate(ProjectsOpen, GetEditProjectKeyboardButtons, GetAccess), text = projects_button_name)
# Список проектов
dp.register_message_handler(simple_message.SimpleMessageTemplate(ProjectsOpen, GetStartProjectKeyboardButtons, GetAccess), text = projects_button_name)
global select_handler
select_handler = bd_item_view.SelectAndShowBDItemRegisterHandlers(dp, list_project_button_name, table_name, key_name, ShowProject, GetButtonNameAndKeyValueAndAccess, select_project_message, GetAccess, GetEditProjectKeyboardButtons)
bd_item_delete.DeleteBDItemRegisterHandlers(dp, del_project_button_name, table_name, key_name, ProjectPreDelete, ProjectPostDelete, GetButtonNameAndKeyValueAndAccess, select_project_message, GetAccess, GetEditProjectKeyboardButtons)
select_handler = bd_item_view.SelectAndShowBDItemRegisterHandlers(dp, list_project_button_name, table_name, key_name, ShowMessageTemplate(project_open_message), GetButtonNameAndKeyValueAndAccess, select_project_message, GetAccess, GetStartProjectKeyboardButtons)
# Удаление проекта
bd_item_delete.DeleteBDItemRegisterHandlers(dp, del_project_button_name, table_name, key_name, ProjectPreDelete, ProjectPostDelete, GetButtonNameAndKeyValueAndAccess, select_project_message, GetAccess, GetStartProjectKeyboardButtons)
'''
# Добавление проекта
dp.register_message_handler(ProjectCreate, text = add_project_button_name)
dp.register_message_handler(ProjectPhotoSkip, text = projects_skip_button_name, state = FSMCreateProject.prjPhoto)
@ -424,8 +409,13 @@ def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(ProjectCreateCancel, text = projects_canсel_button_name, state = FSMCreateProject.prjDesc)
dp.register_message_handler(ProjectPhotoLoad, content_types = ['photo'], state = FSMCreateProject.prjPhoto)
dp.register_message_handler(ProjectNameLoad, state = FSMCreateProject.prjName)
dp.register_message_handler(ProjectDescLoad, state = FSMCreateProject.prjDesc)
dp.register_message_handler(ProjectDescLoad, state = FSMCreateProject.prjDesc)'''
# Редактирование проекта
dp.register_message_handler(simple_message.InfoMessageTemplate(project_start_edit_message, GetEditProjectKeyboardButtons, GetAccess, access_mode = user_access.AccessMode.EDIT), text = edit_project_button_name)
bd_item_edit.EditBDItemRegisterHandlers(dp, edit_project_photo_button_name, project_select_to_edit_message, ShowMessageTemplate(project_edit_photo_message), ShowMessageTemplate(project_success_edit_message), table_name, key_name, photo_field, GetButtonNameAndKeyValueAndAccess, GetAccess, GetEditProjectKeyboardButtons, access_mode = user_access.AccessMode.EDIT, field_type = bd_item_edit.FieldType.photo)
bd_item_edit.EditBDItemRegisterHandlers(dp, edit_project_name_button_name, project_select_to_edit_message, ShowMessageTemplate(project_edit_name_message), ShowMessageTemplate(project_success_edit_message), table_name, key_name, name_field, GetButtonNameAndKeyValueAndAccess, GetAccess, GetEditProjectKeyboardButtons, access_mode = user_access.AccessMode.EDIT, field_type = bd_item_edit.FieldType.text)
bd_item_edit.EditBDItemRegisterHandlers(dp, edit_project_desc_button_name, project_select_to_edit_message, ShowMessageTemplate(project_edit_desc_message), ShowMessageTemplate(project_success_edit_message), table_name, key_name, desc_field, GetButtonNameAndKeyValueAndAccess, GetAccess, GetEditProjectKeyboardButtons, access_mode = user_access.AccessMode.EDIT, field_type = bd_item_edit.FieldType.text)
'''
dp.register_message_handler(ProjectSelectForEdit, text = edit_project_button_name)
dp.register_callback_query_handler(ProjectEdit, lambda x: x.data.startswith(select_to_edit_project_callback_prefix))
dp.register_message_handler(ProjectEditPhotoSkip, text = projects_skip_button_name, state = FSMEditProject.prjPhoto)
@ -434,5 +424,4 @@ def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(ProjectEditCancel, text = projects_canсel_button_name, state = FSMEditProject.prjDesc)
dp.register_message_handler(ProjectEditPhotoLoad, content_types = ['photo'], state = FSMEditProject.prjPhoto)
dp.register_message_handler(ProjectEditNameLoad, state = FSMEditProject.prjName)
dp.register_message_handler(ProjectEditDescLoad, state = FSMEditProject.prjDesc)
# Удаление проекта
dp.register_message_handler(ProjectEditDescLoad, state = FSMEditProject.prjDesc)'''

2
bot_modules/start.py

@ -38,7 +38,7 @@ def GetStartKeyboardButtons(a_UserGroups):
# Обработка сообщений
# Первичное привестивие
async def StartMenu(a_Message):
async def StartMenu(a_Message, state = None):
user_id = str(a_Message.from_user.id)
user_name = str(a_Message.from_user.username)
profile.AddUser(user_id, user_name)

61
template/bd_item.py

@ -0,0 +1,61 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Работа с элементом в БД
from bot_sys import user_access, bot_bd
from bot_modules import groups
from aiogram import types
'''
class TableListParam():
def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc):
self.table_name = a_TableName
self.key_name = a_KeyName
self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc
'''
item_not_found = 'Элемент {item_id} не найден в таблице {a_TableName}'
def GetAllItemsTemplate(a_TableName):
def GetAllItems():
return bot_bd.SelectBDTemplate(a_TableName)()
return GetAllItems
def GetBDItemsTemplate(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 GetBDItem
def DeleteBDItemInTableTemplate(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 DeleteBDItem
def EditBDItemInTableTemplate(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 EditBDItemInTable
def CheckAccessBDItemTemplate(a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_AccessMode : user_access.AccessMode):
async def CheckAccessBDItem(a_CallbackQuery : types.CallbackQuery, a_ResultWorkFunc):
user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
item_id = a_KeyValue
item = GetBDItemsTemplate(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)
a_ResultWorkFunc = await a_WorkFunc(a_CallbackQuery, item[0])
if a_ResultWorkFunc is None or a_ResultWorkFunc.string_message is None:
print('a_ResultWorkFunc', a_ResultWorkFunc)
return a_ResultWorkFunc
if not a_ResultWorkFunc.item_access is None and not user_access.CheckAccessString(a_ResultWorkFunc.item_access, user_groups, a_AccessMode):
return simple_message.WorkFuncResult(access.access_denied_message)
return None
return CheckAccessBDItem

41
template/bd_item_delete.py

@ -5,47 +5,24 @@
from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups
from template import simple_message, bd_item_select
from template import simple_message, bd_item_select, bd_item
from aiogram import types
item_not_found = 'Элемент {item_id} не найден в таблице {a_TableName}'
'''
class TableListParam():
def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc):
self.table_name = a_TableName
self.key_name = a_KeyName
self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc
'''
def DeleteBDItemInTableTemplate(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 DeleteBDItem
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):
async def DeleteBDItem(a_CallbackQuery : types.CallbackQuery, state = None):
user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
item_id = str(a_CallbackQuery.data).replace(a_Prefix, '')
item = bd_item_select.GetBDItemsTemplate(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)
res_of_pre_del = None
check = await bd_item.CheckAccessBDItemTemplate(a_TableName, a_KeyName, item_id, a_PreDeleteWorkFunc, access_mode)(a_CallbackQuery, res_of_pre_del)
res_of_pre_del = await a_PreDeleteWorkFunc(a_CallbackQuery, item[0])
if not check is None:
return check
if not delete:
return res_of_pre_del
if res_of_pre_del is None or res_of_pre_del.string_message is None:
return res_of_pre_del
if not res_of_pre_del.item_access is None and not user_access.CheckAccessString(res_of_pre_del.item_access, user_groups, access_mode):
return simple_message.WorkFuncResult(access.access_denied_message)
result, error = DeleteBDItemInTableTemplate(a_TableName, a_KeyName)(item_id)
result, error = bd_item.DeleteBDItemInTableTemplate(a_TableName, a_KeyName)(item_id)
if not error is None:
msg = error
log.Error(error)
@ -55,9 +32,9 @@ def DeleteBDItemTemplate(a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDele
return simple_message.SimpleMessageTemplate(DeleteBDItem, a_ButtonFunc, a_AccessFunc, access_mode)
def DeleteBDItemRegisterHandlers(dp, a_RequestButtonName, a_TableName : str, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.DELETE):
def DeleteBDItemRegisterHandlers(dp, a_ButtonName, a_TableName : str, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.DELETE):
a_Prefix = f'delete_{a_TableName}_{a_KeyName}:'
sel_handler = bd_item_select.SelectDBItemTemplate(a_TableName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode)
dp.register_message_handler(sel_handler, text = a_RequestButtonName)
dp.register_message_handler(sel_handler, text = a_ButtonName)
dp.register_callback_query_handler(DeleteBDItemTemplate(a_TableName, a_KeyName, a_PreDeleteWorkFunc, a_PostDeleteWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), lambda x: x.data.startswith(a_Prefix))

94
template/bd_item_edit.py

@ -0,0 +1,94 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Редактирование элемента в БД
from enum import Enum
from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups
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
canсel_button_name = "🚫 Отменить"
cancel_message = '''
🚫 Редактирование отменено
'''
error_photo_type_message = '''
🚫 Фотографий не найдено
'''
class FieldType(Enum):
text = 0
photo = 1
def StartEditBDItemTemplate(a_FSM, a_MessageFunc, a_TableName, a_KeyName, a_FieldName, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT):
async def StartEditBDItem(a_CallbackQuery : types.CallbackQuery, state : FSMContext):
user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
await a_FSM.item_id.set()
item_id = str(a_CallbackQuery.data).replace(a_Prefix, '')
res_of_work_func = None
async with state.proxy() as item_data:
item_data['item_id'] = item_id
check_func = bd_item.CheckAccessBDItemTemplate(a_TableName, a_KeyName, item_id, a_MessageFunc, access_mode)
print('check_func', check_func)
print('res_of_work_func', res_of_work_func)
check = await check_func(a_CallbackQuery, res_of_work_func)
print('res_of_work_func', res_of_work_func)
print('check', check)
if not check is None:
return check
await a_FSM.next()
print('res_of_work_func', res_of_work_func)
return res_of_work_func
return simple_message.SimpleMessageTemplate(StartEditBDItem, a_ButtonFunc, a_AccessFunc, access_mode)
def FinishEditBDItemTemplate(a_FSM, a_TableName, a_KeyName, a_FieldName, a_MessageFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = FieldType.text):
async def FinishEditBDItem(a_CallbackQuery : types.CallbackQuery, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
error = None
res_of_work_func = None
async with state.proxy() as item_data:
if a_Message.text == canсel_button_name:
return simple_message.WorkFuncResult(cancel_message)
item_id = item_data['item_id']
check = await bd_item.CheckAccessBDItemTemplate(a_TableName, a_KeyName, item_id, a_MessageFunc, access_mode)(a_CallbackQuery, res_of_work_func)
if not check is None:
return check
field_value = ''
if field_type == FieldType.photo:
if a_Message.photo == None or len(a_Message.photo) == 0:
return simple_message.WorkFuncResult(error_photo_type_message)
field_value = a_Message.photo[0].file_id
else:
field_value = a_Message.text
res, error = bot_item.EditBDItemInTableTemplate(a_TableName, a_KeyName, a_FieldName)(item_id, field_value)
log.Success(f'Изменено поле в таблице {a_TableName} ключу {a_KeyName}={item_id}. Новое значение поля {a_FieldName}={field_value}. Пользователь {user_id}.')
await state.finish()
if error:
return simple_message.WorkFuncResult(error)
return res_of_work_func
return simple_message.SimpleMessageTemplate(FinishEditBDItem, a_ButtonFunc, a_AccessFunc, access_mode)
def EditBDItemRegisterHandlers(dp, a_ButtonName, a_StartMessage, a_EditMessageFunc, a_FinishMessageFunc, a_TableName : str, a_KeyName, a_FieldName, a_GetButtonNameAndKeyValueAndAccessFunc, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.EDIT, field_type = FieldType.text):
class FSMEditItem(StatesGroup):
item_id = State()
item_field = State()
a_Prefix = f'edit_{a_TableName}_{a_KeyName}_{a_FieldName}:'
sel_handler = bd_item_select.SelectDBItemTemplate(a_TableName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode)
dp.register_message_handler(sel_handler, text = a_ButtonName)
dp.register_callback_query_handler(StartEditBDItemTemplate(FSMEditItem, a_EditMessageFunc, a_TableName, a_KeyName, a_FieldName, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), lambda x: x.data.startswith(a_Prefix))
dp.register_message_handler(FinishEditBDItemTemplate(FSMEditItem, a_TableName, a_KeyName, a_FieldName, a_FinishMessageFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode, field_type = field_type), state = FSMEditItem.item_field)

14
template/bd_item_select.py

@ -5,23 +5,13 @@
from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups
from template import simple_message
from template import simple_message, bd_item
from aiogram import types
def GetAllItemsTemplate(a_TableName):
def GetAllItems():
return bot_bd.SelectBDTemplate(a_TableName)()
return GetAllItems
def GetBDItemsTemplate(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 GetBDItem
def GetBDItemsListKeyboardButtonsTemplate(a_TableName : str, a_Prefix : str, a_GetButtonNameAndKeyValueAndAccessFunc, access_mode = user_access.AccessMode.VIEW):
def GetBDItemsListKeyboardButtons(a_UserGroups):
items = GetAllItemsTemplate(a_TableName)()
items = bd_item.GetAllItemsTemplate(a_TableName)()
items_button_list = []
for t in items:
bname, key_value, access = a_GetButtonNameAndKeyValueAndAccessFunc(t)

12
template/bd_item_view.py

@ -9,21 +9,13 @@ from template import simple_message, bd_item_select, bd_item_delete
from aiogram import types
'''
class TableListParam():
def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc):
self.table_name = a_TableName
self.key_name = a_KeyName
self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc
'''
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 SelectAndShowBDItemRegisterHandlers(dp, a_RequestButtonName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW):
def SelectAndShowBDItemRegisterHandlers(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 = f'select_{a_TableName}_{a_KeyName}:'
sel_handler = bd_item_select.SelectDBItemTemplate(a_TableName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode)
dp.register_message_handler(sel_handler, text = a_RequestButtonName)
dp.register_message_handler(sel_handler, text = a_ButtonName)
dp.register_callback_query_handler(ShowBDItemTemplate(a_TableName, a_KeyName, a_ShowItemWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), lambda x: x.data.startswith(a_Prefix))
return sel_handler

7
template/simple_message.py

@ -17,19 +17,20 @@ class WorkFuncResult():
self.item_access = item_access
def InfoMessageTemplate(a_HelpMessage, a_GetButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW):
async def GetMessage(a_Message : types.message):
async def GetMessage(a_Message : types.message, state = None):
return WorkFuncResult(a_HelpMessage)
return SimpleMessageTemplate(GetMessage, a_GetButtonsFunc, a_AccessFunc, access_mode)
def SimpleMessageTemplate(a_WorkFunc, a_GetButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW):
async def SimpleMessage(a_Message : types.message):
async def SimpleMessage(a_Message : types.message, state = None):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, access_mode):
return await bot.send_message(a_Message.from_user.id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
res = await a_WorkFunc(a_Message)
print(a_WorkFunc)
res = await a_WorkFunc(a_Message, state = state)
if res is None:
return

Loading…
Cancel
Save