Browse Source

Шаблоны БД

test_bot
Alexei 2 years ago
parent
commit
8a581d4bf2
  1. 11
      bot_modules/access.py
  2. 73
      bot_modules/groups.py
  3. 14
      bot_modules/profile.py
  4. 15
      bot_modules/projects.py
  5. 65
      bot_sys/bot_bd.py

11
bot_modules/access.py

@ -15,12 +15,15 @@ bot = Bot(token=config.GetTelegramBotApiToken(), parse_mode=types.ParseMode.HTML
# ---------------------------------------------------------
# БД
init_bd_cmds = ["""CREATE TABLE IF NOT EXISTS module_access(
table_name = 'module_access'
module_name = 'access'
init_bd_cmds = [f"""CREATE TABLE IF NOT EXISTS {table_name}(
modName TEXT,
modAccess TEXT,
UNIQUE(modName)
);""",
"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('access', 'other=-');"
f"INSERT OR IGNORE INTO {table_name} (modName, modAccess) VALUES ('{module_name}', 'other=-');"
]
# ---------------------------------------------------------
@ -37,6 +40,8 @@ request_start_message = '''
Можете воспользоваться следующими шаблонами:
1. `SELECT * FROM users` - Все пользователи
2. `SELECT * FROM module_access` - Все права к модулям
3. `UPDATE module_access SET modAccess = 'NEWACCESS' WHERE modName = 'MODNAME'` - Задать новые права NEWACCESS для модуля MODNAME
'''
help_message = '''
@ -69,6 +74,8 @@ async def AccessStart(a_Message):
# ---------------------------------------------------------
# Работа с базой данных
def GetModAccessList():
return bot_db.SelectBDTemplate(table_name)()
# ---------------------------------------------------------
# API

73
bot_modules/groups.py

@ -113,7 +113,7 @@ async def RequestToBD(a_Message : types.message, state : FSMContext):
async with state.proxy() as prjData:
sql_request = a_Message.text
log.Success(f'Сделан запрос [{sql_request}] пользователем {a_Message.from_user.id}.')
result = SQLRequestToBD(sql_request)
result = bot_bd.SQLRequestToBDCommit(sql_request)
log.Success(f'Результат запроса [{sql_request}] от пользователя {a_Message.from_user.id} следующий [{result}].')
await state.finish()
await a_Message.answer(str(result), reply_markup = GetEditGroupKeyboardButtons(user_access))
@ -121,78 +121,11 @@ async def RequestToBD(a_Message : types.message, state : FSMContext):
# ---------------------------------------------------------
# Работа с базой данных групп
def SQLRequestToBD(a_Request : str):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
result = []
try:
cursor.execute(a_Request)
result = cursor.fetchall()
db.commit()
except sqlite3.Error as e:
result = "Ошибка sqlite3:" + str(e)
cursor.close()
db.close()
return result
def GetGroupIDForUser(a_UserID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
groups = cursor.execute('SELECT group_id FROM user_in_groups WHERE user_id = ?', (a_UserID)).fetchall()
cursor.close()
db.close()
return groups
return bot_bd.SQLRequestToBD1('SELECT group_id FROM user_in_groups WHERE user_id = ?', a_UserID)
def GetGroupNamesForUser(a_UserID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
groups = cursor.execute('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', (a_UserID)).fetchall()
cursor.close()
db.close()
print(groups)
return groups
def GetGroupList():
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
groups = cursor.execute('SELECT * FROM user_groups').fetchall()
cursor.close()
db.close()
return groups
def GetGroup(a_GroupID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
group = cursor.execute('SELECT * FROM user_groups WHERE groupID = ?', ([a_GroupID])).fetchall()
cursor.close()
db.close()
return group
def AddGroup(a_Name):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
cursor.execute('INSERT INTO user_groups(groupName) VALUES(?)', (a_prjName))
db.commit()
cursor.close()
db.close()
return
def EditGroup(a_GroupID, a_Name):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
cursor.execute('UPDATE user_groups SET groupName = ? WHERE groupID = ?', (a_prjPhoto, a_Name))
db.commit()
cursor.close()
db.close()
return
def DelGroup(a_GroupID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
cursor.execute('DELETE FROM user_groups WHERE groupID = ?', ([a_GroupID]))
db.commit()
db.close()
return
return bot_bd.SQLRequestToBD1('SELECT groupName FROM user_groups WHERE group_id=(SELECT group_id FROM user_in_groups WHERE user_id = ?)', a_UserID)
# ---------------------------------------------------------
# API

14
bot_modules/profile.py

@ -59,20 +59,12 @@ async def ProfileOpen(a_Message):
# Добавление пользователя, если он уже есть, то игнорируем
def AddUser(a_UserID, a_UserName):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
cursor.execute("INSERT OR IGNORE INTO users (user_id, userName) VALUES (?, ?);", (a_UserID, a_UserName));
db.commit()
cursor.close()
db.close()
bot_bd.SQLRequestToBD2Commit("INSERT OR IGNORE INTO users (user_id, userName) VALUES (?, ?);", a_UserID, a_UserName)
# Добавление пользователя, если он уже есть, то игнорируем
def GetUserInfo(a_UserID):
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
user_info = cursor.execute('SELECT * FROM users WHERE user_id = ?', ([a_UserID])).fetchall()
cursor.close()
db.close()
user_info = bot_bd.SQLRequestToBD1('SELECT * FROM users WHERE user_id = ?', [a_UserID])
print(user_info, str(user_info))
if len(user_info) != 0:
return user_info[0]
return None

15
bot_modules/projects.py

@ -26,15 +26,19 @@ class FSMEditProject(StatesGroup):
# ---------------------------------------------------------
# БД
init_bd_cmds = ['''CREATE TABLE IF NOT EXISTS projects(
table_name = 'projects'
module_name = 'projects'
init_bd_cmds = [f'''CREATE TABLE IF NOT EXISTS {table_name}(
projectPhoto TEXT,
projectName TEXT,
projectDesc TEXT,
projectID INTEGER PRIMARY KEY
)''',
"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('project', 'other=va');"
f"INSERT OR IGNORE INTO module_access (modName, modAccess) VALUES ('{module_name}', 'other=va');"
]
# ---------------------------------------------------------
# Сообщения
@ -322,12 +326,7 @@ async def prjDelete(a_CallbackQuery : types.CallbackQuery):
# Работа с базой данных проектов
def GetProjectList():
db = sqlite3.connect(bot_bd.GetBDFileName())
cursor = db.cursor()
projects = cursor.execute('SELECT * FROM projects').fetchall()
cursor.close()
db.close()
return projects
return bot_bd.SelectBDTemplate(table_name)()
def GetProject(a_ProjectID):
db = sqlite3.connect(bot_bd.GetBDFileName())

65
bot_sys/bot_bd.py

@ -2,6 +2,7 @@
# Общественное достояние 2023, Алексей Безбородов (Alexei Bezborodov) <AlexeiBv+mirocod_platform_bot@narod.ru>
import sqlite3
from bot_sys import log
# Работа с базой данных
@ -25,18 +26,54 @@ def BDExecute(a_Commands):
cursor.close()
db.close()
'''
# Таблица групп пользователей
cursor.execute("""CREATE TABLE IF NOT EXISTS group(
group_id INTEGER,
groupName TEXT,
UNIQUE(group_id)
);""")
# Таблица соответствия пользователей и групп пользователей
cursor.execute("""CREATE TABLE IF NOT EXISTS groups_users(
user_id INTEGER,
group_id INTEGER
);""")
'''
def SelectBDTemplate(a_TableName):
def SelectBD():
return SQLRequestToBD(f'SELECT * FROM {a_TableName}')
return SelectBD
def SQLRequestToBDCommit(a_Request : str):
return SQLRequestToBD1Commit(a_Request, None)
def SQLRequestToBD1Commit(a_Request : str, a_Param1):
return SQLRequestToBD2Commit(a_Request, a_Param1, None)
def SQLRequestToBD2Commit(a_Request : str, a_Param1, a_Param2):
return SQLRequestToBD3Common(a_Request, True, a_Param1, a_Param2, None)
def SQLRequestToBD3Commit(a_Request : str, a_Param1, a_Param2, a_Param3):
return SQLRequestToBD3Common(a_Request, True, a_Param1, a_Param2, a_Param3)
def SQLRequestToBD(a_Request : str):
return SQLRequestToBD1(a_Request, None)
def SQLRequestToBD1(a_Request : str, a_Param1):
return SQLRequestToBD2(a_Request, a_Param1, None)
def SQLRequestToBD2(a_Request : str, a_Param1, a_Param2):
return SQLRequestToBD3Common(a_Request, False, a_Param1, a_Param2, None)
def SQLRequestToBD3(a_Request : str, a_Param1, a_Param2, a_Param3):
return SQLRequestToBD3Common(a_Request, False, a_Param1, a_Param2, a_Param3)
def SQLRequestToBD3Common(a_Request : str, a_Commit : bool, a_Param1, a_Param2, a_Param3):
db = sqlite3.connect(GetBDFileName())
cursor = db.cursor()
result = []
try:
if not a_Param3 is None:
cursor.execute(a_Request, (a_Param1, a_Param3, a_Param3))
elif not a_Param2 is None:
cursor.execute(a_Request, (a_Param1, a_Param2))
elif not a_Param1 is None:
cursor.execute(a_Request, (a_Param1))
else:
cursor.execute(a_Request)
result = cursor.fetchall()
if a_Commit:
db.commit()
except sqlite3.Error as e:
log.Error(f'Ошибка при обработке запроса [{a_Request}]:{str(e)}')
result = "Ошибка sqlite3:" + str(e)
cursor.close()
db.close()
return result

Loading…
Cancel
Save