From 70cb71e0ead1e8c197b30f0351043ca079f9b519 Mon Sep 17 00:00:00 2001 From: Alexei Date: Sat, 20 May 2023 20:32:25 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A7=D0=B8=D1=81=D1=82=D0=BA=D0=B0=20=D0=BE?= =?UTF-8?q?=D1=82=20=D1=81=D1=82=D0=B0=D1=80=D0=BE=D0=B3=D0=BE=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_modules/access.py | 2 +- bot_modules/access_utils.py | 2 +- bot_modules/backup.py | 4 +- bot_modules/buttons.py | 2 +- bot_modules/comments.py | 2 +- bot_modules/languages.py | 4 +- bot_modules/messages.py | 2 +- bot_modules/mod_simple_message.py | 2 +- bot_modules/mod_table_operate.py | 8 ++-- bot_modules/needs.py | 2 +- bot_modules/projects.py | 2 +- bot_modules/tasks.py | 2 +- bot_sys/aiogram_bot.py | 24 +++++++++--- bot_sys/bot_bd.py | 25 +++--------- bot_sys/bot_messages.py | 4 +- bot_sys/keyboard.py | 11 ++---- bot_sys/log.py | 82 ++++++++++++++++++++------------------- bot_sys/user_access.py | 4 -- bot_sys/user_messages.py | 56 -------------------------- main.py | 10 +++-- template/bd_item.py | 10 ++--- template/bd_item_add.py | 6 +-- template/bd_item_edit.py | 2 +- template/bd_item_select.py | 2 +- template/file_message.py | 2 +- template/sql_request.py | 12 +++--- 26 files changed, 114 insertions(+), 170 deletions(-) delete mode 100644 bot_sys/user_messages.py diff --git a/bot_modules/access.py b/bot_modules/access.py index d1efee8..b5b2529 100644 --- a/bot_modules/access.py +++ b/bot_modules/access.py @@ -146,7 +146,7 @@ class ModuleAccess(mod_table_operate.TableOperateModule): keyboard.ButtonWithAccess(self.m_SqlRequestButtonName, user_access.AccessMode.EDIT, self.GetAccess()), keyboard.ButtonWithAccess(self.m_HelpButtonName , user_access.AccessMode.VIEW, self.GetAccess()) ] - return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups) + return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) def RegisterHandlers(self): super().RegisterHandlers() diff --git a/bot_modules/access_utils.py b/bot_modules/access_utils.py index 81da334..18c6e99 100644 --- a/bot_modules/access_utils.py +++ b/bot_modules/access_utils.py @@ -20,7 +20,7 @@ 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)() + return bot_bd.RequestSelectTemplate(a_Bot, table_name)() def GetAccessForModule(a_Bot, a_ModuleName): alist = GetModulesAccessList(a_Bot) diff --git a/bot_modules/backup.py b/bot_modules/backup.py index 291ca5b..bd4ca67 100644 --- a/bot_modules/backup.py +++ b/bot_modules/backup.py @@ -69,7 +69,7 @@ class ModuleBackup(mod_simple_message.SimpleMessageModule): ) self.m_BackupLogMessageHandler = file_message.BackupFileTemplate( self.m_Bot, - self.m_Bot.GetLog().g_log_file_name, + self.m_Bot.GetLog().GetFileName(), self.m_BackupLogMessage, self.m_GetAccessFunc, self.m_GetStartKeyboardButtonsFunc, @@ -87,7 +87,7 @@ class ModuleBackup(mod_simple_message.SimpleMessageModule): keyboard.ButtonWithAccess(self.m_BackupBDButtonName, user_access.AccessMode.EDIT, self.GetAccess()), keyboard.ButtonWithAccess(self.m_BackupLogButtonName , user_access.AccessMode.EDIT, self.GetAccess()) ] - return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups) + return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) def RegisterHandlers(self): super().RegisterHandlers() diff --git a/bot_modules/buttons.py b/bot_modules/buttons.py index 2cc3ef7..e2cef12 100644 --- a/bot_modules/buttons.py +++ b/bot_modules/buttons.py @@ -3,7 +3,7 @@ # Сообщения -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table, bot_messages +from bot_sys import bot_bd, keyboard, user_access, bd_table, bot_messages from bot_modules import mod_table_operate, mod_simple_message, access_utils from template import bd_item diff --git a/bot_modules/comments.py b/bot_modules/comments.py index e09a78b..8217dc8 100644 --- a/bot_modules/comments.py +++ b/bot_modules/comments.py @@ -3,7 +3,7 @@ # Комментарии -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_sys import bot_bd, keyboard, user_access, bd_table from bot_modules import mod_table_operate, mod_simple_message from aiogram.dispatcher import FSMContext diff --git a/bot_modules/languages.py b/bot_modules/languages.py index cfb0534..259bb59 100644 --- a/bot_modules/languages.py +++ b/bot_modules/languages.py @@ -3,7 +3,7 @@ # Языки -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_sys import bot_bd, keyboard, user_access, bd_table from bot_modules import mod_table_operate, mod_simple_message, access_utils from template import bd_item @@ -166,7 +166,7 @@ class ModuleLanguages(mod_table_operate.TableOperateModule): for lang_name, lang_id in self.m_LanguageIDs: if a_LangID == lang_id: return lang_name - return user_messages.default_language + return self.m_BotMessages.m_DefaultLanguage def FlushLanguages(self): msg = self.m_BotMessages.GetMessages() diff --git a/bot_modules/messages.py b/bot_modules/messages.py index a78141d..2585c8b 100644 --- a/bot_modules/messages.py +++ b/bot_modules/messages.py @@ -3,7 +3,7 @@ # Сообщения -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table, bot_messages +from bot_sys import bot_bd, keyboard, user_access, bd_table, bot_messages from bot_modules import mod_table_operate, mod_simple_message, access_utils from template import bd_item diff --git a/bot_modules/mod_simple_message.py b/bot_modules/mod_simple_message.py index 8ef5a65..19d5ff4 100644 --- a/bot_modules/mod_simple_message.py +++ b/bot_modules/mod_simple_message.py @@ -89,7 +89,7 @@ class SimpleMessageModule(mod_interface.IModule): def GetStartKeyboardButtons(self, a_Message, a_UserGroups): buttons = self.GetButtons(self.m_ChildModuleNameList) - return keyboard.MakeButtons(buttons, a_UserGroups) + return keyboard.MakeButtons(self.m_Bot, buttons, a_UserGroups) def GetInitBDCommands(self): return [ diff --git a/bot_modules/mod_table_operate.py b/bot_modules/mod_table_operate.py index 742c93c..0c62eaa 100644 --- a/bot_modules/mod_table_operate.py +++ b/bot_modules/mod_table_operate.py @@ -94,10 +94,10 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): keyboard.ButtonWithAccess(self.GetButton(ButtonNames.DEL), user_access.AccessMode.DELETE, self.GetAccess()), keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT), user_access.AccessMode.EDIT, self.GetAccess()), ] - return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups) + return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) def GetEditKeyboardButtons(self, a_Message, a_UserGroups): - mod_buttons = keyboard.MakeButtons(self.GetButtons(self.m_EditModuleNameList), a_UserGroups) + mod_buttons = keyboard.MakeButtons(self.m_Bot, self.GetButtons(self.m_EditModuleNameList), a_UserGroups) cur_buttons = [ keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT_PHOTO), user_access.AccessMode.VIEW, self.GetAccess()), keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT_NAME), user_access.AccessMode.ADD, self.GetAccess()), @@ -105,7 +105,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT_ACCESS), user_access.AccessMode.DELETE, self.GetAccess()), keyboard.ButtonWithAccess(self.GetButton(ButtonNames.EDIT_DEFAULT_ACCESS), user_access.AccessMode.EDIT, self.GetAccess()), ] - return mod_buttons + keyboard.MakeButtons(cur_buttons, a_UserGroups) + return mod_buttons + keyboard.MakeButtons(self.m_Bot, cur_buttons, a_UserGroups) def GetViewItemInlineKeyboardTemplate(self, a_ItemID): def GetViewItemInlineKeyboard(a_Message, a_UserGroups): @@ -122,7 +122,7 @@ class TableOperateModule(mod_simple_message.SimpleMessageModule): cur_buttons = [ keyboard.InlineButtonWithAccess(child_mod.GetButton(ButtonNames.LIST), child_mod.GetSelectPrefix(), a_ItemID, self.GetAccess(), user_access.AccessMode.VIEW), ] - return keyboard.MakeInlineKeyboardButtons(cur_buttons, a_UserGroups) + return keyboard.MakeInlineKeyboardButtons(self.m_Bot, cur_buttons, a_UserGroups) def GetButtonNameAndKeyValueAndAccess(self, a_Item): return \ diff --git a/bot_modules/needs.py b/bot_modules/needs.py index b58ca8d..15625a3 100644 --- a/bot_modules/needs.py +++ b/bot_modules/needs.py @@ -3,7 +3,7 @@ # Потребности -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_sys import bot_bd, keyboard, user_access, bd_table from bot_modules import mod_table_operate, mod_simple_message from aiogram.dispatcher import FSMContext diff --git a/bot_modules/projects.py b/bot_modules/projects.py index 08d181d..6b82cfa 100644 --- a/bot_modules/projects.py +++ b/bot_modules/projects.py @@ -3,7 +3,7 @@ # Проекты -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_sys import bot_bd, keyboard, user_access, bd_table from bot_modules import mod_table_operate, mod_simple_message from aiogram.dispatcher import FSMContext diff --git a/bot_modules/tasks.py b/bot_modules/tasks.py index 5632a18..b591ce3 100644 --- a/bot_modules/tasks.py +++ b/bot_modules/tasks.py @@ -3,7 +3,7 @@ # Задачи -from bot_sys import bot_bd, keyboard, user_access, user_messages, bd_table +from bot_sys import bot_bd, keyboard, user_access, bd_table from bot_modules import mod_table_operate, mod_simple_message from aiogram.dispatcher import FSMContext diff --git a/bot_sys/aiogram_bot.py b/bot_sys/aiogram_bot.py index 07985c5..6b4ccca 100644 --- a/bot_sys/aiogram_bot.py +++ b/bot_sys/aiogram_bot.py @@ -26,7 +26,7 @@ class AiogramBot(interfaces.IBot): return self.m_Log 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_Log, 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, parse_mode = None): if not parse_mode: @@ -40,22 +40,36 @@ class AiogramBot(interfaces.IBot): if inline_keyboards: base_keyboards = inline_keyboards if a_PhotoIDs and a_PhotoIDs != 0 and a_PhotoIDs != '0': - for k in base_keyboards: - await self.m_TBot.send_photo( + if base_keyboards: + for k in base_keyboards: + await self.m_TBot.send_photo( a_UserID, a_PhotoIDs, a_Message, reply_markup = k ) + else: + await self.m_TBot.send_photo( + a_UserID, + a_PhotoIDs, + a_Message + ) else: #print('SendMessage', a_UserID, a_Message, a_PhotoIDs, a_InlineKeyboardButtons, a_KeyboardButtons, base_keyboard) - for k in base_keyboards: - await self.m_TBot.send_message( + if base_keyboards: + for k in base_keyboards: + await self.m_TBot.send_message( a_UserID, a_Message, reply_markup = k, parse_mode = parse_mode ) + else: + await self.m_TBot.send_message( + a_UserID, + a_Message, + parse_mode = parse_mode + ) async def SendDocument(self, a_UserID, a_Document, a_Caption, a_KeyboardButtons, a_InlineKeyboardButtons): inline_keyboard = None diff --git a/bot_sys/bot_bd.py b/bot_sys/bot_bd.py index 4a1d73f..ec81174 100644 --- a/bot_sys/bot_bd.py +++ b/bot_sys/bot_bd.py @@ -6,16 +6,6 @@ from bot_sys import log # Работа с базой данных -# Имя файла БД -g_bd_file_name = 'bot.db' -def GetBDFileName(): - return g_bd_file_name - -# --------------------------------------------------------- -# Функции работы с базой - -# --------------------------------------------------------- - def GetBDDateTimeNow(): return 'datetime(\'now\')' @@ -24,16 +14,12 @@ def SelectBDTemplate(a_Bot, a_TableName): return a_Bot.SQLRequest(f'SELECT * FROM {a_TableName}') return SelectBD -def RequestsExecute(a_BDFileName, a_Commands): - for cmd in a_Commands: - SQLRequest(a_BDFileName, cmd, commit = True) - -def RequestSelectTemplate(a_BDFileName, a_TableName): +def RequestSelectTemplate(a_Bot, a_TableName): def SelectBD(): - return SQLRequest(a_BDFileName, f'SELECT * FROM {a_TableName}') + return a_Bot.SQLRequest(f'SELECT * FROM {a_TableName}') return SelectBD -def SQLRequest(a_BDFileName, a_Request : str, commit = False, return_error = False, param = None): +def SQLRequest(a_Log, a_BDFileName, a_Request : str, commit = False, return_error = False, param = None): db = sqlite3.connect(a_BDFileName) cursor = db.cursor() result = [] @@ -47,11 +33,12 @@ def SQLRequest(a_BDFileName, a_Request : str, commit = False, return_error = Fal if commit: db.commit() except sqlite3.Error as e: - log.Error(f'Ошибка при обработке запроса [{a_Request}]:{str(e)}') + a_Log.Error(f'Ошибка при обработке запроса [{a_Request}]:{str(e)}') error = "Ошибка sqlite3:" + str(e) cursor.close() db.close() - if not error and commit: log.Success(f'Выполнен запрос [{a_Request}]') + if not error and commit: + a_Log.Success(f'Выполнен запрос [{a_Request}]') if return_error: return result, error return result diff --git a/bot_sys/bot_messages.py b/bot_sys/bot_messages.py index dca7307..c032df4 100644 --- a/bot_sys/bot_messages.py +++ b/bot_sys/bot_messages.py @@ -61,7 +61,7 @@ def MakeBotMessage(a_MessageDesc): class BotMessages: def __init__(self, a_DefaultLanguage): - self.a_DefaultLanguage = a_DefaultLanguage + self.m_DefaultLanguage = a_DefaultLanguage self.m_Messages = {} self.m_LastUpdate = None @@ -73,7 +73,7 @@ class BotMessages: def CreateMessage(self, a_MessageName, a_MessageDesc, a_DateTime, a_MessagePhotoID = 0, a_MessageLang = None): if not a_MessageLang: - a_MessageLang = self.a_DefaultLanguage + a_MessageLang = self.m_DefaultLanguage cur_msg = BotMessage(self, a_MessageName, a_MessageDesc, a_MessageLang, a_MessagePhotoID, a_DateTime) msg = self.GetMessages() if not msg.get(a_MessageLang, None): diff --git a/bot_sys/keyboard.py b/bot_sys/keyboard.py index 2ba2190..c598ca5 100644 --- a/bot_sys/keyboard.py +++ b/bot_sys/keyboard.py @@ -34,13 +34,13 @@ def GetButtonInRowCount(a_AllKeyCount): return min(max(int(math.sqrt(a_AllKeyCount) // 1), 1), 3) # TODO перенести KeyboardButton в MakeAiogramKeyboard -def MakeButtons(a_ButtonList : [ButtonWithAccess], a_UserGroups): +def MakeButtons(a_Bot, a_ButtonList : [ButtonWithAccess], a_UserGroups): buttons = [] for b in a_ButtonList: if not b.label: continue label = str(b.label) - if user_access.CheckAccessString(b.access_string, a_UserGroups, b.access_mode): + if user_access.CheckAccess(a_Bot.GetRootIDs(), b.access_string, a_UserGroups, b.access_mode): buttons += [types.KeyboardButton(label)] step = GetButtonInRowCount(len(buttons)) return Chunks(buttons, step) @@ -65,19 +65,16 @@ class InlineButtonWithAccess: self.access_string = a_AccessString self.access_mode = a_AccessMode -def MakeInlineKeyboardButtons(a_ButtonList : [InlineButtonWithAccess], a_UserGroups): +def MakeInlineKeyboardButtons(a_Bot, a_ButtonList : [InlineButtonWithAccess], a_UserGroups): buttons = [] for b in a_ButtonList: - if user_access.CheckAccessString(b.access_string, a_UserGroups, b.access_mode): + if user_access.CheckAccess(a_Bot.GetRootIDs(), b.access_string, a_UserGroups, b.access_mode): data = f'{b.callback_prefix}{b.callback_data}' assert len(data) < 41 # Телеграм больше не поддерживает buttons += [InlineButton(b.label, data)] step = GetButtonInRowCount(len(buttons)) return Chunks(buttons, step) -def MakeInlineKeyboard(a_ButtonList : [InlineButtonWithAccess], a_UserGroups): - return MakeAiogramInlineKeyboard(MakeInlineKeyboardButtons(a_ButtonList, a_UserGroups)) - # ------------------------------- diff --git a/bot_sys/log.py b/bot_sys/log.py index cfb28e3..fd8adb6 100644 --- a/bot_sys/log.py +++ b/bot_sys/log.py @@ -10,48 +10,52 @@ # Error - Ошибка. # Success - Успех. -# Файл лога -g_log_file_name = 'log.txt' - from bot_sys import config import colorama import datetime colorama.init() -def GetTimeNow(): - return datetime.datetime.now() - -def GetTime(): - now = GetTimeNow() - time = now.strftime(f"[%d.%m.%Y, %H:%M]") - return time - -def Info(a_LogMessage): - time = GetTime() - WriteToFile(f'{time} | {a_LogMessage}') - print(f"{time} {colorama.Back.BLUE}{colorama.Style.BRIGHT} ИНФО {colorama.Style.RESET_ALL} | {a_LogMessage}") - -def Warn(a_LogMessage): - time = GetTime() - WriteToFile(f'{time} | {a_LogMessage}') - print(f"{time} {colorama.Back.YELLOW}{colorama.Style.BRIGHT} ВНИМАНИЕ {colorama.Style.RESET_ALL} | {a_LogMessage}") - -def Error(a_LogMessage): - time = GetTime() - WriteToFile(f'{time} | {a_LogMessage}') - print(f"{time} {colorama.Back.RED}{colorama.Style.BRIGHT} ОШИБКА {colorama.Style.RESET_ALL} | {a_LogMessage}") - -def Success(a_LogMessage): - time = GetTime() - WriteToFile(f'{time} | {a_LogMessage}') - print(f"{time} {colorama.Back.GREEN}{colorama.Style.BRIGHT} УСПЕХ {colorama.Style.RESET_ALL} | {a_LogMessage}") - -def WriteToFile(a_LogMessage): - if config.g_log_to_file != True: - return - - f = open(g_log_file_name, 'a+') - f.write(a_LogMessage) - f.write('\n') - f.close() +class Log: + def __init__(self, a_FileName): + self.m_FileName = a_FileName + + def GetFileName(self): + return self.m_FileName + + def GetTimeNow(self): + return datetime.datetime.now() + + def GetTime(self): + now = self.GetTimeNow() + time = now.strftime(f"[%d.%m.%Y, %H:%M]") + return time + + def Info(self, a_LogMessage): + time = self.GetTime() + self.WriteToFile(f'{time} | {a_LogMessage}') + print(f"{time} {colorama.Back.BLUE}{colorama.Style.BRIGHT} ИНФО {colorama.Style.RESET_ALL} | {a_LogMessage}") + + def Warn(self, a_LogMessage): + time = self.GetTime() + self.WriteToFile(f'{time} | {a_LogMessage}') + print(f"{time} {colorama.Back.YELLOW}{colorama.Style.BRIGHT} ВНИМАНИЕ {colorama.Style.RESET_ALL} | {a_LogMessage}") + + def Error(self, a_LogMessage): + time = self.GetTime() + self.WriteToFile(f'{time} | {a_LogMessage}') + print(f"{time} {colorama.Back.RED}{colorama.Style.BRIGHT} ОШИБКА {colorama.Style.RESET_ALL} | {a_LogMessage}") + + def Success(self, a_LogMessage): + time = self.GetTime() + self.WriteToFile(f'{time} | {a_LogMessage}') + print(f"{time} {colorama.Back.GREEN}{colorama.Style.BRIGHT} УСПЕХ {colorama.Style.RESET_ALL} | {a_LogMessage}") + + def WriteToFile(self, a_LogMessage): + if not self.m_FileName: + return + + f = open(self.m_FileName, 'a+') + f.write(a_LogMessage) + f.write('\n') + f.close() diff --git a/bot_sys/user_access.py b/bot_sys/user_access.py index c4fbd67..abe3127 100644 --- a/bot_sys/user_access.py +++ b/bot_sys/user_access.py @@ -54,10 +54,6 @@ def CheckAccessItem(a_AccessItem : str, a_AccessMode : AccessMode): return False # Возвращает возможность доступа пользователю a_UserGroups в элемент с правами a_AccessValue по режиму доступа a_AccessMode -def CheckAccessString(a_AccessValue : str, a_UserGroups : UserGroups, a_AccessMode : AccessMode): - return CheckAccess(config.GetRootIDs(), a_AccessValue, a_UserGroups, a_AccessMode) - -# Возвращает возможность доступа пользователю a_UserGroups в элемент с правами a_AccessValue по режиму доступа a_AccessMode def CheckAccess(a_RootIDs, a_AccessValue : str, a_UserGroups : UserGroups, a_AccessMode : AccessMode): if a_UserGroups.user_id in a_RootIDs: return True diff --git a/bot_sys/user_messages.py b/bot_sys/user_messages.py deleted file mode 100644 index 61e39b2..0000000 --- a/bot_sys/user_messages.py +++ /dev/null @@ -1,56 +0,0 @@ -#-*-coding utf-8-*- -# Общественное достояние, 2023, Алексей Безбородов (Alexei Bezborodov) - -import sqlite3 -from bot_sys import log - -# Работа ссообщениями - -default_language = 'ru' - -g_messages = None -def GetMessages(): - global g_messages - if not g_messages: - g_messages = {} - return g_messages - -g_last_update = None -def UpdateSignal(a_DateTime): - global g_last_update - g_last_update = a_DateTime -# --------------------------------------------------------- -# Функции работы с собщениями - -# --------------------------------------------------------- -class Message: - def __init__(self, a_MessageName : str, a_MessageDesc : str, a_Language : str, a_PhotoID : str, a_DateTime): - self.m_MessageName = a_MessageName - self.m_MessageDesc = a_MessageDesc - self.m_Language = a_Language - self.m_PhotoID = a_PhotoID - self.m_DateTime = a_DateTime - - def __str__(self): - global g_last_update - last_update = g_last_update - if self.m_DateTime < last_update: - msg = GetMessages() - if not msg.get(self.m_Language, None): - msg[self.m_Language] = {} - new_msg = msg[self.m_Language].get(self.m_MessageName, self) - self.m_MessageName = new_msg.m_MessageName - self.m_MessageDesc = new_msg.m_MessageDesc - self.m_PhotoID = new_msg.m_PhotoID - self.m_DateTime = last_update - return f'{self.m_MessageDesc}' - -def MSG(a_MessageName, a_MessageDesc, a_UpdateMSG, a_DateTime): - cur_msg = Message(a_MessageName, a_MessageDesc, default_language, 0, a_DateTime) - msg = GetMessages() - if not msg.get(default_language, None): - msg[default_language] = {} - if not msg[default_language].get(a_MessageName, None): - msg[default_language][a_MessageName] = cur_msg - a_UpdateMSG(cur_msg) - diff --git a/main.py b/main.py index d12de06..f48c1ad 100644 --- a/main.py +++ b/main.py @@ -5,11 +5,15 @@ log_start_message = 'Бот успешно запущен!' import os -from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages, bd_table +from bot_sys import config, log, aiogram_bot, bot_messages, bd_table, user_access from bot_modules import mod_agregator, start, profile, backup, groups, access, projects, tasks, needs, comments, languages, messages, buttons -g_Log = log -g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log) +bd_file_name = 'bot.db' + +log_file_name = 'log.txt' + +g_Log = log.Log(log_file_name) +g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bd_file_name, config.GetRootIDs(), g_Log) default_language = 'ru' diff --git a/template/bd_item.py b/template/bd_item.py index 31f3316..b0cadc6 100644 --- a/template/bd_item.py +++ b/template/bd_item.py @@ -42,21 +42,21 @@ def GetKeyDataFromCallbackMessage(a_Message, a_Prefix): key_item_id = str(a_Message.data).replace(a_Prefix, '') return key_item_id -def GetCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): +def GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, a_AccessMode): def GetCancelKeyboardButtons(a_Message, a_UserGroups): cur_buttons = [ keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()), ] - return keyboard.MakeButtons(cur_buttons, a_UserGroups) + return keyboard.MakeButtons(a_Bot, cur_buttons, a_UserGroups) return GetCancelKeyboardButtons -def GetSkipAndCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): +def GetSkipAndCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, a_AccessMode): def GetSkipAndCancelKeyboardButtons(a_Message, a_UserGroups): cur_buttons = [ keyboard.ButtonWithAccess(skip_button_name, a_AccessMode, a_AccessFunc()), keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()), ] - return keyboard.MakeButtons(cur_buttons, a_UserGroups) + return keyboard.MakeButtons(a_Bot, cur_buttons, a_UserGroups) return GetSkipAndCancelKeyboardButtons def GetAllItemsTemplate(a_Bot, a_TableName): @@ -94,7 +94,7 @@ def CheckAccessBDItemTemplate(a_Bot, a_TableName, a_KeyName, a_KeyValue, a_WorkF if result_work_func is None or result_work_func.m_BotMessage 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): + if not result_work_func.item_access is None and not user_access.CheckAccess(a_Bot.GetRootIDs(), result_work_func.item_access, user_groups, a_AccessMode): return simple_message.WorkFuncResult(bot_messages.MakeBotMessage(access_utils.access_denied_message)), None return None, result_work_func diff --git a/template/bd_item_add.py b/template/bd_item_add.py index 7fa2d68..2bcb39d 100644 --- a/template/bd_item_add.py +++ b/template/bd_item_add.py @@ -93,8 +93,8 @@ def FinishOrNextAddBDItemTemplate(a_Bot, a_FSM, a_AddBDItemFunc, a_ParentTableNa return simple_message.SimpleMessageTemplate(a_Bot, FinishAddBDItem, a_ButtonFunc, None, a_AccessFunc, access_mode) 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) + keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, access_mode) + keyboard_skip_and_cancel = bd_item.GetSkipAndCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, access_mode) reg_func = a_Bot.RegisterMessageHandler if a_ParentTableName: reg_func = a_Bot.RegisterCallbackHandler @@ -106,7 +106,7 @@ def AddBDItem3RegisterHandlers(a_Bot, a_StartCheckFunc, a_FSM, a_FSMName, a_FSMD 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(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) + keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, access_mode) reg_func = a_Bot.RegisterMessageHandler if a_ParentTableName: reg_func = a_Bot.RegisterCallbackHandler diff --git a/template/bd_item_edit.py b/template/bd_item_edit.py index 5c21dc9..a665349 100644 --- a/template/bd_item_edit.py +++ b/template/bd_item_edit.py @@ -38,7 +38,7 @@ def EditBDItemRegisterHandlers(a_Bot, a_PrevPrefix, a_FSM, a_StartCheckFunc, a_S if a_ParentIDFieldName: reg_func = a_Bot.RegisterCallbackHandler - keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_AccessFunc, access_mode) + keyboard_cancel = bd_item.GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, access_mode) a_Prefix = bd_item.HashPrefix(f'edit_{a_TableName}_{a_KeyName}_{a_FieldName}:') 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) diff --git a/template/bd_item_select.py b/template/bd_item_select.py index 8514c9e..2e199bd 100644 --- a/template/bd_item_select.py +++ b/template/bd_item_select.py @@ -24,7 +24,7 @@ def GetBDItemsListKeyboardButtonsTemplate(a_Bot, a_TableName : str, a_ParentIDFi if bname: b = keyboard.InlineButtonWithAccess(bname, a_NextPrefix, key_value, access, access_mode) items_button_list += [b] - return keyboard.MakeInlineKeyboardButtons(items_button_list, a_UserGroups) + return keyboard.MakeInlineKeyboardButtons(a_Bot, items_button_list, a_UserGroups) return GetBDItemsListKeyboardButtons 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): diff --git a/template/file_message.py b/template/file_message.py index 2869bda..fe7e6a7 100644 --- a/template/file_message.py +++ b/template/file_message.py @@ -11,7 +11,7 @@ def BackupFileTemplate(a_Bot, a_Path, a_CaptionMessage, a_AccessFunc, a_GetButto async def BackupFile(a_Message): user_id = str(a_Message.from_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.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, access_mode): return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) document = await GetFile(a_Bot, a_Path) diff --git a/template/sql_request.py b/template/sql_request.py index f50696b..262d781 100644 --- a/template/sql_request.py +++ b/template/sql_request.py @@ -13,34 +13,32 @@ cancel_message = ''' 🚫 Запрос к БД отменён ''' -def GetCancelKeyboardButtonsTemplate(a_AccessFunc, a_AccessMode): +def GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, a_AccessMode): def GetCancelKeyboardButtons(a_Message, a_UserGroups): print ('canсel_button_name', canсel_button_name) cur_buttons = [ keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc()) ] - return keyboard.MakeButtons(cur_buttons, a_UserGroups) + return keyboard.MakeButtons(a_Bot, cur_buttons, a_UserGroups) return GetCancelKeyboardButtons -# TODO CheckAccessString -> CheckAccess - def RequestToBDTemplate(a_Bot, a_StartMessage, a_GetButtonsFunc, a_AccessFunc, a_FSM, a_AccessMode): async def RequestToBDStart(a_Message): user_id = str(a_Message.from_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.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, a_AccessMode): return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) await a_FSM.sqlRequest.set() 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') + await simple_message.SendMessage(a_Bot, a_StartMessage, GetCancelKeyboardButtonsTemplate(a_Bot, a_AccessFunc, a_AccessMode), None, user_id, a_Message, user_groups, parse_mode='Markdown') return RequestToBDStart def RequestToBDFinishTemplate(a_Bot, a_GetButtonsFunc, a_AccessFunc, a_AccessMode): async def RequestToBDFinish(a_Message, state): user_id = str(a_Message.from_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.CheckAccess(a_Bot.GetRootIDs(), a_AccessFunc(), user_groups, a_AccessMode): return await simple_message.AccessDeniedMessage(a_Bot, a_GetButtonsFunc, user_id, a_Message, user_groups) result = ''