From 283c074cbb39b651650248a8194cd6fefff1bd1a Mon Sep 17 00:00:00 2001 From: Alexei Date: Mon, 1 May 2023 13:58:39 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=20=D0=B8=20=D1=8F=D0=B7=D1=8B=D0=BA=D0=B8.=20?= =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D0=B0.=20?= =?UTF-8?q?=D0=9F=D0=BE=D0=BA=D0=B0=20=D0=BD=D0=B5=20=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=B0=D1=8E=D1=82.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_modules/languages.py | 31 +++++++++++++++++++++++++++++-- bot_modules/messages.py | 32 ++++++++++++++++++++++++++++++-- bot_modules/start.py | 10 ++++++++-- bot_sys/user_messages.py | 42 ++++++++++++++++++++++++++++++++++++++++++ main.py | 15 ++++++++++----- 5 files changed, 119 insertions(+), 11 deletions(-) create mode 100644 bot_sys/user_messages.py diff --git a/bot_modules/languages.py b/bot_modules/languages.py index 132318b..0f73e90 100644 --- a/bot_modules/languages.py +++ b/bot_modules/languages.py @@ -3,7 +3,7 @@ # Языки -from bot_sys import bot_bd, log, keyboard, user_access +from bot_sys import bot_bd, log, keyboard, user_access, user_messages from bot_modules import start, access, groups, messages from template import bd_item_view, simple_message, bd_item_delete, bd_item_edit, bd_item, bd_item_add @@ -48,7 +48,9 @@ init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}( {desc_field} TEXT, {photo_field} TEXT, {access_field} TEXT, - {create_datetime_field} TEXT + {create_datetime_field} TEXT, + UNIQUE({key_name}), + UNIQUE({name_field}) )''', f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_new}=va', '{user_access.user_access_group_new}=va');" ] @@ -230,6 +232,7 @@ async def LanguagePreDelete(a_CallbackQuery : types.CallbackQuery, a_Item): async def LanguagePostDelete(a_CallbackQuery : types.CallbackQuery, a_ItemID): log.Success(f'Язык №{a_ItemID} был удалён пользователем {a_CallbackQuery.from_user.id}.') #TODO: удалить вложенные + FlushLanguages() return simple_message.WorkFuncResult(language_success_delete_message) # --------------------------------------------------------- @@ -244,11 +247,35 @@ def AddBDItemFunc(a_ItemData, a_UserID): else: log.Success(f'Пользоватлель {a_UserID}. Добавлена запись в таблицу {table_name} ({a_ItemData[photo_field]}, {a_ItemData[name_field]}, {a_ItemData[desc_field]}, {access.GetItemDefaultAccessForModule(module_name)}).') + FlushLanguages() return res, error # --------------------------------------------------------- # API +def AddOrIgnoreLang(a_Lang : str): + res, error = bot_bd.SQLRequestToBD(f'INSERT OR IGNORE INTO {table_name}({photo_field}, {name_field}, {desc_field}, {access_field}, {create_datetime_field}) VALUES(?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()})', + commit = True, return_error = True, param = (0, a_Lang, '', access.GetItemDefaultAccessForModule(module_name))) + +g_languages = {} +def GetLangID(a_Lang): + return g_languages.get(a_Lang, None) + +def GetLangName(a_LangID): + for lang_name, lang_id in g_languages: + if a_LangID == lang_id: + return lang_name + return None + +def FlushLanguages(): + msg = user_messages.GetMessages() + for lang, msg_dict in msg.items(): + AddOrIgnoreLang(lang) + langs = bd_item.GetAllItemsTemplate(table_name)() + if langs: + for l in langs: + g_languages[l[1]] = str(l[0]) + # Инициализация БД def GetInitBDCommands(): return init_bd_cmds diff --git a/bot_modules/messages.py b/bot_modules/messages.py index d2d2642..d3580f0 100644 --- a/bot_modules/messages.py +++ b/bot_modules/messages.py @@ -3,7 +3,7 @@ # Сообщения -from bot_sys import bot_bd, log, keyboard, user_access +from bot_sys import bot_bd, log, keyboard, user_access, user_messages from bot_modules import start, access, groups, languages from template import bd_item_view, simple_message, bd_item_delete, bd_item_edit, bd_item, bd_item_add, bd_item_select @@ -54,7 +54,9 @@ init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}( {photo_field} TEXT, {access_field} TEXT, {create_datetime_field} TEXT, - {parent_id_field} INTEGER + {parent_id_field} INTEGER, + UNIQUE({key_name}), + UNIQUE({name_field}, {parent_id_field}) )''', f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VALUES ('{module_name}', '{user_access.user_access_group_new}=va', '{user_access.user_access_group_new}=va');" ] @@ -212,6 +214,8 @@ def ShowMessageTemplate(a_StringMessage, keyboard_template_func = None): if (len(a_Item) < 6): return simple_message.WorkFuncResult(error_find_proj_message) + if message_success_edit_message == a_StringMessage: + FlushMessages() msg = a_StringMessage.\ replace(f'#{name_field}', a_Item[1]).\ replace(f'#{desc_field}', a_Item[2]).\ @@ -239,6 +243,7 @@ async def MessagePreDelete(a_CallbackQuery : types.CallbackQuery, a_Item): async def MessagePostDelete(a_CallbackQuery : types.CallbackQuery, a_ItemID): log.Success(f'Сообщение №{a_ItemID} была удалена пользователем {a_CallbackQuery.from_user.id}.') #TODO: удалить вложенные + FlushMessages() return simple_message.WorkFuncResult(message_success_delete_message) # --------------------------------------------------------- @@ -253,11 +258,34 @@ def AddBDItemFunc(a_ItemData, a_UserID): else: log.Success(f'Пользоватлель {a_UserID}. Добавлена запись в таблицу {table_name} ({a_ItemData[photo_field]}, {a_ItemData[name_field]}, {a_ItemData[desc_field]}, {access.GetItemDefaultAccessForModule(module_name)}).') + FlushMessages() return res, error # --------------------------------------------------------- # API +def AddOrIgnoreMessage(a_Message : user_messages.Message): + return bot_bd.SQLRequestToBD(f'INSERT OR IGNORE INTO {table_name}({photo_field}, {name_field}, {desc_field}, {access_field}, {parent_id_field}, {create_datetime_field}) VALUES(?, ?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()})', + commit = True, return_error = True, param = (a_Message.m_PhotoID, a_Message.m_MessageName, a_Message.m_MessageDesc, access.GetItemDefaultAccessForModule(module_name), languages.GetLangID(a_Message.m_Language))) + +def FlushMessages(): + msg = user_messages.GetMessages() + for lang, msg_dict in msg.items(): + for msg_name, message in msg_dict.items(): + AddOrIgnoreMessage(message) + + msgs_bd = bd_item.GetAllItemsTemplate(table_name)() + if msgs_bd: + for m in msgs_bd: + name = m[1] + lang_id = m[5] + lang_name = languages.GetLangName(lang_id) + new_msg = user_messages.Message(name, m[2], lang_name, m[3]) + if not msg.get(lang_name, None): + msg[lang_name] = {} + msg[lang_name][name] = new_msg + user_messages.UpdateMSG(new_msg) + # Инициализация БД def GetInitBDCommands(): return init_bd_cmds diff --git a/bot_modules/start.py b/bot_modules/start.py index 616a6fe..f8def01 100644 --- a/bot_modules/start.py +++ b/bot_modules/start.py @@ -3,12 +3,17 @@ # Стартовое меню -from bot_sys import log, config, keyboard, user_access +from bot_sys import log, config, keyboard, user_access, user_messages from bot_modules import profile, projects, groups, access, backup, languages from template import simple_message from aiogram.dispatcher import Dispatcher +MSG = user_messages.MSG +def UpdateMSG(a_Message : user_messages.Message): + print(a_Message.m_MessageName, a_Message.m_MessageDesc) + globals()[a_Message.m_MessageName] = a_Message + # --------------------------------------------------------- # БД module_name = 'start' @@ -20,10 +25,11 @@ f"INSERT OR IGNORE INTO module_access (modName, modAccess, itemDefaultAccess) VA # --------------------------------------------------------- # Сообщения -start_message = ''' +MSG('start_message', ''' Добро пожаловать! Выберите возможные действия на кнопках ниже ⌨''' +, UpdateMSG) start_menu_button_name = "☰ Главное меню" diff --git a/bot_sys/user_messages.py b/bot_sys/user_messages.py new file mode 100644 index 0000000..46a2b99 --- /dev/null +++ b/bot_sys/user_messages.py @@ -0,0 +1,42 @@ +#-*-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 + +# --------------------------------------------------------- +# Функции работы с собщениями + +# --------------------------------------------------------- +class Message: + def __init__(self, a_MessageName : str, a_MessageDesc : str, a_Language : str, a_PhotoID : str): + self.m_MessageName = a_MessageName + self.m_MessageDesc = a_MessageDesc + self.m_Language = a_Language + self.m_PhotoID = a_PhotoID + def __str__(self): + return f'{self.m_MessageDesc}' + +def MSG(a_MessageName, a_MessageDesc, a_UpdateMSG): + cur_msg = Message(a_MessageName, a_MessageDesc, default_language, 0) + 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) + +def UpdateMSG(a_Message : Message): + print(a_Message.m_MessageName, a_Message.m_MessageDesc) + globals()[a_Message.m_MessageName] = a_Message diff --git a/main.py b/main.py index c5e12b9..4b74566 100644 --- a/main.py +++ b/main.py @@ -13,7 +13,7 @@ from bot_sys import config, log, bot_bd, user_access from bot_modules import profile, start, projects, groups, access, backup, tasks, needs, comments, messages, languages storage = MemoryStorage() -bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode = types.ParseMode.HTML) +bot = Bot(token = config.GetTelegramBotApiToken(), parse_mode = types.ParseMode.HTML) dp = Dispatcher(bot, storage = storage) # Первичная инициализация модулей. Все модули должны быть прописаны в списке modules @@ -21,21 +21,26 @@ modules = [tasks, access, profile, start, projects, groups, backup, needs, comme init_bd_cmd = [] for m in modules: - m.RegisterHandlers(dp) c = m.GetInitBDCommands() if not c is None: init_bd_cmd += c -# Первичаня инициализация базы данных +# Первичная инициализация базы данных bot_bd.BDExecute(init_bd_cmd) +languages.FlushLanguages() +messages.FlushMessages() + +for m in modules: + m.RegisterHandlers(dp) + # Юнит тесты модулей и файлов test_mods = [user_access] for m in test_mods: m.Test() if __name__ == '__main__': - os.system('clear') - os.system('cls') +# os.system('clear') +# os.system('cls') log.Success(log_start_message) executor.start_polling(dp)