Browse Source

Просмотри проектов переведён на шаблоны

test_bot
Alexei 2 years ago
parent
commit
8591175e65
  1. 2
      bot_modules/profile.py
  2. 62
      bot_modules/projects.py
  3. 2
      bot_modules/start.py
  4. 64
      template/bd_item_view.py
  5. 20
      template/simple_message.py

2
bot_modules/profile.py

@ -49,7 +49,7 @@ async def ProfileOpen(a_Message):
msg = profile_message
if not user_info is None:
msg = msg.replace('@user_id', str(user_info[0])).replace('@user_name', str(user_info[1]))
return msg
return msg, None
# ---------------------------------------------------------
# Работа с базой данных пользователей

62
bot_modules/projects.py

@ -5,6 +5,8 @@
from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, access, groups
from template import bd_item_view, simple_message
from aiogram import Bot, types
from aiogram.dispatcher import FSMContext
@ -27,14 +29,17 @@ class FSMEditProject(StatesGroup):
# ---------------------------------------------------------
# БД
table_name = 'projects'
module_name = 'projects'
table_name = 'projects'
key_name = 'projectID'
init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}(
projectPhoto TEXT,
projectName TEXT,
projectDesc TEXT,
projectID INTEGER PRIMARY KEY
projectAccess TEXT,
{key_name} INTEGER PRIMARY KEY
)''',
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=va');"
]
@ -44,7 +49,7 @@ f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name
# Сообщения
base_project_message = '''
<b>🛒 Проекты</b>
<b>🟥 Проекты</b>
'''
select_project_message = '''
@ -52,7 +57,7 @@ select_project_message = '''
'''
error_find_proj_message = '''
Ошибка, проект с ID @project_id не найден
Ошибка, проект не найден
'''
project_open_message = '''
@ -179,13 +184,30 @@ def GetProjectsListKeyboardButtons(a_UserGroups, a_Prefix):
# ---------------------------------------------------------
# Обработка сообщений
# Отображение всех проектов
def GetButtonNameAndKeyValueAndAccess(a_Item):
# projectName projectID projectAccess
return a_Item[1], a_Item[4], a_Item[3]
async def ShowProject(a_CallbackQuery : types.CallbackQuery, a_Item):
if (len(a_Item) < 3):
return error_find_proj_message, None
photo_id = a_Item[0]
name = a_Item[1]
desc = a_Item[2]
msg = project_open_message.replace('@proj_name', name).replace('@proj_desk', desc)
return msg, photo_id
select_handler = 0
# стартовое сообщение
async def ProjectsOpen(a_Message : types.message):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
await bot.send_message(a_Message.from_user.id, base_project_message, reply_markup = GetEditProjectKeyboardButtons(user_groups))
await bot.send_message(a_Message.from_user.id, select_project_message, reply_markup = GetProjectsListKeyboardButtons(user_groups, select_project_callback_prefix))
await a_Message.answer(base_project_message, reply_markup = GetEditProjectKeyboardButtons(user_groups))
await select_handler(a_Message)
return None
# Создание нового проекта
def GetProjectData(a_ProjectID):
project = GetProject(a_ProjectID)
if len(project) < 1:
@ -196,23 +218,6 @@ def GetProjectData(a_ProjectID):
p = project[0]
return '', p[0], p[1], p[2]
async def ShowProject(a_CallbackQuery : types.CallbackQuery):
project_id = str(a_CallbackQuery.data).replace(select_project_callback_prefix, '')
user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
msg, photo_id, name, desc = GetProjectData(project_id)
if msg != '':
await bot.send_message(a_CallbackQuery.from_user.id, msg, reply_markup = GetEditProjectKeyboardButtons(user_groups))
return
msg = project_open_message.replace('@proj_name', name).replace('@proj_desk', desc)
if photo_id == '0':
await bot.send_message(a_CallbackQuery.from_user.id, msg, reply_markup = GetEditProjectKeyboardButtons(user_groups))
else:
await bot.send_photo(a_CallbackQuery.from_user.id, photo_id, msg, reply_markup = GetEditProjectKeyboardButtons(user_groups))
# Создание нового проекта
async def ProjectCreateCancel(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
@ -406,10 +411,11 @@ def GetModuleButtons():
# Обработка кнопок
def RegisterHandlers(dp : Dispatcher):
# Список проектов
dp.register_message_handler(ProjectsOpen, text = projects_button_name)
dp.register_message_handler(ProjectsOpen, text = list_project_button_name)
dp.register_callback_query_handler(ShowProject, lambda x: x.data.startswith(select_project_callback_prefix))
dp.register_message_handler(simple_message.SimpleMessageTemplate(ProjectsOpen, GetEditProjectKeyboardButtons, GetAccess), text = projects_button_name)
global select_handler
select_handler = bd_item_view.SelectAndShowBDItemRegisterHandlers(dp, list_project_button_name, table_name, key_name, ShowProject, GetButtonNameAndKeyValueAndAccess, select_project_message, GetAccess, GetEditProjectKeyboardButtons)
# Добавление проекта
dp.register_message_handler(ProjectCreate, text = add_project_button_name)
dp.register_message_handler(ProjectPhotoSkip, text = projects_skip_button_name, state = FSMCreateProject.prjPhoto)

2
bot_modules/start.py

@ -43,7 +43,7 @@ async def StartMenu(a_Message):
user_name = str(a_Message.from_user.username)
profile.AddUser(user_id, user_name)
log.Info(f'Пользователь {user_id} {user_name} авторизовался в боте')
return start_message
return start_message, None
# ---------------------------------------------------------
# API

64
template/bd_item_view.py

@ -0,0 +1,64 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Простые информационные сообщения
from bot_sys import user_access, bot_bd, keyboard
from bot_modules import access, groups
from template import simple_message
from aiogram import types
def GetAllItemsTemplate(a_TableName):
def GetAllItems():
return bot_bd.SelectBDTemplate(a_TableName)()
return GetAllItems
def GetBDItemTemplate(a_TableName : str, a_KeyName : str):
def GetBDItem(a_KeyValue):
return bot_bd.SQLRequestToBD(f'SELECT * FROM {a_TableName} WHERE {a_KeyName} = ?', param = ([a_KeyValue]))
return GetBDItem
def GetBDItemsListKeyboardButtonsTemplate(a_TableName : str, a_Prefix : str, a_GetButtonNameAndKeyValueAndAccessFunc, access_mode = user_access.AccessMode.VIEW):
def GetBDItemsListKeyboardButtons(a_UserGroups):
items = GetAllItemsTemplate(a_TableName)()
items_button_list = []
for t in items:
bname, key_value, access = a_GetButtonNameAndKeyValueAndAccessFunc(t)
if not bname is None and user_access.CheckAccessString(access, a_UserGroups, access_mode):
items_button_list += [keyboard.Button(bname, key_value)]
return keyboard.MakeInlineKeyboard(items_button_list, a_Prefix)
return GetBDItemsListKeyboardButtons
'''
class TableListParam():
def __init__(self, a_TableName : str, a_KeyName : str, a_GetButtonNameAndKeyValueAndAccessFunc):
self.table_name = a_TableName
self.key_name = a_KeyName
self.get_bname_and_key_value_func = a_GetButtonNameAndKeyValueAndAccessFunc
'''
def SelectDBItemTemplate(a_TableName : str, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode = user_access.AccessMode.VIEW):
keyborad_func = GetBDItemsListKeyboardButtonsTemplate(a_TableName, a_Prefix, a_GetButtonNameAndKeyValueAndAccessFunc)
return simple_message.InfoMessageTemplate(a_StartMessage, keyborad_func, a_AccessFunc, access_mode)
def ShowBDItemTemplate(a_TableName, a_KeyName, a_WorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW):
async def ShowBDItem(a_CallbackQuery : types.CallbackQuery):
user_id = str(a_CallbackQuery.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
item_id = str(a_CallbackQuery.data).replace(a_Prefix, '')
item = GetBDItemTemplate(a_TableName, a_KeyName)(item_id)
if len(item) < 1:
msg = f'Элемент {item_id} не найден в таблице {a_TableName}'
log.Error(msg)
await bot.send_message(a_CallbackQuery.from_user.id, msg, reply_markup = a_ButtonFunc(user_groups))
return None, None
return await a_WorkFunc(a_CallbackQuery, item[0])
return simple_message.SimpleMessageTemplate(ShowBDItem, a_ButtonFunc, a_AccessFunc, access_mode)
def SelectAndShowBDItemRegisterHandlers(dp, a_RequestButtonName, a_TableName : str, a_KeyName, a_ShowItemWorkFunc, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_ButtonFunc, access_mode = user_access.AccessMode.VIEW):
a_Prefix = f'select_{a_TableName}_{a_KeyName}:'
sel_handler = SelectDBItemTemplate(a_TableName, a_GetButtonNameAndKeyValueAndAccessFunc, a_StartMessage, a_AccessFunc, a_Prefix, access_mode)
dp.register_message_handler(sel_handler, text = a_RequestButtonName)
dp.register_callback_query_handler(ShowBDItemTemplate(a_TableName, a_KeyName, a_ShowItemWorkFunc, a_Prefix, a_AccessFunc, a_ButtonFunc, access_mode), lambda x: x.data.startswith(a_Prefix))
return sel_handler

20
template/simple_message.py

@ -3,13 +3,16 @@
# Простые информационные сообщения
from bot_sys import user_access
from bot_sys import user_access, config
from bot_modules import access, groups
from aiogram import types
from aiogram import Bot
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode = types.ParseMode.HTML)
def InfoMessageTemplate(a_HelpMessage, a_GetButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW):
async def GetMessage(a_Message : types.message):
return a_HelpMessage
return a_HelpMessage, None
return SimpleMessageTemplate(GetMessage, a_GetButtonsFunc, a_AccessFunc, access_mode)
@ -18,9 +21,14 @@ def SimpleMessageTemplate(a_WorkFunc, a_GetButtonsFunc, a_AccessFunc, access_mod
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, access_mode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
return await bot.send_message(a_Message.from_user.id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
msg = await a_WorkFunc(a_Message)
if not msg is None:
await a_Message.answer(msg, reply_markup = a_GetButtonsFunc(user_groups))
msg, photo_id = await a_WorkFunc(a_Message)
if msg is None:
return
if photo_id is None or photo_id == 0 or photo_id == '0':
return await bot.send_message(a_Message.from_user.id, msg, reply_markup = a_GetButtonsFunc(user_groups))
await bot.send_photo(user_id, photo_id, msg, reply_markup = a_GetButtonsFunc(user_groups))
return SimpleMessage

Loading…
Cancel
Save