Browse Source

Группы пользователей

pull/2/head
Alexei 2 years ago
parent
commit
b29224bba0
  1. 6
      bot_modules/access.py
  2. 37
      bot_modules/access_utils.py
  3. 156
      bot_modules/groups.py
  4. 16
      bot_modules/groups_utils.py
  5. 8
      bot_modules/mod_simple_message.py
  6. 8
      bot_sys/aiogram_bot.py
  7. 3
      bot_sys/bot_messages.py
  8. 2
      bot_sys/interfaces.py
  9. 6
      main.py
  10. 6
      template/bd_item.py
  11. 13
      template/file_message.py
  12. 18
      template/simple_message.py
  13. 62
      template/sql_request.py

6
bot_modules/access.py

@ -4,7 +4,7 @@
# Права пользователей # Права пользователей
from bot_sys import bot_bd, log, config, keyboard, user_access from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, groups from bot_modules import access_utils
from template import simple_message, sql_request, bd_item_edit, bd_item from template import simple_message, sql_request, bd_item_edit, bd_item
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
@ -68,10 +68,6 @@ help_message = '''
modAccess - строка modAccess - строка
''' + user_access.user_access_readme ''' + user_access.user_access_readme
access_denied_message = '''
Доступ запрещён!
'''
access_button_name = "⛀ Доступ пользователей" access_button_name = "⛀ Доступ пользователей"
sql_request_button_name = "⛁ Запрос к БД для редактирования доступа" sql_request_button_name = "⛁ Запрос к БД для редактирования доступа"
help_button_name = "📄 Информация по редактированию доступа" help_button_name = "📄 Информация по редактированию доступа"

37
bot_modules/access_utils.py

@ -0,0 +1,37 @@
# -*- coding: utf8 -*-
# Общественное достояние, 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Права пользователей
from bot_sys import bot_bd
# ---------------------------------------------------------
# БД
table_name = 'module_access'
mod_name_field = 'modName'
moduleaccess_field = 'modAccess'
mod_default_access_field = 'itemDefaultAccess'
access_denied_message = '''
Доступ запрещён!
'''
def GetAccessForModuleRequest(module_name, access, default_access):
return f"INSERT OR IGNORE INTO {table_name} ({mod_name_field}, {moduleaccess_field}, {mod_default_access_field}) VALUES ('{module_name}', '{access}', '{default_access}');"
def GetModulesAccessList(a_Bot):
return bot_bd.RequestSelectTemplate(a_Bot.m_BDFileName, table_name)()
def GetAccessForModule(a_Bot, a_ModuleName):
alist = GetModulesAccessList(a_Bot)
for i in alist:
if i[0] == a_ModuleName:
return i[1]
return ''
def GetItemDefaultAccessForModule(a_Bot, a_ModuleName):
alist = GetModulesAccessList(a_Bot)
for i in alist:
if i[0] == a_ModuleName:
return i[2]
return ''

156
bot_modules/groups.py

@ -3,13 +3,12 @@
# Группы пользователей # Группы пользователей
from bot_sys import bot_bd, log, config, keyboard, user_access from bot_sys import keyboard, user_access, bot_bd
from bot_modules import start, access from bot_modules import mod_simple_message
from template import simple_message, sql_request from template import simple_message, sql_request, bd_item
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import Dispatcher
class FSMRequestToBD(StatesGroup): class FSMRequestToBD(StatesGroup):
sqlRequest = State() sqlRequest = State()
@ -27,29 +26,10 @@ user_id_field = 'user_id'
access_field = 'access' access_field = 'access'
create_datetime_field = 'createDateTime' create_datetime_field = 'createDateTime'
init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_groups_name}(
{key_table_groups_name} INTEGER PRIMARY KEY NOT NULL,
{name_table_groups_field} TEXT,
{access_field} TEXT,
{create_datetime_field} TEXT,
UNIQUE({key_table_groups_name}),
UNIQUE({name_table_groups_field})
);""",
f"""CREATE TABLE IF NOT EXISTS {table_user_in_groups_name}(
{user_id_field} INTEGER,
{key_table_groups_name} INTEGER,
{access_field} TEXT,
{create_datetime_field} TEXT,
UNIQUE({user_id_field}, {key_table_groups_name})
);""",
f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_new}=-', '{user_access.user_access_group_new}=-');",
f"INSERT OR IGNORE INTO {table_groups_name} ({name_table_groups_field}, {access_field}, {create_datetime_field}) VALUES ('{user_access.user_access_group_new}', '{user_access.user_access_group_new}=-', {bot_bd.GetBDDateTimeNow()});"
]
# --------------------------------------------------------- # ---------------------------------------------------------
# Сообщения # Сообщения
group_start_message = ''' start_message = '''
<b>Группы пользователей находятся в стадии разработки</b> <b>Группы пользователей находятся в стадии разработки</b>
Пока можете воспользоваться хардкорным способом через запросы к БД Пока можете воспользоваться хардкорным способом через запросы к БД
@ -73,69 +53,73 @@ help_message = '''
`user_in_groups(user_id, group_id)` - содержит соответсвия ID пользователей и групп `user_in_groups(user_id, group_id)` - содержит соответсвия ID пользователей и групп
''' '''
user_group_button_name = "▦ Группы пользователей" start_menu_button_name = "▦ Группы пользователей"
sql_request_button_name = "⛃ Запрос к БД для редактирования групп" sql_request_button_name = "⛃ Запрос к БД для редактирования групп"
help_button_name = "📄 Информация по группам" help_button_name = "📄 Информация по группам"
# --------------------------------------------------------- init_access = '{user_access.user_access_group_new}=-'
# Работа с кнопками
''' class ModuleGroups(mod_simple_message.SimpleMessageModule):
def GetEditGroupKeyboardButtons(a_Message, a_UserGroups): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log):
cur_buttons = [ super().__init__(start_message, start_menu_button_name, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log)
keyboard.ButtonWithAccess(sql_request_button_name, user_access.AccessMode.EDIT, GetAccess()), self.m_SqlRequestButtonName = self.CreateButton('sql request', sql_request_button_name)
keyboard.ButtonWithAccess(help_button_name, user_access.AccessMode.VIEW, GetAccess()) self.m_RequestStartMessage = self.CreateMessage('equest start', request_start_message)
]
mods = [start] self.m_HelpButtonName = self.CreateButton('help', help_button_name)
return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups) self.m_HelpMessage = self.CreateMessage('help', help_message)
# --------------------------------------------------------- self.m_HelpMessageHandler = simple_message.InfoMessageTemplate(
# Обработка сообщений self.m_Bot,
self.m_HelpMessage,
# --------------------------------------------------------- self.m_GetStartKeyboardButtonsFunc,
# Работа с базой данных групп None,
self.m_GetAccessFunc
def GetGroupIDForUser(a_UserID): )
return bot_bd.SQLRequestToBD('SELECT group_id FROM user_in_groups WHERE user_id = ?', param = [a_UserID])
def GetInitBDCommands(self):
def GetGroupNamesForUser(a_UserID): return super(). GetInitBDCommands() + [
return bot_bd.SQLRequestToBD('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', param = [a_UserID]) f"""CREATE TABLE IF NOT EXISTS {table_groups_name}(
{key_table_groups_name} INTEGER PRIMARY KEY NOT NULL,
# --------------------------------------------------------- {name_table_groups_field} TEXT,
# API {access_field} TEXT,
{create_datetime_field} TEXT,
def GetUserGroupData(a_UserID): UNIQUE({key_table_groups_name}),
r = GetGroupNamesForUser(a_UserID) UNIQUE({name_table_groups_field})
groups = [] );""",
for i in r: f"""CREATE TABLE IF NOT EXISTS {table_user_in_groups_name}(
if len(i) > 0: {user_id_field} INTEGER,
groups += [i[0]] {key_table_groups_name} INTEGER,
return user_access.UserGroups(a_UserID, groups) {access_field} TEXT,
{create_datetime_field} TEXT,
# Инициализация БД UNIQUE({user_id_field}, {key_table_groups_name})
def GetInitBDCommands(): );""",
return init_bd_cmds f"INSERT OR IGNORE INTO {table_groups_name} ({name_table_groups_field}, {access_field}, {create_datetime_field}) VALUES ('{user_access.user_access_group_new}', '{user_access.user_access_group_new}=-', {bot_bd.GetBDDateTimeNow()});"
]
def GetAccess():
return access.GetAccessForModule(module_name) def GetName(self):
return module_name
# Доступные кнопки
def GetModuleButtons(): def GetStartKeyboardButtons(self, a_Message, a_UserGroups):
return [keyboard.ButtonWithAccess(user_group_button_name, user_access.AccessMode.VIEW, GetAccess())] mod_buttons = super().GetStartKeyboardButtons(a_Message, a_UserGroups)
cur_buttons = [
# Обработка кнопок keyboard.ButtonWithAccess(self.m_SqlRequestButtonName, user_access.AccessMode.EDIT, self.GetAccess()),
def RegisterHandlers(dp : Dispatcher): keyboard.ButtonWithAccess(self.m_HelpButtonName , user_access.AccessMode.VIEW, self.GetAccess())
dp.register_message_handler(simple_message.InfoMessageTemplateLegacy(group_start_message, GetEditGroupKeyboardButtons, GetAccess), text = user_group_button_name) ]
dp.register_message_handler(simple_message.InfoMessageTemplateLegacy(help_message, GetEditGroupKeyboardButtons, GetAccess), text = help_button_name) return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups)
sql_request.RequestToBDRegisterHandlers(dp, sql_request_button_name, request_start_message, FSMRequestToBD, GetEditGroupKeyboardButtons, user_access.AccessMode.EDIT, GetAccess) def RegisterHandlers(self):
''' super().RegisterHandlers()
sql_request.RequestToBDRegisterHandlers(
self.m_Bot,
self.m_SqlRequestButtonName,
self.m_RequestStartMessage,
FSMRequestToBD,
self.m_GetStartKeyboardButtonsFunc,
user_access.AccessMode.EDIT,
self.m_GetAccessFunc
)
self.m_Bot.RegisterMessageHandler(
self.m_HelpMessageHandler,
bd_item.GetCheckForTextFunc(self.m_HelpButtonName)
)
def GetUserGroupData(a_Bot, a_UserID):
def GetGroupNamesForUser(a_UserID):
return a_Bot.SQLRequest('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', param = [a_UserID])
r = GetGroupNamesForUser(a_UserID)
groups = []
for i in r:
if len(i) > 0:
groups += [i[0]]
return user_access.UserGroups(a_UserID, groups)

16
bot_modules/groups_utils.py

@ -0,0 +1,16 @@
# -*- coding: utf8 -*-
# Общественное достояние, 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Группы пользователей
from bot_sys import user_access
def GetUserGroupData(a_Bot, a_UserID):
def GetGroupNamesForUser(a_UserID):
return a_Bot.SQLRequest('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', param = [a_UserID])
r = GetGroupNamesForUser(a_UserID)
groups = []
for i in r:
if len(i) > 0:
groups += [i[0]]
return user_access.UserGroups(a_UserID, groups)

8
bot_modules/mod_simple_message.py

@ -3,8 +3,8 @@
# Простой модуль с одним сообщением # Простой модуль с одним сообщением
from bot_sys import keyboard, user_access, keyboard from bot_sys import keyboard, user_access
from bot_modules import access, mod_interface from bot_modules import access_utils, mod_interface
from template import simple_message, bd_item from template import simple_message, bd_item
class SimpleMessageModule(mod_interface.IModule): class SimpleMessageModule(mod_interface.IModule):
@ -67,11 +67,11 @@ class SimpleMessageModule(mod_interface.IModule):
def GetInitBDCommands(self): def GetInitBDCommands(self):
return [ return [
access.GetAccessForModuleRequest(self.GetName(), self.m_InitAccess, self.m_InitAccess), access_utils.GetAccessForModuleRequest(self.GetName(), self.m_InitAccess, self.m_InitAccess),
] ]
def GetAccess(self): def GetAccess(self):
return access.GetAccessForModule(self.m_Bot, self.GetName()) return access_utils.GetAccessForModule(self.m_Bot, self.GetName())
def GetModuleButtons(self): def GetModuleButtons(self):
return [ return [

8
bot_sys/aiogram_bot.py

@ -28,7 +28,9 @@ class AiogramBot(interfaces.IBot):
def SQLRequest(self, a_Request : str, commit = False, return_error = False, param = None): def SQLRequest(self, a_Request : str, commit = False, return_error = False, param = None):
return bot_bd.SQLRequest(self.m_BDFileName, a_Request, commit = commit, return_error = return_error, param = param) return bot_bd.SQLRequest(self.m_BDFileName, a_Request, commit = commit, return_error = return_error, param = param)
async def SendMessage(self, a_UserID, a_Message, a_PhotoIDs, a_KeyboardButtons, a_InlineKeyboardButtons): async def SendMessage(self, a_UserID, a_Message, a_PhotoIDs, a_KeyboardButtons, a_InlineKeyboardButtons, parse_mode = None):
if not parse_mode:
parse_mode = types.ParseMode.HTML
inline_keyboard = None inline_keyboard = None
if a_InlineKeyboardButtons: if a_InlineKeyboardButtons:
inline_keyboard = keyboard.MakeAiogramInlineKeyboard(a_InlineKeyboardButtons) inline_keyboard = keyboard.MakeAiogramInlineKeyboard(a_InlineKeyboardButtons)
@ -49,7 +51,8 @@ class AiogramBot(interfaces.IBot):
await self.m_TBot.send_message( await self.m_TBot.send_message(
a_UserID, a_UserID,
a_Message, a_Message,
reply_markup = base_keyboard reply_markup = base_keyboard,
parse_mode = parse_mode
) )
async def SendDocument(self, a_UserID, a_Document, a_Caption, a_KeyboardButtons, a_InlineKeyboardButtons): async def SendDocument(self, a_UserID, a_Document, a_Caption, a_KeyboardButtons, a_InlineKeyboardButtons):
@ -68,7 +71,6 @@ class AiogramBot(interfaces.IBot):
reply_markup = base_keyboard 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, commands=None, regexp=None, content_types=None, state=None):
if a_CheckFunc: if a_CheckFunc:
self.m_Dispatcher.register_message_handler(a_MessageHandler, a_CheckFunc, commands=commands, regexp=regexp, content_types=content_types, state=state) self.m_Dispatcher.register_message_handler(a_MessageHandler, a_CheckFunc, commands=commands, regexp=regexp, content_types=content_types, state=state)

3
bot_sys/bot_messages.py

@ -50,6 +50,9 @@ class BotMessage:
self.m_DateTime = new_msg.m_DateTime self.m_DateTime = new_msg.m_DateTime
return new_msg return new_msg
def MakeBotMessage(a_MessageDesc):
return BotMessage(None, '', a_MessageDesc, None, 0, None)
class BotMessages: class BotMessages:
def __init__(self, a_DefaultLanguage): def __init__(self, a_DefaultLanguage):
self.a_DefaultLanguage = a_DefaultLanguage self.a_DefaultLanguage = a_DefaultLanguage

2
bot_sys/interfaces.py

@ -17,7 +17,7 @@ class IBot(ABC):
pass pass
@abstractmethod @abstractmethod
async def SendMessage(self, a_UserID, a_Message, a_PhotoIDs, a_KeyboardButtons, a_InlineKeyboardButtons): async def SendMessage(self, a_UserID, a_Message, a_PhotoIDs, a_KeyboardButtons, a_InlineKeyboardButtons, parse_mode=None):
pass pass
@abstractmethod @abstractmethod

6
main.py

@ -6,7 +6,7 @@ log_start_message = 'Бот успешно запущен!'
import os import os
from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages
from bot_modules import mod_agregator, start, profile, backup #, projects, groups, access, , tasks, needs, comments, messages, , languages from bot_modules import mod_agregator, start, profile, backup, groups #, projects, , access, , tasks, needs, comments, messages, , languages
g_Log = log g_Log = log
g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log) g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log)
@ -26,9 +26,13 @@ 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([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log)
g_ModuleAgregator.AddModule(mod_backup) g_ModuleAgregator.AddModule(mod_backup)
mod_groups = groups.ModuleGroups([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log)
g_ModuleAgregator.AddModule(mod_groups)
start_mod_name_list = [#, 'projects', 'groups', 'access', , 'languages'] start_mod_name_list = [#, 'projects', 'groups', 'access', , 'languages']
mod_profile.GetName(), mod_profile.GetName(),
mod_backup.GetName(), mod_backup.GetName(),
mod_groups.GetName(),
] ]
mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log)
g_ModuleAgregator.AddModule(mod_start) g_ModuleAgregator.AddModule(mod_start)

6
template/bd_item.py

@ -5,7 +5,7 @@
from enum import Enum from enum import Enum
from bot_sys import user_access, bot_bd, keyboard, log from bot_sys import user_access, bot_bd, keyboard, log
from bot_modules import groups, access from bot_modules import groups_utils, access_utils
from template import simple_message from template import simple_message
from aiogram import types from aiogram import types
@ -82,7 +82,7 @@ def EditBDItemInTableTemplate(a_TableName : str, a_KeyName : str, a_FieldName :
def CheckAccessBDItemTemplate(a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_AccessMode : user_access.AccessMode): def CheckAccessBDItemTemplate(a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_AccessMode : user_access.AccessMode):
async def CheckAccessBDItem(a_CallbackQuery : types.CallbackQuery): async def CheckAccessBDItem(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_utils.GetUserGroupData(user_id)
item_id = a_KeyValue item_id = a_KeyValue
item = GetBDItemsTemplate(a_TableName, a_KeyName)(item_id) item = GetBDItemsTemplate(a_TableName, a_KeyName)(item_id)
if len(item) < 1: if len(item) < 1:
@ -95,7 +95,7 @@ def CheckAccessBDItemTemplate(a_TableName, a_KeyName, a_KeyValue, a_WorkFunc, a_
return result_work_func, result_work_func 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): 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.access_denied_message), None return simple_message.WorkFuncResult(access_utils.access_denied_message), None
return None, result_work_func return None, result_work_func
return CheckAccessBDItem return CheckAccessBDItem

13
template/file_message.py

@ -4,25 +4,20 @@
# Сообщения для работы с файлами # Сообщения для работы с файлами
from bot_sys import log, config, user_access from bot_sys import log, config, user_access
from bot_modules import access, groups from bot_modules import groups_utils
from template import simple_message from template import simple_message
def BackupFileTemplate(a_Bot, a_Path, a_CaptionMessage, a_AccessFunc, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_ErrorMessage, access_mode = user_access.AccessMode.EDIT): def BackupFileTemplate(a_Bot, a_Path, a_CaptionMessage, a_AccessFunc, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_ErrorMessage, access_mode = user_access.AccessMode.EDIT):
async def BackupFile(a_Message): async def BackupFile(a_Message):
user_id = str(a_Message.from_user.id) user_id = str(a_Message.from_user.id)
user_groups= groups.GetUserGroupData(a_Bot, user_id) user_groups= groups_utils.GetUserGroupData(a_Bot, user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, access_mode): if not user_access.CheckAccessString(a_AccessFunc(), user_groups, access_mode):
return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups)
document = await GetFile(a_Bot, a_Path) document = await GetFile(a_Bot, a_Path)
if document is None: if document is None:
return a_Bot.SendMessage( return simple_message.SendMessage(a_Bot, a_ErrorMessage, a_GetButtonsFunc, None, user_id, a_Message, user_groups)
user_id,
a_ErrorMessage,
None,
simple_message.ProxyGetButtonsTemplate(a_GetButtonsFunc)(a_Message, user_groups),
None
)
msg = a_CaptionMessage.GetDesc() msg = a_CaptionMessage.GetDesc()
msg = msg.replace('@time', a_Bot.GetLog().GetTime()) msg = msg.replace('@time', a_Bot.GetLog().GetTime())

18
template/simple_message.py

@ -4,7 +4,7 @@
# Простые информационные сообщения # Простые информационные сообщения
from bot_sys import user_access from bot_sys import user_access
from bot_modules import access, groups from bot_modules import access_utils, groups_utils
from aiogram import types from aiogram import types
def ProxyGetButtonsTemplate(a_GetButtonsFunc1): def ProxyGetButtonsTemplate(a_GetButtonsFunc1):
@ -15,15 +15,19 @@ def ProxyGetButtonsTemplate(a_GetButtonsFunc1):
else: else:
return ReturnNone return ReturnNone
async def AccessDeniedMessage(a_Bot, a_GetButtonsFunc, a_UserID, a_Message, user_groups): async def SendMessage(a_Bot, a_BotMessage, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_UserID, a_Message, user_groups, parse_mode=None):
return a_Bot.SendMessage( return await a_Bot.SendMessage(
a_UserID, a_UserID,
access.access_denied_message, a_BotMessage.GetDesc(),
None, a_BotMessage.GetPhotoID(),
ProxyGetButtonsTemplate(a_GetButtonsFunc)(a_Message, user_groups), ProxyGetButtonsTemplate(a_GetButtonsFunc)(a_Message, user_groups),
None ProxyGetButtonsTemplate(a_GetInlineButtonsFunc)(a_Message, user_groups),
parse_mode = parse_mode
) )
async def AccessDeniedMessage(a_Bot, a_GetButtonsFunc, a_UserID, a_Message, user_groups):
return await SendMessage(a_Bot, bot_messages.MakeBotMessage(access_utils.access_denied_message), a_GetButtonsFunc, None, a_UserID, a_Message, user_groups)
class WorkFuncResult(): class WorkFuncResult():
def __init__(self, a_BotMessage, item_access = None): def __init__(self, a_BotMessage, item_access = None):
self.m_BotMessage = a_BotMessage self.m_BotMessage = a_BotMessage
@ -39,7 +43,7 @@ def SimpleMessageTemplate(a_Bot, a_WorkFunc, a_GetButtonsFunc, a_GetInlineButton
async def SimpleMessage(a_Message : types.message, state = None): async def SimpleMessage(a_Message : types.message, state = None):
user_id = str(a_Message.from_user.id) user_id = str(a_Message.from_user.id)
lang = str(a_Message.from_user.language_code) lang = str(a_Message.from_user.language_code)
user_groups = groups.GetUserGroupData(a_Bot, user_id) user_groups = groups_utils.GetUserGroupData(a_Bot, user_id)
if not user_access.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, access_mode): if not user_access.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, access_mode):
return await AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) return await AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups)

62
template/sql_request.py

@ -3,11 +3,9 @@
# Сообщения для работы с sql запросами # Сообщения для работы с sql запросами
from bot_sys import bot_bd, log, config, user_access, keyboard from bot_sys import user_access, keyboard
from bot_modules import access, groups from bot_modules import groups_utils
from template import bd_item, simple_message
from aiogram import types
from aiogram.dispatcher import FSMContext
canсel_button_name = "🚫 Отменить" canсel_button_name = "🚫 Отменить"
@ -15,46 +13,54 @@ cancel_message = '''
🚫 Запрос к БД отменён 🚫 Запрос к БД отменён
''' '''
def GetCancelKeyboardButtons(a_Message, a_UserGroups, a_AccessFunc, a_AccessMode): def GetCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode):
cur_buttons = [ def GetCancelKeyboardButtons(a_Message, a_UserGroups):
keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()) print ('canсel_button_name', canсel_button_name)
] cur_buttons = [
return keyboard.MakeKeyboard(cur_buttons, a_UserGroups) keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc())
]
return keyboard.MakeButtons(cur_buttons, a_UserGroups)
# TODO CheckAccessString -> CheckAccess
def RequestToBDTemplate(a_StartMessage, a_AccessFunc, a_FSM, a_AccessMode): def RequestToBDTemplate(a_Bot, a_StartMessage, a_GetButtonsFunc, a_AccessFunc, a_FSM, a_AccessMode):
async def RequestToBDStart(a_Message : types.message): async def RequestToBDStart(a_Message):
user_id = str(a_Message.from_user.id) user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id) user_groups = groups_utils.GetUserGroupData(a_Bot, user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode): if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = GetCancelKeyboardButtons(a_Message, user_groups, a_AccessFunc, a_AccessMode)) return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups)
await a_FSM.sqlRequest.set() await a_FSM.sqlRequest.set()
await a_Message.answer(a_StartMessage, reply_markup = GetCancelKeyboardButtons(a_Message, user_groups, a_AccessFunc, a_AccessMode), parse_mode='Markdown') print ('a_FSM.sqlRequest.set()', a_StartMessage)
await simple_message.SendMessage(a_Bot, a_StartMessage, GetCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode), None, user_id, a_Message, user_groups, parse_mode='Markdown')
return RequestToBDStart return RequestToBDStart
def RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode): def RequestToBDFinishTemplate(a_Bot, a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
async def RequestToBDFinish(a_Message : types.message, state : FSMContext): async def RequestToBDFinish(a_Message, state):
user_id = str(a_Message.from_user.id) user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id) user_groups = groups.GetUserGroupData(a_Bot, user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode): if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(a_Message, user_groups)) return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups)
result = '' result = ''
async with state.proxy() as prjData: async with state.proxy() as prjData:
if a_Message.text == canсel_button_name: if a_Message.text == canсel_button_name:
await state.finish() await state.finish()
return await a_Message.answer(cancel_message, reply_markup = a_GetButtonsFunc(a_Message, user_groups)) return await simple_message.SendMessage(a_Bot, keyboard.MakeBotMessage(cancel_message), a_GetButtonsFunc, None, user_id, a_Message, user_groups)
sql_request = a_Message.text sql_request = a_Message.text
log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.') a_Bot.GetLog().Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.')
result, error = bot_bd.SQLRequestToBD(sql_request, commit = True, return_error = True) result, error = a_Bot.SQLReques(sql_request, commit = True, return_error = True)
if not error is None: if not error is None:
log.Error(f'Ошибка при выполнении запроса [{sql_request}] от пользователя {a_Message.from_user.id} ответ следующий [{str(error)}].') a_Bot.GetLog().Error(f'Ошибка при выполнении запроса [{sql_request}] от пользователя {a_Message.from_user.id} ответ следующий [{str(error)}].')
result = str(error) result = str(error)
else: else:
log.Success(f'Результат запроса [{sql_request}] от пользователя {a_Message.from_user.id} следующий [{result}].') a_Bot.GetLog().Success(f'Результат запроса [{sql_request}] от пользователя {a_Message.from_user.id} следующий [{result}].')
await state.finish() await state.finish()
await a_Message.answer(str(result), reply_markup = a_GetButtonsFunc(a_Message, user_groups)) await simple_message.SendMessage(a_Bot, keyboard.MakeBotMessage(str(result)), a_GetButtonsFunc, None, user_id, a_Message, user_groups)
return RequestToBDFinish return RequestToBDFinish
def RequestToBDRegisterHandlers(dp, a_RequestButtonName, a_RequestStartMessage, a_FSM, a_GetButtonsFunc, a_AccessMode, a_AccessFunc): def RequestToBDRegisterHandlers(a_Bot, 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) a_Bot.RegisterMessageHandler(RequestToBDTemplate(a_Bot, a_RequestStartMessage, a_GetButtonsFunc, a_AccessFunc, a_FSM, a_AccessMode), bd_item.GetCheckForTextFunc(a_RequestButtonName))
dp.register_message_handler(RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), state = a_FSM.sqlRequest) a_Bot.RegisterMessageHandler(RequestToBDFinishTemplate(a_Bot, a_GetButtonsFunc, a_AccessFunc, a_AccessMode), None, state = a_FSM.sqlRequest)

Loading…
Cancel
Save