From 1e016c297dd6af2edfeae7e70d87fee181f7f7d1 Mon Sep 17 00:00:00 2001 From: Alexei Date: Sat, 13 May 2023 23:44:16 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=84=D0=B0=D0=B9=D0=BB=20=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D0=B0=D0=B5=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_modules/mod_simple_message.py | 4 +- bot_modules/profile.py | 134 +++++++++++++++----------------------- bot_modules/start.py | 9 +-- bot_sys/aiogram_bot.py | 9 ++- bot_sys/bot_messages.py | 7 +- bot_sys/keyboard.py | 4 +- main.py | 11 +++- template/bd_item.py | 2 +- template/simple_message.py | 8 +-- 9 files changed, 86 insertions(+), 102 deletions(-) diff --git a/bot_modules/mod_simple_message.py b/bot_modules/mod_simple_message.py index f7030bf..2bc56eb 100644 --- a/bot_modules/mod_simple_message.py +++ b/bot_modules/mod_simple_message.py @@ -35,8 +35,8 @@ class SimpleMessageModule(mod_interface.IModule): self.m_StartMessageHandler = simple_message.SimpleMessageTemplate( self.m_Bot, self.m_StartMessageHandlerFunc, - None, self.m_GetStartKeyboardButtonsFunc, + None, self.m_GetAccessFunc ) @@ -75,7 +75,7 @@ class SimpleMessageModule(mod_interface.IModule): def GetModuleButtons(self): return [ - keyboard.ButtonWithAccess(self.m_StartButtonName, user_access.AccessMode.VIEW, GetAccess()), + keyboard.ButtonWithAccess(self.m_StartButtonName, user_access.AccessMode.VIEW, self.GetAccess()), ] def RegisterHandlers(self): diff --git a/bot_modules/profile.py b/bot_modules/profile.py index b910900..2b958cf 100644 --- a/bot_modules/profile.py +++ b/bot_modules/profile.py @@ -3,12 +3,9 @@ # Профиль пользователя -from bot_sys import bot_bd, log, config, keyboard, user_access, user_messages -from bot_modules import start, access, groups -from template import simple_message - -from aiogram import types -from aiogram.dispatcher import Dispatcher +from bot_sys import user_access, bot_bd +from bot_modules import mod_simple_message, groups, access_utils +from template import bd_item, simple_message # --------------------------------------------------------- # БД @@ -24,30 +21,7 @@ language_code_field = 'userLanguageCode' access_field = 'userAccess' create_datetime_field = 'createDateTime' -init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_name}( - {key_name} INTEGER, - {name_field} TEXT, - {name1_field} TEXT, - {name2_field} TEXT, - {is_bot_field} TEXT, - {language_code_field} TEXT, - {access_field} TEXT, - {create_datetime_field} TEXT, - UNIQUE({key_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}=+');" -] - -def MSG(a_MessageName, a_MessageDesc): - def UpdateMSG(a_Message : user_messages.Message): - print(a_Message.m_MessageName, a_Message.m_MessageDesc) - globals()[a_Message.m_MessageName] = a_Message - user_messages.MSG(a_MessageName, a_MessageDesc, UpdateMSG, log.GetTimeNow()) - -# --------------------------------------------------------- -# Сообщения - -MSG('profile_message', f''' +start_message = f''' 📰 Профиль: ID: #{key_name} @@ -56,25 +30,41 @@ MSG('profile_message', f''' Имя2: #{name2_field} Код языка: #{language_code_field} Дата добавления: #{create_datetime_field} -''') - -user_profile_button_name = "📰 Профиль" - -# --------------------------------------------------------- -# Работа с кнопками - -def GetStartKeyboardButtons(a_Message, a_UserGroups): - mods = [start] - return keyboard.MakeKeyboardForMods(mods, a_UserGroups) - -# --------------------------------------------------------- -# Обработка сообщений - -async def ProfileOpen(a_Message, state = None): - user_info = GetUserInfo(a_Message.from_user.id) - msg = profile_message - if not user_info is None: - msg = str(msg).\ +''' + +start_menu_button_name = "📰 Профиль" + +class ModuleProfile(mod_simple_message.SimpleMessageModule): + def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): + a_InitAccess = f'{user_access.user_access_group_new}=+' + super().__init__(start_message, start_menu_button_name, a_InitAccess, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + + def GetInitBDCommands(self): + return super(). GetInitBDCommands() + [ + f"""CREATE TABLE IF NOT EXISTS {table_name}( + {key_name} INTEGER, + {name_field} TEXT, + {name1_field} TEXT, + {name2_field} TEXT, + {is_bot_field} TEXT, + {language_code_field} TEXT, + {access_field} TEXT, + {create_datetime_field} TEXT, + UNIQUE({key_name}) + );""", + ] + + def GetName(self): + return module_name + + # Основной обработчик главного сообщения + async def StartMessageHandler(self, a_Message, state = None): + user_info = GetUserInfo(self.m_Bot, a_Message.from_user.id) + lang = str(a_Message.from_user.language_code) + msg = self.m_StartMessage + msg = msg.GetMessageForLang(lang).StaticCopy() + if not user_info is None: + msg.m_MessageDesc = msg.GetDesc().\ replace(f'#{key_name}', str(user_info[0])).\ replace(f'#{name_field}', str(user_info[1])).\ replace(f'#{name1_field}', str(user_info[2])).\ @@ -83,46 +73,28 @@ async def ProfileOpen(a_Message, state = None): replace(f'#{language_code_field}', str(user_info[5])).\ replace(f'#{access_field}', str(user_info[6])).\ replace(f'#{create_datetime_field}', str(user_info[7])) - return simple_message.WorkFuncResult(msg, item_access = str(user_info[6])) - return simple_message.WorkFuncResult(msg) + return simple_message.WorkFuncResult(msg, item_access = str(user_info[6])) + return await super().StartMessageHandler(a_Message, state) + -# --------------------------------------------------------- # Работа с базой данных пользователей # Добавление пользователя, если он уже есть, то игнорируем -def AddUser(a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode): - bot_bd.SQLRequestToBD(f"INSERT OR IGNORE INTO users ({key_name}, {name_field}, {name1_field}, {name2_field}, {is_bot_field}, {language_code_field}, {access_field}, {create_datetime_field}) VALUES (?, ?, ?, ?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()});", - commit=True, param = (a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode, access.GetItemDefaultAccessForModule(module_name))) - - user_groups = groups.GetUserGroupData(a_UserID) +def AddUser(a_Bot, a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode): + a_Bot.SQLRequest(f"INSERT OR IGNORE INTO users ({key_name}, {name_field}, {name1_field}, {name2_field}, {is_bot_field}, {language_code_field}, {access_field}, {create_datetime_field}) VALUES (?, ?, ?, ?, ?, ?, ?, {bot_bd.GetBDDateTimeNow()});", + commit=True, param = (a_UserID, a_UserName, a_UserName1, a_UserName2, a_UserIsBot, a_LanguageCode, access_utils.GetItemDefaultAccessForModule(a_Bot, module_name))) +''' + user_groups = access_utils.GetUserGroupData(a_Bot, a_UserID) # Если пользователь не состоит ни в одной группе, то добавляем его в группу user_access.user_access_group_new if len(user_groups.group_names_list) == 0: - new_group_id = bot_bd.SQLRequestToBD(f'SELECT {groups.key_table_groups_name} FROM {groups.table_groups_name} WHERE {groups.name_table_groups_field} = ?', + new_group_id = a_Bot.SQLRequest(f'SELECT {groups.key_table_groups_name} FROM {groups.table_groups_name} WHERE {groups.name_table_groups_field} = ?', param = [user_access.user_access_group_new]) if new_group_id and new_group_id[0]: - bot_bd.SQLRequestToBD(f"INSERT OR IGNORE INTO {groups.table_user_in_groups_name} ({groups.user_id_field}, {groups.key_table_groups_name}, {groups.access_field}, {groups.create_datetime_field}) VALUES (?, ?, ?, {bot_bd.GetBDDateTimeNow()});", - commit=True, param = (a_UserID, new_group_id[0][0], access.GetItemDefaultAccessForModule(module_name))) - -def GetUserInfo(a_UserID): - user_info = bot_bd.SQLRequestToBD('SELECT * FROM users WHERE user_id = ?', param = [a_UserID]) + a_Bot.SQLRequest(f"INSERT OR IGNORE INTO {groups.table_user_in_groups_name} ({groups.user_id_field}, {groups.key_table_groups_name}, {groups.access_field}, {groups.create_datetime_field}) VALUES (?, ?, ?, {bot_bd.GetBDDateTimeNow()});", + commit=True, param = (a_UserID, new_group_id[0][0], access_utils.GetItemDefaultAccessForModule(a_Bot, module_name))) +''' +def GetUserInfo(a_Bot, a_UserID): + user_info = a_Bot.SQLRequest('SELECT * FROM users WHERE user_id = ?', param = [a_UserID]) if len(user_info) != 0: return user_info[0] return None - -# --------------------------------------------------------- -# API - -# Инициализация БД -def GetInitBDCommands(): - return init_bd_cmds - -def GetAccess(): - return access.GetAccessForModule(module_name) - -# Доступные кнопки -def GetModuleButtons(): - return [keyboard.ButtonWithAccess(user_profile_button_name, user_access.AccessMode.VIEW, GetAccess())] - -# Обработка кнопок -def RegisterHandlers(dp : Dispatcher): - dp.register_message_handler(simple_message.SimpleMessageTemplateLegacy(ProfileOpen, GetStartKeyboardButtons, GetAccess), text = user_profile_button_name) diff --git a/bot_modules/start.py b/bot_modules/start.py index fab84aa..34f3514 100644 --- a/bot_modules/start.py +++ b/bot_modules/start.py @@ -4,7 +4,7 @@ # Стартовое меню from bot_sys import user_access -from bot_modules import mod_simple_message +from bot_modules import mod_simple_message, profile from template import bd_item start_message = ''' @@ -29,7 +29,7 @@ class ModuleStart(mod_simple_message.SimpleMessageModule): last_name = str(a_Message.from_user.last_name) is_bot = str(a_Message.from_user.is_bot) language_code = str(a_Message.from_user.language_code) - #profile.AddUser(user_id, user_name, first_name, last_name, is_bot, language_code) + profile.AddUser(self.m_Bot, user_id, user_name, first_name, last_name, is_bot, language_code) self.m_Log.Info(f'Пользователь {user_id} {user_name} авторизовался в боте. Полные данные {a_Message.from_user}.') return await super().StartMessageHandler(a_Message, state) @@ -42,8 +42,3 @@ class ModuleStart(mod_simple_message.SimpleMessageModule): ) - -#def GetStartKeyboardButtons(a_Message, a_UserGroups): -# mods = [profile, projects, groups, access, backup, languages] -# return keyboard.MakeKeyboardForMods(mods, a_UserGroups) - diff --git a/bot_sys/aiogram_bot.py b/bot_sys/aiogram_bot.py index a2994f8..cf18b35 100644 --- a/bot_sys/aiogram_bot.py +++ b/bot_sys/aiogram_bot.py @@ -29,9 +29,13 @@ class AiogramBot(interfaces.IBot): 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_InlineKeyboardButtons, a_KeyboardButtons): - inline_keyboard = keyboard.MakeAiogramInlineKeyboard(a_InlineKeyboardButtons) - base_keyboard = keyboard.MakeAiogramKeyboard(a_KeyboardButtons) + inline_keyboard = None if a_InlineKeyboardButtons: + inline_keyboard = keyboard.MakeAiogramInlineKeyboard(a_InlineKeyboardButtons) + base_keyboard = None + if a_KeyboardButtons: + base_keyboard = keyboard.MakeAiogramKeyboard(a_KeyboardButtons) + if inline_keyboard: base_keyboard = inline_keyboard if a_PhotoIDs and a_PhotoIDs != 0 and a_PhotoIDs != '0': await self.m_TBot.send_photo( @@ -41,6 +45,7 @@ class AiogramBot(interfaces.IBot): reply_markup = base_keyboard ) else: + #print('SendMessage', a_UserID, a_Message, a_PhotoIDs, a_InlineKeyboardButtons, a_KeyboardButtons, base_keyboard) await self.m_TBot.send_message( a_UserID, a_Message, diff --git a/bot_sys/bot_messages.py b/bot_sys/bot_messages.py index ef1fb34..2f8b968 100644 --- a/bot_sys/bot_messages.py +++ b/bot_sys/bot_messages.py @@ -12,6 +12,9 @@ class BotMessage: self.m_PhotoID = a_PhotoID self.m_DateTime = a_DateTime + def StaticCopy(self): + return BotMessage(None, self.m_MessageName, self.m_MessageDesc, self.m_Language, self.m_PhotoID, self.m_DateTime) + def GetName(self): return self.m_MessageName @@ -25,10 +28,12 @@ class BotMessage: return self.m_PhotoID def __str__(self): - msg = GetMessageForLang(self.m_Language) + msg = self.GetMessageForLang(self.m_Language) return msg.GetDesc() def GetMessageForLang(self, a_Language): + if not self.m_BotMessages: + return self last_update = self.m_BotMessages.m_LastUpdate new_msg = self if self.m_DateTime < last_update: diff --git a/bot_sys/keyboard.py b/bot_sys/keyboard.py index c114e27..ba3a38e 100644 --- a/bot_sys/keyboard.py +++ b/bot_sys/keyboard.py @@ -37,7 +37,7 @@ def MakeButtons(a_ButtonList : [ButtonWithAccess], a_UserGroups): buttons = [] for b in a_ButtonList: if user_access.CheckAccessString(b.access_string, a_UserGroups, b.access_mode): - buttons += [types.KeyboardButton(b.label)] + buttons += [types.KeyboardButton(str(b.label))] step = GetButtonInRowCount(len(buttons)) return Chunks(buttons, step) @@ -69,7 +69,7 @@ def MakeAiogramInlineKeyboard(a_ButtonList : [InlineButton]): for row in a_ButtonList: r = [] for b in row: - r += [types.InlineKeyboardButton(text = b.label, callback_data = b.callback_data)] + r += [types.InlineKeyboardButton(text = str(b.label), callback_data = b.callback_data)] buttons += r inline_keyboard = InlineKeyboardMarkup(inline_keyboard=buttons) return inline_keyboard diff --git a/main.py b/main.py index c93b3f0..0f29a7c 100644 --- a/main.py +++ b/main.py @@ -6,7 +6,7 @@ log_start_message = 'Бот успешно запущен!' import os from bot_sys import config, log, bot_bd, user_access, aiogram_bot, bot_messages -from bot_modules import mod_agregator, start #, projects, groups, access, backup, tasks, needs, comments, messages, profile, languages +from bot_modules import mod_agregator, start, profile #, projects, groups, access, backup, tasks, needs, comments, messages, , languages g_Log = log g_Bot = aiogram_bot.AiogramBot(config.GetTelegramBotApiToken(), bot_bd.GetBDFileName(), config.GetRootIDs(), g_Log) @@ -18,7 +18,13 @@ g_BotButtons = bot_messages.BotMessages(default_language) g_ModuleAgregator = mod_agregator.ModuleAgregator() -mod_start = start.ModuleStart([], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +mod_start_name = 'start' + +mod_profile = profile.ModuleProfile([mod_start_name], g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +g_ModuleAgregator.AddModule(mod_profile) + +start_mod_name_list = [mod_profile.GetName()]#, 'projects', 'groups', 'access', 'backup', 'languages'] +mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_start) # Первичная инициализация модулей. Все модули должны быть прописаны в списке modules @@ -40,6 +46,7 @@ g_BotButtons.UpdateSignal(g_Log.GetTimeNow()) #messages.FlushMessages() for m in modules: + print(m) m.RegisterHandlers() # Юнит тесты модулей и файлов diff --git a/template/bd_item.py b/template/bd_item.py index 610c04f..060457d 100644 --- a/template/bd_item.py +++ b/template/bd_item.py @@ -31,7 +31,7 @@ def GetCheckForPrefixFunc(a_Prefix): return lambda x: x.data.startswith(a_Prefix) def GetCheckForTextFunc(a_Text): - return lambda x: x.text == a_Text + return lambda x: x.text == str(a_Text) def GetCheckForCommandsFunc(a_Commands): return lambda x: x.commands == a_Commands diff --git a/template/simple_message.py b/template/simple_message.py index 0a5f4a5..7a56bb3 100644 --- a/template/simple_message.py +++ b/template/simple_message.py @@ -19,11 +19,11 @@ def InfoMessageTemplate(a_Bot, a_HelpMessage, a_GetButtonsFunc, a_GetInlineButto return SimpleMessageTemplate(a_Bot, GetMessage, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_AccessFunc, access_mode = access_mode) def SimpleMessageTemplate(a_Bot, a_WorkFunc, a_GetButtonsFunc, a_GetInlineButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW): - def ProxyGetButtonsTemplate(a_GetButtonsFunc): + def ProxyGetButtonsTemplate(a_GetButtonsFunc1): def ReturnNone(a_Message, user_groups): return None - if a_GetButtonsFunc: - return a_GetButtonsFunc + if a_GetButtonsFunc1: + return a_GetButtonsFunc1 else: return ReturnNone @@ -54,7 +54,7 @@ def SimpleMessageTemplate(a_Bot, a_WorkFunc, a_GetButtonsFunc, a_GetInlineButton if not res.item_access is None and not user_access.CheckAccess(a_Bot.GetRootIDs(), res.item_access, user_groups, access_mode): return await AccessDeniedMessage(user_id, a_Message, user_groups) - msg = msg.GetMessageForLang(lang) + msg = msg.GetMessageForLang(lang).StaticCopy() await a_Bot.SendMessage( user_id,