Browse Source

Проекты без возможности добавления и удаления

test_bot
Alexei 2 years ago
parent
commit
d99a016a2b
  1. 12
      bot_modules/profile.py
  2. 114
      bot_modules/projects.py
  3. 10
      bot_modules/start.py
  4. 22
      bot_sys/keyboard.py
  5. 4
      main.py

12
bot_modules/profile.py

@ -36,9 +36,9 @@ user_profile_button_name = "📰 Профиль"
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с кнопками # Работа с кнопками
def GetProfileKeyboardButtons(a_UserAccess): def GetStartKeyboardButtons(a_UserAccess):
start_button_names = start.GetButtonNames(a_UserAccess) mods = [start]
return keyboard.MakeKeyboard([start_button_names]) return keyboard.MakeKeyboardForMods(mods, a_UserAccess)
# --------------------------------------------------------- # ---------------------------------------------------------
# Обработка сообщений # Обработка сообщений
@ -50,7 +50,7 @@ async def ProfileOpen(a_Message):
msg = profile_message msg = profile_message
if not user_info is None: if not user_info is None:
msg = msg.replace('@user_id', str(user_info[0])).replace('@user_name', str(user_info[1])) msg = msg.replace('@user_id', str(user_info[0])).replace('@user_name', str(user_info[1]))
await bot.send_message(user_id, msg, reply_markup = GetProfileKeyboardButtons(None)) await bot.send_message(user_id, msg, reply_markup = GetStartKeyboardButtons(None))
# --------------------------------------------------------- # ---------------------------------------------------------
# Работа с базой данных пользователей # Работа с базой данных пользователей
@ -78,13 +78,13 @@ def GetUserInfo(a_UserID):
# --------------------------------------------------------- # ---------------------------------------------------------
# API # API
# Доступные кнопки # Инициализация БД
def GetInitBDCommands(): def GetInitBDCommands():
return [init_bd_cmd] return [init_bd_cmd]
# Доступные кнопки # Доступные кнопки
def GetButtonNames(a_UserAccess): def GetButtonNames(a_UserAccess):
return user_profile_button_name return [user_profile_button_name]
# Обработка кнопок # Обработка кнопок
def RegisterHandlers(dp : Dispatcher): def RegisterHandlers(dp : Dispatcher):

114
bot_modules/projects.py

@ -0,0 +1,114 @@
# -*- coding: utf8 -*-
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
# Проекты
from bot_sys import bot_bd, log, config, keyboard
from bot_modules import start
from aiogram import Bot, types
import sqlite3
from aiogram.dispatcher import Dispatcher
bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML)
# ---------------------------------------------------------
# БД
init_bd_cmd = '''CREATE TABLE IF NOT EXISTS projects(
projectPhoto TEXT,
projectName TEXT,
projectDesc TEXT,
parentID INTEGER,
projectID INTEGER PRIMARY KEY
)'''
# ---------------------------------------------------------
# Сообщения
select_project_message = '''
<b>🛒 Проекты</b>
Пожалуйста, выберите проект:
'''
error_find_proj_message = '''
Ошибка, проект с ID @project_id не найден
'''
project_open_message = '''
<b>Проект: @proj_name</b>
@proj_desk
'''
projects_button_name = "📰 Проекты"
# Префиксы
select_project_callback_prefix = 'project:'
# ---------------------------------------------------------
# Работа с кнопками
def GetStartKeyboardButtons(a_UserAccess):
mods = [start]
return keyboard.MakeKeyboardForMods(mods, a_UserAccess)
# ---------------------------------------------------------
# Обработка сообщений
# Отображение всех проектов без родителя
async def ProjectsOpen(a_Message):
projects = GetProjectList(0)
projects_button_list = []
for t in projects:
b = keyboard.Button(str(t[1]), t[4])
await bot.send_message(a_Message.from_user.id, select_project_message, reply_markup=keyboard.MakeInlineKeyboard(projects_button_list, select_project_callback_prefix))
async def ShowProject(a_CallbackQuery : types.CallbackQuery):
project_id = str(a_CallbackQuery.data).replace(select_project_callback_prefix, '')
project = GetProject(project_id)
if len(project) != 1:
log.Error(f'Проект не найден {project_id}')
msg = Ошибка.replace('@project_id', project_id)
await bot.send_message(a_CallbackQuery.from_user.id, msg, reply_markup=keyboard.MakeKeyboardForMods([start]))
return
p = project[0]
msg = project_open_message.replace('@proj_name', p[1]).replace('@proj_desk', p[2])
await bot.send_photo(a_CallbackQuery.from_user.id, p[0], msg, reply_markup=keyboard.MakeKeyboardForMods([start]))
# ---------------------------------------------------------
# Работа с базой данных пользователей
def GetProjectList(a_ParentID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
projects = cursor.execute('SELECT * FROM projects where parentID = ?', ([a_ParentID])).fetchall()
cursor.close()
db.close()
return projects
def GetProject(a_ProjectID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
project = cursor.execute('SELECT * FROM categories WHERE catID = ?', ([catID])).fetchall()
cursor.close()
db.close()
return project
# ---------------------------------------------------------
# API
# Инициализация БД
def GetInitBDCommands():
return [init_bd_cmd]
# Доступные кнопки
def GetButtonNames(a_UserAccess):
return [projects_button_name]
# Обработка кнопок
def RegisterHandlers(dp : Dispatcher):
dp.register_message_handler(ProjectsOpen, text = projects_button_name)
dp.register_callback_query_handler(ShowProject, lambda x: x.data.startswith(select_project_callback_prefix))

10
bot_modules/start.py

@ -4,7 +4,7 @@
# Стартовое меню # Стартовое меню
from bot_sys import log, config, keyboard from bot_sys import log, config, keyboard
from bot_modules import profile from bot_modules import profile, projects
from aiogram.dispatcher import Dispatcher from aiogram.dispatcher import Dispatcher
@ -23,8 +23,8 @@ start_menu_button_name = "☰ Главное меню"
# Работа с кнопками # Работа с кнопками
def GetStartKeyboardButtons(a_UserAccess): def GetStartKeyboardButtons(a_UserAccess):
profile_button_names = profile.GetButtonNames(a_UserAccess) mods = [profile, projects]
return keyboard.MakeKeyboard([profile_button_names]) return keyboard.MakeKeyboardForMods(mods, a_UserAccess)
# --------------------------------------------------------- # ---------------------------------------------------------
# Обработка сообщений # Обработка сообщений
@ -40,13 +40,13 @@ async def StartMenu(a_Message):
# --------------------------------------------------------- # ---------------------------------------------------------
# API # API
# Доступные кнопки # Инициализация БД
def GetInitBDCommands(): def GetInitBDCommands():
return None return None
# Имена доступных кнопок # Имена доступных кнопок
def GetButtonNames(a_UserAccess): def GetButtonNames(a_UserAccess):
return start_menu_button_name return [start_menu_button_name]
# Обработка кнопок # Обработка кнопок
def RegisterHandlers(dp : Dispatcher): def RegisterHandlers(dp : Dispatcher):

22
bot_sys/keyboard.py

@ -6,6 +6,14 @@
from aiogram import types, Bot, Dispatcher from aiogram import types, Bot, Dispatcher
from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton from aiogram.types import ReplyKeyboardRemove, ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
def GetButtons(a_ModList, a_UserAccess):
names = []
for m in a_ModList:
n = m.GetButtonNames(a_UserAccess)
if not n is None or len(n) != 0:
names += n
return names
def MakeKeyboard(a_ButtonList): def MakeKeyboard(a_ButtonList):
key = types.ReplyKeyboardMarkup(resize_keyboard = True) key = types.ReplyKeyboardMarkup(resize_keyboard = True)
for b in a_ButtonList: for b in a_ButtonList:
@ -13,3 +21,17 @@ def MakeKeyboard(a_ButtonList):
key.add(k) key.add(k)
return key return key
def MakeKeyboardForMods(a_ModList, a_UserAccess):
names = GetButtons(a_ModList, a_UserAccess)
return MakeKeyboard(names)
class Button:
def __init__(self, a_Label, a_CallBackData):
self.label = a_Label
self.callback_data = a_CallBackData
def MakeInlineKeyboard(a_ButtonList, a_CallBackPrefix):
inline_keyboard = InlineKeyboardMarkup(resize_keyboard=True, row_width=2)
for b in a_ButtonList:
inline_keyboard.insert(types.InlineKeyboardButton(text=b.label, callback_data=f'{a_CallBackPrefix}{b.callback_data}'))

4
main.py

@ -10,13 +10,13 @@ from aiogram.dispatcher import Dispatcher
from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.contrib.fsm_storage.memory import MemoryStorage
import sqlite3 import sqlite3
from bot_sys import config, log, bot_bd from bot_sys import config, log, bot_bd
from bot_modules import profile, start from bot_modules import profile, start, projects
storage = MemoryStorage() 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) dp = Dispatcher(bot, storage = storage)
mods = [profile, start] mods = [profile, start, projects]
init_bd_cmd = [] init_bd_cmd = []
for m in mods: for m in mods:

Loading…
Cancel
Save