Browse Source

Шаблоны для простых сообщений и для запросов к БД

test_bot
Alexei 2 years ago
parent
commit
058d3a286c
  1. 32
      bot_modules/access.py
  2. 88
      bot_modules/groups.py
  3. 1
      bot_modules/projects.py
  4. 5
      bot_modules/start.py
  5. 2
      template/file_message.py
  6. 17
      template/simple_message.py
  7. 63
      template/sql_request.py

32
bot_modules/access.py

@ -5,16 +5,12 @@
from bot_sys import bot_bd, log, config, keyboard, user_access from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, groups from bot_modules import start, groups
from aiogram import Bot, types from template import simple_message, sql_request
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters.state import State, StatesGroup
import sqlite3
from aiogram.dispatcher import Dispatcher from aiogram.dispatcher import Dispatcher
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML)
class FSMRequestToBDAccess(StatesGroup): class FSMRequestToBDAccess(StatesGroup):
sqlRequest = State() sqlRequest = State()
@ -69,7 +65,7 @@ help_button_name = "📄 Информация по редактированию
def GetEditAccessKeyboardButtons(a_UserGroups): def GetEditAccessKeyboardButtons(a_UserGroups):
cur_buttons = [ cur_buttons = [
keyboard.ButtonWithAccess(sql_request_button_name, user_access.AccessMode.EDIT, GetAccess()), keyboard.ButtonWithAccess(sql_request_button_name, user_access.AccessMode.ACCEES_EDIT, GetAccess()),
keyboard.ButtonWithAccess(help_button_name, user_access.AccessMode.VIEW, GetAccess()) keyboard.ButtonWithAccess(help_button_name, user_access.AccessMode.VIEW, GetAccess())
] ]
mods = [start] mods = [start]
@ -78,19 +74,15 @@ def GetEditAccessKeyboardButtons(a_UserGroups):
# --------------------------------------------------------- # ---------------------------------------------------------
# Обработка сообщений # Обработка сообщений
# Приветствие
async def AccessStart(a_Message):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(GetAccess(), user_groups, user_access.AccessMode.VIEW):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = GetEditAccessKeyboardButtons(user_groups))
await bot.send_message(user_id, access_start_message, reply_markup = GetEditAccessKeyboardButtons(user_groups))
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с базой данных # Работа с базой данных
def GetModuleAccessList(): def GetModuleAccessList():
return bot_bd.SelectBDTemplate(table_name)() return bot_bd.SelectBDTemplate(table_name)()
# ---------------------------------------------------------
# API
def GetAccessForModule(a_ModuleName): def GetAccessForModule(a_ModuleName):
alist = GetModuleAccessList() alist = GetModuleAccessList()
for i in alist: for i in alist:
@ -98,9 +90,6 @@ def GetAccessForModule(a_ModuleName):
return i[1] return i[1]
return '' return ''
# ---------------------------------------------------------
# API
# Инициализация БД # Инициализация БД
def GetInitBDCommands(): def GetInitBDCommands():
return init_bd_cmds return init_bd_cmds
@ -114,10 +103,7 @@ def GetModuleButtons():
# Обработка кнопок # Обработка кнопок
def RegisterHandlers(dp : Dispatcher): def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(AccessStart, text = access_button_name) dp.register_message_handler(simple_message.InfoMessageTemplate(access_start_message, GetEditAccessKeyboardButtons, GetAccess), text = access_button_name)
dp.register_message_handler(simple_message.InfoMessageTemplate(help_message, GetEditAccessKeyboardButtons, GetAccess), text = help_button_name)
dp.register_message_handler(groups.RequestToBDTemplate(request_start_message, GetAccess, FSMRequestToBDAccess), text = sql_request_button_name)
dp.register_message_handler(groups.RequestToBDCancelTemplate(GetEditAccessKeyboardButtons, GetAccess), text = groups.canсel_button_name, state = FSMRequestToBDAccess.sqlRequest)
dp.register_message_handler(groups.RequestToBDFinishTemplate(GetEditAccessKeyboardButtons, GetAccess), state = FSMRequestToBDAccess.sqlRequest)
dp.register_message_handler(groups.HelpTemplate(help_message, GetEditAccessKeyboardButtons, GetAccess), text = help_button_name) sql_request.RequestToBDRegisterHandlers(dp, sql_request_button_name, request_start_message, FSMRequestToBDAccess, GetEditAccessKeyboardButtons, user_access.AccessMode.ACCEES_EDIT, GetAccess)

88
bot_modules/groups.py

@ -5,16 +5,12 @@
from bot_sys import bot_bd, log, config, keyboard, user_access from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, access from bot_modules import start, access
from aiogram import Bot, types from template import simple_message, sql_request
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters.state import State, StatesGroup
import sqlite3
from aiogram.dispatcher import Dispatcher from aiogram.dispatcher import Dispatcher
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML)
class FSMRequestToBD(StatesGroup): class FSMRequestToBD(StatesGroup):
sqlRequest = State() sqlRequest = State()
@ -69,7 +65,6 @@ request_cancel_message = '''
user_group_button_name = "▦ Группы пользователей" user_group_button_name = "▦ Группы пользователей"
sql_request_button_name = "⛃ Запрос к БД для редактирования групп" sql_request_button_name = "⛃ Запрос к БД для редактирования групп"
help_button_name = "📄 Информация по группам" help_button_name = "📄 Информация по группам"
canсel_button_name = "🚫 Отменить"
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с кнопками # Работа с кнопками
@ -82,73 +77,9 @@ def GetEditGroupKeyboardButtons(a_UserGroups):
mods = [start] mods = [start]
return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups) return keyboard.MakeKeyboard(keyboard.GetButtons(mods) + cur_buttons, a_UserGroups)
def GetCancelKeyboardButtons(a_UserGroups, a_AccessFunc):
cur_buttons = [
keyboard.ButtonWithAccess(canсel_button_name, user_access.AccessMode.VIEW, a_AccessFunc())
]
return keyboard.MakeKeyboard(cur_buttons, a_UserGroups)
# --------------------------------------------------------- # ---------------------------------------------------------
# Обработка сообщений # Обработка сообщений
# Приветствие
async def GroupStart(a_Message):
user_id = str(a_Message.from_user.id)
user_groups = GetUserGroupData(user_id)
if not user_access.CheckAccessString(GetAccess(), user_groups, user_access.AccessMode.VIEW):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = GetEditGroupKeyboardButtons(user_groups))
await bot.send_message(user_id, group_start_message, reply_markup = GetEditGroupKeyboardButtons(user_groups))
def RequestToBDCancelTemplate(a_GetButtonsFunc, a_AccessFunc):
async def RequestToBDCancel(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, user_access.AccessMode.VIEW):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
await state.finish()
await a_Message.answer(request_cancel_message, reply_markup = a_GetButtonsFunc(user_groups))
return RequestToBDCancel
def HelpTemplate(a_HelpMessage, a_GetButtonsFunc, a_AccessFunc):
async def Help(a_Message : types.message):
user_id = str(a_Message.from_user.id)
user_groups = GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, user_access.AccessMode.VIEW):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
await a_Message.answer(a_HelpMessage, reply_markup = a_GetButtonsFunc(user_groups)) #, parse_mode='Markdown')
return Help
def RequestToBDTemplate(a_StartMessage, a_AccessFunc, a_FSM):
async def RequestToBDStart(a_Message : types.message):
user_id = str(a_Message.from_user.id)
user_groups = GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, user_access.AccessMode.EDIT):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = GetCancelKeyboardButtons(user_groups, a_AccessFunc))
await a_FSM.sqlRequest.set()
await a_Message.answer(a_StartMessage, reply_markup = GetCancelKeyboardButtons(user_groups, a_AccessFunc), parse_mode='Markdown')
return RequestToBDStart
def RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc):
async def RequestToBDFinish(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, user_access.AccessMode.EDIT):
return await bot.send_message(user_id, access.access_denied_message, reply_markup = GetEditGroupKeyboardButtons(user_groups))
result = ''
async with state.proxy() as prjData:
sql_request = a_Message.text
log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.')
result, error = bot_bd.SQLRequestToBD(sql_request, commit = True, return_error = True)
if not error is None:
log.Error(f'Ошибка при выполнении запроса [{sql_request}] от пользователя {a_Message.from_user.id} ответ следующий [{str(error)}].')
result = str(error)
else:
log.Success(f'Результат запроса [{sql_request}] от пользователя {a_Message.from_user.id} следующий [{result}].')
await state.finish()
await a_Message.answer(str(result), reply_markup = a_GetButtonsFunc(user_groups))
return RequestToBDFinish
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с базой данных групп # Работа с базой данных групп
@ -158,18 +89,17 @@ def GetGroupIDForUser(a_UserID):
def GetGroupNamesForUser(a_UserID): def GetGroupNamesForUser(a_UserID):
return bot_bd.SQLRequestToBD('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', param = [a_UserID]) return bot_bd.SQLRequestToBD('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', param = [a_UserID])
# ---------------------------------------------------------
# API
def GetUserGroupData(a_UserID): def GetUserGroupData(a_UserID):
r = GetGroupNamesForUser(a_UserID) r = GetGroupNamesForUser(a_UserID)
groups = [] groups = []
for i in r: for i in r:
if len(i) > 0: if len(i) > 0:
groups += [i[0]] groups += [i[0]]
print(groups)
return user_access.UserGroups(a_UserID, groups) return user_access.UserGroups(a_UserID, groups)
# ---------------------------------------------------------
# API
# Инициализация БД # Инициализация БД
def GetInitBDCommands(): def GetInitBDCommands():
return init_bd_cmds return init_bd_cmds
@ -183,9 +113,7 @@ def GetModuleButtons():
# Обработка кнопок # Обработка кнопок
def RegisterHandlers(dp : Dispatcher): def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(GroupStart, text = user_group_button_name) dp.register_message_handler(simple_message.InfoMessageTemplate(group_start_message, GetEditGroupKeyboardButtons, GetAccess), text = user_group_button_name)
dp.register_message_handler(HelpTemplate(help_message, GetEditGroupKeyboardButtons, GetAccess), text = help_button_name) dp.register_message_handler(simple_message.InfoMessageTemplate(help_message, GetEditGroupKeyboardButtons, GetAccess), text = help_button_name)
dp.register_message_handler(RequestToBDTemplate(request_start_message, GetAccess, FSMRequestToBD), text = sql_request_button_name) sql_request.RequestToBDRegisterHandlers(dp, sql_request_button_name, request_start_message, FSMRequestToBD, GetEditGroupKeyboardButtons, user_access.AccessMode.EDIT, GetAccess)
dp.register_message_handler(RequestToBDCancelTemplate(GetEditGroupKeyboardButtons, GetAccess), text = canсel_button_name, state = FSMRequestToBD.sqlRequest)
dp.register_message_handler(RequestToBDFinishTemplate(GetEditGroupKeyboardButtons, GetAccess), state = FSMRequestToBD.sqlRequest)

1
bot_modules/projects.py

@ -6,6 +6,7 @@
from bot_sys import bot_bd, log, config, keyboard, user_access from bot_sys import bot_bd, log, config, keyboard, user_access
from bot_modules import start, access, groups from bot_modules import start, access, groups
from aiogram import Bot, types from aiogram import Bot, types
from aiogram.dispatcher import FSMContext from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.dispatcher import Dispatcher from aiogram.dispatcher import Dispatcher

5
bot_modules/start.py

@ -20,10 +20,9 @@ f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name
# Сообщения # Сообщения
start_message = ''' start_message = '''
<b>👋 | Добро пожаловать!</b> <b>Добро пожаловать!</b>
<b>Приятного пользования!</b> Выберите возмжные действия на кнопах ниже '''
'''
start_menu_button_name = "≣ Главное меню" start_menu_button_name = "≣ Главное меню"

2
template/file_message.py

@ -7,8 +7,6 @@ from bot_sys import log, config, user_access
from bot_modules import access, groups from bot_modules import access, groups
from aiogram import Bot, types from aiogram import Bot, types
import sqlite3
from aiogram.dispatcher import Dispatcher from aiogram.dispatcher import Dispatcher
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML) bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML)

17
template/simple_message.py

@ -0,0 +1,17 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Простые информационные сообщения
from bot_sys import user_access
from bot_modules import access, groups
from aiogram import types
def InfoMessageTemplate(a_HelpMessage, a_GetButtonsFunc, a_AccessFunc, access_mode = user_access.AccessMode.VIEW):
async def Help(a_Message : types.message):
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))
await a_Message.answer(a_HelpMessage, reply_markup = a_GetButtonsFunc(user_groups))
return Help

63
template/sql_request.py

@ -0,0 +1,63 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Сообщения для работы с sql запросами
from bot_sys import bot_bd, log, config, user_access, keyboard
from bot_modules import access, groups
from aiogram import types
from aiogram.dispatcher import FSMContext
canсel_button_name = "🚫 Отменить"
def GetCancelKeyboardButtons(a_UserGroups, a_AccessFunc, a_AccessMode):
cur_buttons = [
keyboard.ButtonWithAccess(canсel_button_name, a_AccessMode, a_AccessFunc())
]
return keyboard.MakeKeyboard(cur_buttons, a_UserGroups)
def RequestToBDCancelTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
async def RequestToBDCancel(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
await state.finish()
await a_Message.answer(request_cancel_message, reply_markup = a_GetButtonsFunc(user_groups))
return RequestToBDCancel
def RequestToBDTemplate(a_StartMessage, a_AccessFunc, a_FSM, a_AccessMode):
async def RequestToBDStart(a_Message : types.message):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = GetCancelKeyboardButtons(user_groups, a_AccessFunc, a_AccessMode))
await a_FSM.sqlRequest.set()
await a_Message.answer(a_StartMessage, reply_markup = GetCancelKeyboardButtons(user_groups, a_AccessFunc, a_AccessMode), parse_mode='Markdown')
return RequestToBDStart
def RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode):
async def RequestToBDFinish(a_Message : types.message, state : FSMContext):
user_id = str(a_Message.from_user.id)
user_groups = groups.GetUserGroupData(user_id)
if not user_access.CheckAccessString(a_AccessFunc(), user_groups, a_AccessMode):
return await a_Message.answer(access.access_denied_message, reply_markup = a_GetButtonsFunc(user_groups))
result = ''
async with state.proxy() as prjData:
sql_request = a_Message.text
log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.')
result, error = bot_bd.SQLRequestToBD(sql_request, commit = True, return_error = True)
if not error is None:
log.Error(f'Ошибка при выполнении запроса [{sql_request}] от пользователя {a_Message.from_user.id} ответ следующий [{str(error)}].')
result = str(error)
else:
log.Success(f'Результат запроса [{sql_request}] от пользователя {a_Message.from_user.id} следующий [{result}].')
await state.finish()
await a_Message.answer(str(result), reply_markup = a_GetButtonsFunc(user_groups))
return RequestToBDFinish
def RequestToBDRegisterHandlers(dp, a_RequestButtonName, a_RequestStartMessage, a_FSM, a_GetButtonsFunc, a_AccessMode, a_AccessFunc):
dp.register_message_handler(RequestToBDTemplate(a_RequestStartMessage, a_AccessFunc, a_FSM, a_AccessMode), text = a_RequestButtonName)
dp.register_message_handler(RequestToBDCancelTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), text = canсel_button_name, state = a_FSM.sqlRequest)
dp.register_message_handler(RequestToBDFinishTemplate(a_GetButtonsFunc, a_AccessFunc, a_AccessMode), state = a_FSM.sqlRequest)
Loading…
Cancel
Save