From 66baaabf987ca4632238414354df01636f2ce0ee Mon Sep 17 00:00:00 2001 From: Alexei Date: Wed, 24 May 2023 12:21:06 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=BE=D0=B4=D1=83=D0=BB=D1=8C=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0=D1=82=D0=B5=D0=BB?= =?UTF-8?q?=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bot_modules/profile.py | 67 +++----------- bot_modules/start.py | 4 +- bot_modules/users.py | 159 ++++++++++++++++++++++++++++++++++ bot_modules/users_groups_agregator.py | 2 +- main.py | 47 +++++----- 5 files changed, 197 insertions(+), 82 deletions(-) create mode 100644 bot_modules/users.py diff --git a/bot_modules/profile.py b/bot_modules/profile.py index 7c3a986..bda5c46 100644 --- a/bot_modules/profile.py +++ b/bot_modules/profile.py @@ -4,34 +4,13 @@ # Профиль пользователя from bot_sys import user_access, bot_bd, bd_table -from bot_modules import mod_simple_message, access, access_utils, groups_utils, users_groups_agregator +from bot_modules import mod_simple_message, access, access_utils, groups_utils, users_groups_agregator, users from template import bd_item, simple_message # --------------------------------------------------------- # БД module_name = 'profile' -table_name = 'users' -key_name = 'user_id' -name_field = 'userName' -name1_field = 'userFirstName' -name2_field = 'userLastName' -is_bot_field = 'userIsBot' -language_code_field = 'userLanguageCode' -access_field = 'userAccess' -create_datetime_field = 'createDateTime' - -table = bd_table.Table(table_name, [ - bd_table.TableField(key_name, bd_table.TableFieldDestiny.KEY, bd_table.TableFieldType.INT), - bd_table.TableField(name_field, bd_table.TableFieldDestiny.NAME, bd_table.TableFieldType.STR), - bd_table.TableField(name1_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), - bd_table.TableField(name2_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), - bd_table.TableField(is_bot_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), - bd_table.TableField(language_code_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), - bd_table.TableField(access_field, bd_table.TableFieldDestiny.ACCESS, bd_table.TableFieldType.STR), - bd_table.TableField(create_datetime_field, bd_table.TableFieldDestiny.CREATE_DATE, bd_table.TableFieldType.STR), - ]) - button_names = { mod_simple_message.ButtonNames.START: "📰 Профиль", } @@ -40,12 +19,12 @@ messages = { mod_simple_message.Messages.START: f''' 📰 Профиль: -ID: #{key_name} -Имя: #{name_field} -Имя1: #{name1_field} -Имя2: #{name2_field} -Код языка: #{language_code_field} -Дата добавления: #{create_datetime_field} +ID: #{users.key_name} +Имя: #{users.name_field} +Имя1: #{users.name1_field} +Имя2: #{users.name2_field} +Код языка: #{users.language_code_field} +Дата добавления: #{users.create_datetime_field} ''', } @@ -55,44 +34,18 @@ class ModuleProfile(mod_simple_message.SimpleMessageModule): def __init__(self, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): super().__init__(messages, button_names, init_access, a_ChildModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) - def GetInitBDCommands(self): - return super(). GetInitBDCommands() + [ - table.GetInitTableRequest(), - ] - 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) + user_info = users.GetUserInfo(self.m_Bot, a_Message.from_user.id) lang = str(a_Message.from_user.language_code) if not user_info is None: msg = self.GetMessage(mod_simple_message.Messages.START) msg = msg.GetMessageForLang(lang).StaticCopy() - msg.UpdateDesc(table.ReplaceAllFieldTags(msg.GetDesc(), user_info)) - return simple_message.WorkFuncResult(msg, item_access = str(user_info[table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS)])) + msg.UpdateDesc(users.table.ReplaceAllFieldTags(msg.GetDesc(), user_info)) + return simple_message.WorkFuncResult(msg, item_access = str(user_info[users.table.GetFieldIDByDestiny(bd_table.TableFieldDestiny.ACCESS)])) return await super().StartMessageHandler(a_Message, state) -# Работа с базой данных пользователей - -# Добавление пользователя, если он уже есть, то игнорируем -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 = groups_utils.GetUserGroupData(a_Bot, a_UserID) - # Если пользователь не состоит ни в одной группе, то добавляем его в группу user_access.user_access_group_new - if len(user_groups.group_names_list) == 0: - new_group_id = a_Bot.SQLRequest(f'SELECT {users_groups_agregator.key_table_groups_name} FROM {users_groups_agregator.table_groups_name} WHERE {users_groups_agregator.name_table_groups_field} = ?', - param = [user_access.user_access_group_new]) - if new_group_id and new_group_id[0]: - a_Bot.SQLRequest(f"INSERT OR IGNORE INTO {users_groups_agregator.table_user_in_groups_name} ({users_groups_agregator.user_id_field}, {users_groups_agregator.key_table_groups_name}, {users_groups_agregator.access_field}, {users_groups_agregator.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 diff --git a/bot_modules/start.py b/bot_modules/start.py index d4012c3..8088ac7 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, profile +from bot_modules import mod_simple_message, users from template import bd_item module_name = 'start' @@ -37,7 +37,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(self.m_Bot, user_id, user_name, first_name, last_name, is_bot, language_code) + users.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) diff --git a/bot_modules/users.py b/bot_modules/users.py new file mode 100644 index 0000000..2389d98 --- /dev/null +++ b/bot_modules/users.py @@ -0,0 +1,159 @@ +# -*- coding: utf8 -*- +# Общественное достояние, 2023, Алексей Безбородов (Alexei Bezborodov) + +# Проекты + +from bot_sys import bot_bd, keyboard, user_access, bd_table +from bot_modules import mod_table_operate, mod_simple_message +from bot_modules import users_groups_agregator, access_utils, groups_utils + +# --------------------------------------------------------- +# БД +module_name = 'users' + +table_name = module_name +key_name = 'user_id' +name_field = 'userName' +name1_field = 'userFirstName' +name2_field = 'userLastName' +is_bot_field = 'userIsBot' +language_code_field = 'userLanguageCode' +photo_field = 'userPhoto' +access_field = 'userAccess' +create_datetime_field = 'createDateTime' + +table = bd_table.Table(table_name, [ + bd_table.TableField(key_name, bd_table.TableFieldDestiny.KEY, bd_table.TableFieldType.INT), + bd_table.TableField(name_field, bd_table.TableFieldDestiny.NAME, bd_table.TableFieldType.STR), + bd_table.TableField(name1_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), + bd_table.TableField(name2_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), + bd_table.TableField(is_bot_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), + bd_table.TableField(language_code_field, bd_table.TableFieldDestiny.DESC, bd_table.TableFieldType.STR), + bd_table.TableField(photo_field, bd_table.TableFieldDestiny.PHOTO, bd_table.TableFieldType.STR), + bd_table.TableField(access_field, bd_table.TableFieldDestiny.ACCESS, bd_table.TableFieldType.STR), + bd_table.TableField(create_datetime_field, bd_table.TableFieldDestiny.CREATE_DATE, bd_table.TableFieldType.STR), + ]) + +init_access = f'{user_access.user_access_group_new}=-' + +# --------------------------------------------------------- +# Сообщения и кнопки + +button_names = { + mod_simple_message.ButtonNames.START: "👤 Пользователи", + mod_table_operate.ButtonNames.LIST: "📃 Список пользователей", +# mod_table_operate.ButtonNames.ADD: "✅ Добавить пользователя", + mod_table_operate.ButtonNames.EDIT: "🛠 Редактировать пользователя", + mod_table_operate.ButtonNames.EDIT_PHOTO: "☐ Изменить изображение в пользователяе", + mod_table_operate.ButtonNames.EDIT_NAME: "≂ Изменить название в пользователяе", + mod_table_operate.ButtonNames.EDIT_DESC: "𝌴 Изменить описание в пользователяе", + mod_table_operate.ButtonNames.EDIT_ACCESS: "✋ Изменить доступ к пользователю", + mod_table_operate.ButtonNames.DEL: "❌ Удалить пользователя", +} + +messages = { + mod_simple_message.Messages.START: f''' +{button_names[mod_simple_message.ButtonNames.START]} + +''', + mod_table_operate.Messages.SELECT: ''' +Пожалуйста, выберите пользователя: +''', + mod_table_operate.Messages.ERROR_FIND: ''' +❌ Ошибка, пользователя не найден +''', + mod_table_operate.Messages.OPEN: f''' +Пользователь: #{name_field} + +ID: #{key_name} +Имя: #{name_field} +Имя1: #{name1_field} +Имя2: #{name2_field} +Код языка: #{language_code_field} +Дата добавления: #{create_datetime_field} + +Время создания: #{create_datetime_field} +''', + mod_table_operate.Messages.CREATE_NAME: ''' +Создание пользователя. Шаг №1 + +Введите название пользователя: +''', + mod_table_operate.Messages.CREATE_DESC: ''' +Создание пользователя. Шаг №2 + +Введите описание пользователя: +''', + mod_table_operate.Messages.CREATE_PHOTO: ''' +Создание пользователя. Шаг №3 + +Загрузите обложку для пользователя (Фото): +Она будет отображаться в его описании. +''', + mod_table_operate.Messages.SUCCESS_CREATE: '''✅ Пользователь успешно добавлен!''', + mod_table_operate.Messages.START_EDIT: ''' +Пожалуйста, выберите действие: +''', + mod_table_operate.Messages.SELECT_TO_EDIT: ''' +Выберите пользователя, которого вы хотите отредактировать. +''', + mod_table_operate.Messages.EDIT_PHOTO: ''' +Загрузите новую обложку для пользователя (Фото): +Она будет отображаться в его описании. +''', + mod_table_operate.Messages.EDIT_NAME: f''' +Текущее название пользователя: +#{name_field} + +Введите новое название пользователя: +''', + mod_table_operate.Messages.EDIT_DESC: f''' +Текущее описание пользователя: +#{name1_field} + +Введите новое описание пользователя: +''', + mod_table_operate.Messages.EDIT_ACCESS: f''' +Текущий доступ к пользователю: +#{access_field} + +{user_access.user_access_readme} + +Введите новую строку доступа: +''', + mod_table_operate.Messages.SUCCESS_EDIT: '''✅ Пользователь успешно отредактирован!''', + mod_table_operate.Messages.SELECT_TO_DELETE: ''' +Выберите пользователя, который вы хотите удалить. +''', + mod_table_operate.Messages.SUCCESS_DELETE: '''✅ Пользователь успешно удалён!''', +} + +class ModuleUsers(mod_table_operate.TableOperateModule): + def __init__(self, a_ParentModName, a_ChildModName, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log): + super().__init__(table, messages, button_names, a_ParentModName, a_ChildModName, init_access, a_ChildModuleNameList, a_EditModuleNameList, a_Bot, a_ModuleAgregator, a_BotMessages, a_BotButtons, a_Log) + + def GetName(self): + return module_name + + +# Работа с базой данных пользователей + +# Добавление пользователя, если он уже есть, то игнорируем +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}, {photo_field}, {access_field}, {create_datetime_field}) VALUES (?, ?, ?, ?, ?, ?, 0, ?, {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 = groups_utils.GetUserGroupData(a_Bot, a_UserID) + # Если пользователь не состоит ни в одной группе, то добавляем его в группу user_access.user_access_group_new + if len(user_groups.group_names_list) == 0: + new_group_id = a_Bot.SQLRequest(f'SELECT {users_groups_agregator.key_table_groups_name} FROM {users_groups_agregator.table_groups_name} WHERE {users_groups_agregator.name_table_groups_field} = ?', + param = [user_access.user_access_group_new]) + if new_group_id and new_group_id[0]: + a_Bot.SQLRequest(f"INSERT OR IGNORE INTO {users_groups_agregator.table_user_in_groups_name} ({users_groups_agregator.user_id_field}, {users_groups_agregator.key_table_groups_name}, {users_groups_agregator.access_field}, {users_groups_agregator.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 diff --git a/bot_modules/users_groups_agregator.py b/bot_modules/users_groups_agregator.py index a6c2fce..d98146e 100644 --- a/bot_modules/users_groups_agregator.py +++ b/bot_modules/users_groups_agregator.py @@ -51,7 +51,7 @@ sql_request_button_name = "⛃ Запрос к БД для редактиров help_button_name = "📄 Информация по группам" button_names = { - mod_simple_message.ButtonNames.START: "‍️️▦ Группы пользователей", + mod_simple_message.ButtonNames.START: "‍️️▦ Группы и пользователи", } messages = { diff --git a/main.py b/main.py index eff38b7..bbbd0cf 100644 --- a/main.py +++ b/main.py @@ -4,7 +4,7 @@ import os from bot_sys import config, log, aiogram_bot, bot_messages, bd_table, user_access -from bot_modules import mod_agregator, start, profile, backup, users_groups_agregator, access, projects, tasks, needs, comments, languages, messages, buttons +from bot_modules import mod_agregator, start, profile, backup, users_groups_agregator, access, projects, tasks, needs, comments, languages, messages, buttons, users log_start_message = 'Бот успешно запущен!' @@ -30,59 +30,62 @@ mod_projects_name = projects.module_name mod_languages_name = languages.module_name mod_messages_name = messages.module_name mod_buttons_name = buttons.module_name +mod_users_name = users.module_name start_mod_list = [mod_start_name] mod_access = access.ModuleAccess(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_access) -start_mod_name_list = [mod_start_name] -mod_groups = users_groups_agregator.ModuleUsersGroupsAgregator(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) -g_ModuleAgregator.AddModule(mod_groups) +mod_users = users.ModuleUsers(None, None, start_mod_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +g_ModuleAgregator.AddModule(mod_users) + +child_mod_name_list = [mod_start_name, mod_users_name] +mod_users_groups_agregator = users_groups_agregator.ModuleUsersGroupsAgregator(child_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +g_ModuleAgregator.AddModule(mod_users_groups_agregator) -start_mod_list = [mod_start_name] mod_profile = profile.ModuleProfile(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_profile) mod_backup = backup.ModuleBackup(start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_backup) -start_mod_name_list = [mod_start_name, mod_tasks_name, mod_needs_name, mod_comments_name] -mod_project = projects.ModuleProjects(None, mod_tasks_name, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name, mod_tasks_name, mod_needs_name, mod_comments_name] +mod_project = projects.ModuleProjects(None, mod_tasks_name, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_project) -start_mod_name_list = [mod_start_name]#, mod_projects_name, mod_needs_name, mod_comments_name] -mod_tasks = tasks.ModuleTasks(mod_projects_name, mod_needs_name, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name]#, mod_projects_name, mod_needs_name, mod_comments_name] +mod_tasks = tasks.ModuleTasks(mod_projects_name, mod_needs_name, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_tasks) -start_mod_name_list = [mod_start_name]#, mod_projects_name, mod_tasks_name, mod_comments_name] -mod_needs= needs.ModuleNeeds(mod_tasks_name, mod_comments_name, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name]#, mod_projects_name, mod_tasks_name, mod_comments_name] +mod_needs= needs.ModuleNeeds(mod_tasks_name, mod_comments_name, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_needs) -start_mod_name_list = [mod_start_name]#, mod_projects_name, mod_tasks_name, mod_needs_name] -mod_comments= comments.ModuleComments(mod_needs_name, None, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name]#, mod_projects_name, mod_tasks_name, mod_needs_name] +mod_comments= comments.ModuleComments(mod_needs_name, None, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_comments) -start_mod_name_list = [mod_start_name, mod_messages_name, mod_buttons_name] -mod_languages = languages.ModuleLanguages(None, mod_messages_name, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name, mod_messages_name, mod_buttons_name] +mod_languages = languages.ModuleLanguages(None, mod_messages_name, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_languages) -start_mod_name_list = [mod_start_name] -mod_messages = messages.ModuleMessages(mod_languages_name, None, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name] +mod_messages = messages.ModuleMessages(mod_languages_name, None, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_messages) -start_mod_name_list = [mod_start_name] -mod_buttons = buttons.ModuleButtons(mod_languages_name, None, start_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +child_mod_name_list = [mod_start_name] +mod_buttons = buttons.ModuleButtons(mod_languages_name, None, child_mod_name_list, start_mod_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_buttons) -start_mod_name_list = [ +child_mod_name_list = [ mod_profile.GetName(), mod_backup.GetName(), - mod_groups.GetName(), + mod_users_groups_agregator.GetName(), mod_access.GetName(), mod_project.GetName(), mod_languages.GetName(), ] -mod_start = start.ModuleStart(start_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) +mod_start = start.ModuleStart(child_mod_name_list, g_Bot, g_ModuleAgregator, g_BotMessages, g_BotButtons, g_Log) g_ModuleAgregator.AddModule(mod_start) # Первичная инициализация модулей.