Browse Source

Новые правила с доступами.

Новый шаблон выделения элемента.
Мелкие правки
test_bot
Alexei 2 years ago
parent
commit
d1c5982fad
  1. 10
      bot_modules/access.py
  2. 2
      bot_modules/backup.py
  3. 6
      bot_modules/groups.py
  4. 7
      bot_modules/profile.py
  5. 9
      bot_modules/projects.py
  6. 4
      bot_modules/start.py
  7. 92
      bot_sys/user_access.py
  8. 38
      template/bd_item_select.py
  9. 31
      template/bd_item_view.py
  10. 20
      template/simple_message.py
  11. 19
      template/sql_request.py

10
bot_modules/access.py

@ -22,9 +22,10 @@ module_name = 'access'
init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_name}( init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_name}(
modName TEXT, modName TEXT,
modAccess TEXT, modAccess TEXT,
itemDefaultAccess TEXT,
UNIQUE(modName) UNIQUE(modName)
);""", );""",
f"INSERT OR IGNORE INTO {table_name} (modName, modAccess) VALUES ('{module_name}', 'other=-');" f"INSERT OR IGNORE INTO {table_name} (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=-', '{user_access.user_access_group_all}=-');"
] ]
# --------------------------------------------------------- # ---------------------------------------------------------
@ -90,6 +91,13 @@ def GetAccessForModule(a_ModuleName):
return i[1] return i[1]
return '' return ''
def GetItemDefaultAccessForModule(a_ModuleName):
alist = GetModuleAccessList()
for i in alist:
if i[0] == a_ModuleName:
return i[2]
return ''
# Инициализация БД # Инициализация БД
def GetInitBDCommands(): def GetInitBDCommands():
return init_bd_cmds return init_bd_cmds

2
bot_modules/backup.py

@ -20,7 +20,7 @@ bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML
module_name = 'backup' module_name = 'backup'
init_bd_cmds = [ init_bd_cmds = [
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=-');" f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=-', '{user_access.user_access_group_all}=-');"
] ]
# --------------------------------------------------------- # ---------------------------------------------------------

6
bot_modules/groups.py

@ -28,7 +28,7 @@ init_bd_cmds = ["""CREATE TABLE IF NOT EXISTS user_groups(
group_id INTEGER, group_id INTEGER,
UNIQUE(user_id, group_id) UNIQUE(user_id, group_id)
);""", );""",
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=-');" f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=-', '{user_access.user_access_group_all}=-');"
] ]
# --------------------------------------------------------- # ---------------------------------------------------------
@ -58,10 +58,6 @@ help_message = '''
`user_in_groups(user_id, group_id)` - содержит соответсвия ID пользователей и групп `user_in_groups(user_id, group_id)` - содержит соответсвия ID пользователей и групп
''' '''
request_cancel_message = '''
Запрос к БД отменён
'''
user_group_button_name = "▦ Группы пользователей" user_group_button_name = "▦ Группы пользователей"
sql_request_button_name = "⛃ Запрос к БД для редактирования групп" sql_request_button_name = "⛃ Запрос к БД для редактирования групп"
help_button_name = "📄 Информация по группам" help_button_name = "📄 Информация по группам"

7
bot_modules/profile.py

@ -17,9 +17,10 @@ module_name = 'profile'
init_bd_cmds = ["""CREATE TABLE IF NOT EXISTS users( init_bd_cmds = ["""CREATE TABLE IF NOT EXISTS users(
user_id INTEGER, user_id INTEGER,
userName TEXT, userName TEXT,
userAccess TEXT,
UNIQUE(user_id) UNIQUE(user_id)
);""", );""",
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=+');" f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=+', '{user_access.user_access_group_all}=+');"
] ]
# --------------------------------------------------------- # ---------------------------------------------------------
@ -49,14 +50,14 @@ async def ProfileOpen(a_Message):
msg = profile_message msg = profile_message
if not user_info is None: if not user_info is None:
msg = msg.replace('@user_id', str(user_info[0])).replace('@user_name', str(user_info[1])) msg = msg.replace('@user_id', str(user_info[0])).replace('@user_name', str(user_info[1]))
return msg, None return simple_message.WorkFuncResult(msg, item_access = user_info[2])
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с базой данных пользователей # Работа с базой данных пользователей
# Добавление пользователя, если он уже есть, то игнорируем # Добавление пользователя, если он уже есть, то игнорируем
def AddUser(a_UserID, a_UserName): def AddUser(a_UserID, a_UserName):
bot_bd.SQLRequestToBD("INSERT OR IGNORE INTO users (user_id, userName) VALUES (?, ?);", commit=True, param = (a_UserID, a_UserName)) bot_bd.SQLRequestToBD("INSERT OR IGNORE INTO users (user_id, userName, userAccess) VALUES (?, ?, ?);", commit=True, param = (a_UserID, a_UserName, access.GetItemDefaultAccessForModule(module_name)))
def GetUserInfo(a_UserID): def GetUserInfo(a_UserID):
user_info = bot_bd.SQLRequestToBD('SELECT * FROM users WHERE user_id = ?', param = [a_UserID]) user_info = bot_bd.SQLRequestToBD('SELECT * FROM users WHERE user_id = ?', param = [a_UserID])

9
bot_modules/projects.py

@ -41,7 +41,7 @@ init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}(
projectAccess TEXT, projectAccess TEXT,
{key_name} INTEGER PRIMARY KEY {key_name} INTEGER PRIMARY KEY
)''', )''',
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=va');" 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');"
] ]
@ -190,13 +190,14 @@ def GetButtonNameAndKeyValueAndAccess(a_Item):
async def ShowProject(a_CallbackQuery : types.CallbackQuery, a_Item): async def ShowProject(a_CallbackQuery : types.CallbackQuery, a_Item):
if (len(a_Item) < 3): if (len(a_Item) < 3):
return error_find_proj_message, None return simple_message.WorkFuncResult(error_find_proj_message)
photo_id = a_Item[0] photo_id = a_Item[0]
name = a_Item[1] name = a_Item[1]
desc = a_Item[2] desc = a_Item[2]
access = a_Item[3]
msg = project_open_message.replace('@proj_name', name).replace('@proj_desk', desc) msg = project_open_message.replace('@proj_name', name).replace('@proj_desk', desc)
return msg, photo_id return simple_message.WorkFuncResult(msg, photo_id = photo_id, item_access = access)
select_handler = 0 select_handler = 0
# стартовое сообщение # стартовое сообщение
@ -372,7 +373,7 @@ def GetProject(a_ProjectID):
def AddProject(a_prjPhoto, a_prjName, a_prjDesc): def AddProject(a_prjPhoto, a_prjName, a_prjDesc):
db = sqlite3.connect(bot_bd.GetBDFileName()) db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor() cursor = db.cursor()
cursor.execute('INSERT INTO projects(projectPhoto, projectName, projectDesc) VALUES(?, ?, ?)', (a_prjPhoto, a_prjName, a_prjDesc)) cursor.execute('INSERT INTO projects(projectPhoto, projectName, projectDesc, projectAccess) VALUES(?, ?, ?, ?)', (a_prjPhoto, a_prjName, a_prjDesc, access.GetItemDefaultAccessForModule(module_name)))
db.commit() db.commit()
cursor.close() cursor.close()
db.close() db.close()

4
bot_modules/start.py

@ -14,7 +14,7 @@ from aiogram.dispatcher import Dispatcher
module_name = 'start' module_name = 'start'
init_bd_cmds = [ init_bd_cmds = [
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=+');" f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_all}=+', '{user_access.user_access_group_all}=+');"
] ]
# --------------------------------------------------------- # ---------------------------------------------------------
@ -43,7 +43,7 @@ async def StartMenu(a_Message):
user_name = str(a_Message.from_user.username) user_name = str(a_Message.from_user.username)
profile.AddUser(user_id, user_name) profile.AddUser(user_id, user_name)
log.Info(f'Пользователь {user_id} {user_name} авторизовался в боте') log.Info(f'Пользователь {user_id} {user_name} авторизовался в боте')
return start_message, None return simple_message.WorkFuncResult(start_message)
# --------------------------------------------------------- # ---------------------------------------------------------
# API # API

92
bot_sys/user_access.py

@ -6,7 +6,10 @@
from enum import Enum from enum import Enum
from bot_sys import config from bot_sys import config
user_access_readme = ''' user_access_group_all = 'all'
user_access_group_new = 'new'
user_access_readme = f'''
Доступ к пользователям задаётся в виде строки Доступ к пользователям задаётся в виде строки
`user1=daver;user2=av;Group1=v;Group2=-;Group3=+;other=-` `user1=daver;user2=av;Group1=v;Group2=-;Group3=+;other=-`
Где через ';' располагаются различные варианты доступа Где через ';' располагаются различные варианты доступа
@ -21,7 +24,8 @@ DELETE = 'd' - удаление
ACCEES_EDIT = 'r' - изменение прав доступа ACCEES_EDIT = 'r' - изменение прав доступа
'+' - всё включено '+' - всё включено
'-' - всё выключено '-' - всё выключено
группа 'other' - остальные группа '{user_access_group_new}' - новые участники (все новые участники автоматически добавляются в эту группу)
группа '{user_access_group_all}' - все
''' '''
# --------------------------------------------------------- # ---------------------------------------------------------
@ -59,7 +63,7 @@ def CheckAccessString(a_AccessValue : str, a_UserGroups : UserGroups, a_AccessMo
continue continue
name = d[0] name = d[0]
access = d[1] access = d[1]
if name == a_UserGroups.user_id or name in a_UserGroups.group_names_list or name == 'other': if name == a_UserGroups.user_id or name in a_UserGroups.group_names_list or name == user_access_group_all:
if CheckAccessItem(access, a_AccessMode): if CheckAccessItem(access, a_AccessMode):
return True return True
return False return False
@ -122,45 +126,45 @@ def Test():
assert not CheckAccessString('123=-;gr1=ea', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT) assert not CheckAccessString('123=-;gr1=ea', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT)
assert not CheckAccessString('123=-;gr1=ad', UserGroups('1234', ['gr']), AccessMode.VIEW) assert not CheckAccessString('123=-;gr1=ad', UserGroups('1234', ['gr']), AccessMode.VIEW)
assert CheckAccessString('123=-;other=a', UserGroups('1234', []), AccessMode.ADD) assert CheckAccessString(f'123=-;{user_access_group_all}=a', UserGroups('1234', []), AccessMode.ADD)
assert CheckAccessString('123=-;other=d', UserGroups('1234', []), AccessMode.DELETE) assert CheckAccessString(f'123=-;{user_access_group_all}=d', UserGroups('1234', []), AccessMode.DELETE)
assert CheckAccessString('123=-;other=e', UserGroups('1234', []), AccessMode.EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=e', UserGroups('1234', []), AccessMode.EDIT)
assert CheckAccessString('123=-;other=r', UserGroups('1234', []), AccessMode.ACCEES_EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=r', UserGroups('1234', []), AccessMode.ACCEES_EDIT)
assert CheckAccessString('123=-;other=v', UserGroups('1234', []), AccessMode.VIEW) assert CheckAccessString(f'123=-;{user_access_group_all}=v', UserGroups('1234', []), AccessMode.VIEW)
assert CheckAccessString('123=-;other=a', UserGroups('1234', ['gr1']), AccessMode.ADD) assert CheckAccessString(f'123=-;{user_access_group_all}=a', UserGroups('1234', ['gr1']), AccessMode.ADD)
assert CheckAccessString('123=-;other=d', UserGroups('1234', ['gr1']), AccessMode.DELETE) assert CheckAccessString(f'123=-;{user_access_group_all}=d', UserGroups('1234', ['gr1']), AccessMode.DELETE)
assert CheckAccessString('123=-;other=e', UserGroups('1234', ['gr1']), AccessMode.EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=e', UserGroups('1234', ['gr1']), AccessMode.EDIT)
assert CheckAccessString('123=-;other=r', UserGroups('1234', ['gr1']), AccessMode.ACCEES_EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=r', UserGroups('1234', ['gr1']), AccessMode.ACCEES_EDIT)
assert CheckAccessString('123=-;other=v', UserGroups('1234', ['gr1']), AccessMode.VIEW) assert CheckAccessString(f'123=-;{user_access_group_all}=v', UserGroups('1234', ['gr1']), AccessMode.VIEW)
assert CheckAccessString('123=-;other=daver', UserGroups('1234', []), AccessMode.ADD) assert CheckAccessString(f'123=-;{user_access_group_all}=daver', UserGroups('1234', []), AccessMode.ADD)
assert CheckAccessString('123=-;other=dav', UserGroups('1234', []), AccessMode.DELETE) assert CheckAccessString(f'123=-;{user_access_group_all}=dav', UserGroups('1234', []), AccessMode.DELETE)
assert CheckAccessString('123=-;other=edv', UserGroups('1234', []), AccessMode.EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=edv', UserGroups('1234', []), AccessMode.EDIT)
assert CheckAccessString('123=-;other=rav', UserGroups('1234', []), AccessMode.ACCEES_EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=rav', UserGroups('1234', []), AccessMode.ACCEES_EDIT)
assert CheckAccessString('123=-;other=va', UserGroups('1234', []), AccessMode.VIEW) assert CheckAccessString(f'123=-;{user_access_group_all}=va', UserGroups('1234', []), AccessMode.VIEW)
assert CheckAccessString('123=-;other=avr', UserGroups('1234', ['gr1']), AccessMode.ADD) assert CheckAccessString(f'123=-;{user_access_group_all}=avr', UserGroups('1234', ['gr1']), AccessMode.ADD)
assert CheckAccessString('123=-;other=daver', UserGroups('1234', ['gr1']), AccessMode.DELETE) assert CheckAccessString(f'123=-;{user_access_group_all}=daver', UserGroups('1234', ['gr1']), AccessMode.DELETE)
assert CheckAccessString('123=-;other=eva', UserGroups('1234', ['gr1']), AccessMode.EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=eva', UserGroups('1234', ['gr1']), AccessMode.EDIT)
assert CheckAccessString('123=-;other=re', UserGroups('1234', ['gr1']), AccessMode.ACCEES_EDIT) assert CheckAccessString(f'123=-;{user_access_group_all}=re', UserGroups('1234', ['gr1']), AccessMode.ACCEES_EDIT)
assert CheckAccessString('123=-;other=vad', UserGroups('1234', ['gr1']), AccessMode.VIEW) assert CheckAccessString(f'123=-;{user_access_group_all}=vad', UserGroups('1234', ['gr1']), AccessMode.VIEW)
assert not CheckAccessString('123=-;other=d', UserGroups('1234', []), AccessMode.ADD) assert not CheckAccessString(f'123=-;{user_access_group_all}=d', UserGroups('1234', []), AccessMode.ADD)
assert not CheckAccessString('123=-;other=a', UserGroups('1234', []), AccessMode.DELETE) assert not CheckAccessString(f'123=-;{user_access_group_all}=a', UserGroups('1234', []), AccessMode.DELETE)
assert not CheckAccessString('123=-;other=r', UserGroups('1234', []), AccessMode.EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=r', UserGroups('1234', []), AccessMode.EDIT)
assert not CheckAccessString('123=-;other=v', UserGroups('1234', []), AccessMode.ACCEES_EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=v', UserGroups('1234', []), AccessMode.ACCEES_EDIT)
assert not CheckAccessString('123=-;other=e', UserGroups('1234', []), AccessMode.VIEW) assert not CheckAccessString(f'123=-;{user_access_group_all}=e', UserGroups('1234', []), AccessMode.VIEW)
assert not CheckAccessString('123=-;gr1=d;other=-', UserGroups('1234', ['gr']), AccessMode.ADD) assert not CheckAccessString(f'123=-;gr1=d;{user_access_group_all}=-', UserGroups('1234', ['gr']), AccessMode.ADD)
assert not CheckAccessString('123=-;gr1=a;other=-', UserGroups('1234', ['gr']), AccessMode.DELETE) assert not CheckAccessString(f'123=-;gr1=a;{user_access_group_all}=-', UserGroups('1234', ['gr']), AccessMode.DELETE)
assert not CheckAccessString('123=-;gr1=v;other=-', UserGroups('1234', ['gr']), AccessMode.EDIT) assert not CheckAccessString(f'123=-;gr1=v;{user_access_group_all}=-', UserGroups('1234', ['gr']), AccessMode.EDIT)
assert not CheckAccessString('123=-;gr1=e;other=-', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT) assert not CheckAccessString(f'123=-;gr1=e;{user_access_group_all}=-', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT)
assert not CheckAccessString('123=-;gr1=r;other=-', UserGroups('1234', ['gr']), AccessMode.VIEW) assert not CheckAccessString(f'123=-;gr1=r;{user_access_group_all}=-', UserGroups('1234', ['gr']), AccessMode.VIEW)
assert not CheckAccessString('123=-;other=dver', UserGroups('1234', []), AccessMode.ADD) assert not CheckAccessString(f'123=-;{user_access_group_all}=dver', UserGroups('1234', []), AccessMode.ADD)
assert not CheckAccessString('123=-;other=av', UserGroups('1234', []), AccessMode.DELETE) assert not CheckAccessString(f'123=-;{user_access_group_all}=av', UserGroups('1234', []), AccessMode.DELETE)
assert not CheckAccessString('123=-;other=dv', UserGroups('1234', []), AccessMode.EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=dv', UserGroups('1234', []), AccessMode.EDIT)
assert not CheckAccessString('123=-;other=av', UserGroups('1234', []), AccessMode.ACCEES_EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=av', UserGroups('1234', []), AccessMode.ACCEES_EDIT)
assert not CheckAccessString('123=-;other=a', UserGroups('1234', []), AccessMode.VIEW) assert not CheckAccessString(f'123=-;{user_access_group_all}=a', UserGroups('1234', []), AccessMode.VIEW)
assert not CheckAccessString('123=-;other=vr', UserGroups('1234', ['gr']), AccessMode.ADD) assert not CheckAccessString(f'123=-;{user_access_group_all}=vr', UserGroups('1234', ['gr']), AccessMode.ADD)
assert not CheckAccessString('123=-;other=aver', UserGroups('1234', ['gr']), AccessMode.DELETE) assert not CheckAccessString(f'123=-;{user_access_group_all}=aver', UserGroups('1234', ['gr']), AccessMode.DELETE)
assert not CheckAccessString('123=-;other=va', UserGroups('1234', ['gr']), AccessMode.EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=va', UserGroups('1234', ['gr']), AccessMode.EDIT)
assert not CheckAccessString('123=-;other=ea', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT) assert not CheckAccessString(f'123=-;{user_access_group_all}=ea', UserGroups('1234', ['gr']), AccessMode.ACCEES_EDIT)
assert not CheckAccessString('123=-;other=ad', UserGroups('1234', ['gr']), AccessMode.VIEW) assert not CheckAccessString(f'123=-;{user_access_group_all}=ad', UserGroups('1234', ['gr']), AccessMode.VIEW)

38
template/bd_item_select.py

@ -0,0 +1,38 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Просмотр элемента в БД
from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups
from template import simple_message
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_button_list = []
for t in items:
bname, key_value, access = a_GetButtonNameAndKeyValueAndAccessFunc(t)
if access is None:
access = ''
if not bname is None and user_access.CheckAccessString(access, a_UserGroups, access_mode):
items_button_list += [keyboard.Button(bname, key_value)]
return keyboard.MakeInlineKeyboard(items_button_list, a_Prefix)
return GetBDItemsListKeyboardButtons
def SelectDBItemTemplate(a_TableName : str, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode = user_access.AccessMode.VIEW):
keyborad_func = GetBDItemsListKeyboardButtonsTemplate(a_TableName, a_Prefix, a_GetButtonNameAndKeyValueAndAccessFunc)
return simple_message.InfoMessageTemplate(a_StartMessage, keyborad_func, a_AccessFunc, access_mode)

31
template/bd_item_view.py

@ -1,34 +1,14 @@
# -*- coding: utf8 -*- # -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru> # Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Простые информационные сообщения # Просмотр элемента в БД
from bot_sys import user_access, bot_bd, keyboard from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups from bot_modules import access, groups
from template import simple_message from template import simple_message, bd_item_select
from aiogram import types from aiogram import types
def GetAllItemsTemplate(a_TableName):
def GetAllItems():
return bot_bd.SelectBDTemplate(a_TableName)()
return GetAllItems
def GetBDItemTemplate(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_button_list = []
for t in items:
bname, key_value, access = a_GetButtonNameAndKeyValueAndAccessFunc(t)
if not bname is None and user_access.CheckAccessString(access, a_UserGroups, access_mode):
items_button_list += [keyboard.Button(bname, key_value)]
return keyboard.MakeInlineKeyboard(items_button_list, a_Prefix)
return GetBDItemsListKeyboardButtons
''' '''
class TableListParam(): class TableListParam():
def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc): def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc):
@ -36,16 +16,13 @@ class TableListParam():
self.key_name = a_KeyName self.key_name = a_KeyName
self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc
''' '''
def SelectDBItemTemplate(a_TableName : str, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode = user_access.AccessMode.VIEW):
keyborad_func = GetBDItemsListKeyboardButtonsTemplate(a_TableName, a_Prefix, a_GetButtonNameAndKeyValueAndAccessFunc)
return simple_message.InfoMessageTemplate(a_StartMessage, keyborad_func, a_AccessFunc, access_mode)
def ShowBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW): def ShowBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW):
async def ShowBDItem(a_CallbackQuery : types.CallbackQuery): async def ShowBDItem(a_CallbackQuery : types.CallbackQuery):
user_id = str(a_CallbackQuery.from_user.id) user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id) user_groups = groups.GetUserGroupData(user_id)
item_id = str(a_CallbackQuery.data).replace(a_Prefix, '') item_id = str(a_CallbackQuery.data).replace(a_Prefix, '')
item = GetBDItemTemplate(a_TableName, a_KeyName)(item_id) item = bd_item_select.GetBDItemsTemplate(a_TableName, a_KeyName)(item_id)
if len(item) < 1: if len(item) < 1:
msg = f'Элемент {item_id} не найден в таблице {a_TableName}' msg = f'Элемент {item_id} не найден в таблице {a_TableName}'
log.Error(msg) log.Error(msg)
@ -57,7 +34,7 @@ def ShowBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFun
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_RequestButtonName, 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}:' a_Prefix = f'select_{a_TableName}_{a_KeyName}:'
sel_handler = SelectDBItemTemplate(a_TableName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode) 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_RequestButtonName)
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)) 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))

20
template/simple_message.py

@ -10,9 +10,16 @@ from aiogram import types
from aiogram import Bot from aiogram import Bot
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode = types.ParseMode.HTML) bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode = types.ParseMode.HTML)
class WorkFuncResult():
def __init__(self, a_StringMessage : str, photo_id = None, item_access = None):
self.string_message = a_StringMessage
self.photo_id = photo_id
self.item_access = item_access
def InfoMessageTemplate(a_HelpMessage, a_GetButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): 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):
return a_HelpMessage, None print(a_HelpMessage)
return WorkFuncResult(a_HelpMessage)
return SimpleMessageTemplate(GetMessage, a_GetButtonsFunc, a_AccessFunc, access_mode) return SimpleMessageTemplate(GetMessage, a_GetButtonsFunc, a_AccessFunc, access_mode)
@ -23,10 +30,19 @@ def SimpleMessageTemplate(a_WorkFunc, a_GetButtonsFunc, a_AccessFunc, access_mod
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, access_mode): 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)) return await bot.send_message(a_Message.from_user.id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
msg, photo_id = await a_WorkFunc(a_Message) res = await a_WorkFunc(a_Message)
if res is None:
return
msg = res.string_message
if msg is None: if msg is None:
return return
photo_id = res.photo_id
if not res.item_access is None and not user_access.CheckAccessString(res.item_access, user_groups, access_mode):
return await bot.send_message(a_Message.from_user.id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
if photo_id is None or photo_id == 0 or photo_id == '0': if photo_id is None or photo_id == 0 or photo_id == '0':
return await bot.send_message(a_Message.from_user.id, msg, reply_markup = a_GetButtonsFunc(user_groups)) return await bot.send_message(a_Message.from_user.id, msg, reply_markup = a_GetButtonsFunc(user_groups))

19
template/sql_request.py

@ -11,22 +11,16 @@ from aiogram.dispatcher import FSMContext
canсel_button_name = "🚫 Отменить" canсel_button_name = "🚫 Отменить"
request_cancel_message = '''
🚫 Запрос к БД отменён
'''
def GetCancelKeyboardButtons(a_UserGroups, a_AccessFunc, a_AccessMode): def GetCancelKeyboardButtons(a_UserGroups, a_AccessFunc, a_AccessMode):
cur_buttons = [ cur_buttons = [
keyboard.ButtonWithAccess(canсel_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.MakeKeyboard(cur_buttons, a_UserGroups)
def RequestToBDCancelTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
async def RequestToBDCancel(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
await state.finish()
await a_Message.answer(request_cancel_message, reply_markup = a_GetButtonsFunc(user_groups))
return RequestToBDCancel
def RequestToBDTemplate(a_StartMessage, a_AccessFunc, a_FSM, a_AccessMode): def RequestToBDTemplate(a_StartMessage, a_AccessFunc, a_FSM, a_AccessMode):
async def RequestToBDStart(a_Message : types.message): async def RequestToBDStart(a_Message : types.message):
user_id = str(a_Message.from_user.id) user_id = str(a_Message.from_user.id)
@ -45,6 +39,10 @@ def RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups)) return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
result = '' result = ''
async with state.proxy() as prjData: async with state.proxy() as prjData:
if a_Message.text == canсel_button_name:
await state.finish()
return await a_Message.answer(request_cancel_message, reply_markup = a_GetButtonsFunc(user_groups))
sql_request = a_Message.text sql_request = a_Message.text
log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.') log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.')
result, error = bot_bd.SQLRequestToBD(sql_request, commit = True, return_error = True) result, error = bot_bd.SQLRequestToBD(sql_request, commit = True, return_error = True)
@ -59,5 +57,4 @@ def RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
def RequestToBDRegisterHandlers(dp, a_RequestButtonName, a_RequestStartMessage, a_FSM, a_GetButtonsFunc, a_AccessMode, a_AccessFunc): def RequestToBDRegisterHandlers(dp, a_RequestButtonName, a_RequestStartMessage, a_FSM, a_GetButtonsFunc, a_AccessMode, a_AccessFunc):
dp.register_message_handler(RequestToBDTemplate(a_RequestStartMessage, a_AccessFunc, a_FSM, a_AccessMode), text = a_RequestButtonName) dp.register_message_handler(RequestToBDTemplate(a_RequestStartMessage, a_AccessFunc, a_FSM, a_AccessMode), text = a_RequestButtonName)
dp.register_message_handler(RequestToBDCancelTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), text = canсel_button_name, state = a_FSM.sqlRequest)
dp.register_message_handler(RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), state = a_FSM.sqlRequest) dp.register_message_handler(RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), state = a_FSM.sqlRequest)

Loading…
Cancel
Save