mirror of
https://github.com/djimboy/djimbo_template_aio3.git
synced 2026-07-25 09:44:29 +00:00
Update
This commit is contained in:
+4
-3
@@ -1,5 +1,4 @@
|
||||
# supervisorctl
|
||||
|
||||
[program:dj_bot]
|
||||
directory=/root/djimbo_template/
|
||||
command=python3.9 main.py
|
||||
@@ -7,5 +6,7 @@ command=python3.9 main.py
|
||||
autostart=True
|
||||
autorestart=True
|
||||
|
||||
stderr_logfile=/root/djimbo_template/tgbot/data/sv_log_err.log
|
||||
stdout_logfile=/root/djimbo_template/tgbot/data/sv_log_out.log
|
||||
stderr_logfile=/root/autoshopDjimbo/tgbot/data/sv_log_err.log
|
||||
; stderr_logfile_maxbytes=10MB
|
||||
stdout_logfile=/root/autoshopDjimbo/tgbot/data/sv_log_out.log
|
||||
; stdout_logfile_maxbytes=10MB
|
||||
@@ -7,10 +7,10 @@ import colorama
|
||||
from aiogram import Bot, Dispatcher
|
||||
|
||||
from tgbot.data.config import BOT_TOKEN, scheduler, get_admins
|
||||
from tgbot.database.db_helper import create_dbx
|
||||
from tgbot.middlewares import register_all_middlwares
|
||||
from tgbot.routers import register_all_routers
|
||||
from tgbot.services.api_session import RequestSession
|
||||
from tgbot.services.api_sqlite import create_dbx
|
||||
from tgbot.services.api_session import AsyncRequestSession
|
||||
from tgbot.utils.misc.bot_commands import set_commands
|
||||
from tgbot.utils.misc.bot_logging import bot_logger
|
||||
from tgbot.utils.misc_functions import autobackup_admin, startup_notify
|
||||
@@ -28,7 +28,7 @@ async def scheduler_start(bot):
|
||||
async def main():
|
||||
scheduler.start() # Запуск Шедулера
|
||||
dp = Dispatcher() # Образ Диспетчера
|
||||
rSession = RequestSession() # Пул асинхронной сессии запросов
|
||||
arSession = AsyncRequestSession() # Пул асинхронной сессии запросов
|
||||
bot = Bot(token=BOT_TOKEN, parse_mode="HTML") # Образ Бота
|
||||
|
||||
register_all_middlwares(dp) # Регистрация всех мидлварей
|
||||
@@ -52,10 +52,10 @@ async def main():
|
||||
await dp.start_polling(
|
||||
bot,
|
||||
allowed_updates=dp.resolve_used_update_types(),
|
||||
rSession=rSession,
|
||||
arSession=arSession,
|
||||
)
|
||||
finally:
|
||||
await rSession.close()
|
||||
await arSession.close()
|
||||
await bot.session.close()
|
||||
|
||||
|
||||
|
||||
+5
-3
@@ -1,8 +1,10 @@
|
||||
APScheduler~=3.9.1
|
||||
aiogram~=3.0.0
|
||||
aiogram~=3.2.0
|
||||
colorlog~=6.7.0
|
||||
pytz~=2022.6
|
||||
typing~=3.7.4.3
|
||||
aiohttp~=3.8.5
|
||||
aiohttp~=3.9.1
|
||||
cachetools~=4.2.4
|
||||
colorama~=0.4.5
|
||||
colorama~=0.4.5
|
||||
aiofiles~=23.2.1
|
||||
pydantic~=2.5.2
|
||||
@@ -0,0 +1,88 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import sqlite3
|
||||
|
||||
from tgbot.data.config import PATH_DATABASE
|
||||
from tgbot.utils.const_functions import ded
|
||||
|
||||
|
||||
# Преобразование полученного списка в словарь
|
||||
def dict_factory(cursor, row) -> dict:
|
||||
save_dict = {}
|
||||
|
||||
for idx, col in enumerate(cursor.description):
|
||||
save_dict[col[0]] = row[idx]
|
||||
|
||||
return save_dict
|
||||
|
||||
|
||||
# Форматирование запроса без аргументов
|
||||
def update_format(sql, parameters: dict) -> tuple[str, list]:
|
||||
values = ", ".join([
|
||||
f"{item} = ?" for item in parameters
|
||||
])
|
||||
sql += f" {values}"
|
||||
|
||||
return sql, list(parameters.values())
|
||||
|
||||
|
||||
# Форматирование запроса с аргументами
|
||||
def update_format_where(sql, parameters: dict) -> tuple[str, list]:
|
||||
sql += " WHERE "
|
||||
|
||||
sql += " AND ".join([
|
||||
f"{item} = ?" for item in parameters
|
||||
])
|
||||
|
||||
return sql, list(parameters.values())
|
||||
|
||||
|
||||
################################################################################
|
||||
# Создание всех таблиц для БД
|
||||
def create_dbx():
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
|
||||
############################################################
|
||||
# Создание таблицы с хранением - пользователей
|
||||
if len(con.execute("PRAGMA table_info(storage_users)").fetchall()) == 7:
|
||||
print("DB was found(1/2)")
|
||||
else:
|
||||
con.execute(
|
||||
ded(f"""
|
||||
CREATE TABLE storage_users(
|
||||
increment INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER,
|
||||
user_login TEXT,
|
||||
user_name TEXT,
|
||||
user_surname TEXT,
|
||||
user_fullname TEXT,
|
||||
user_unix INTEGER
|
||||
)
|
||||
""")
|
||||
)
|
||||
print("DB was not found(1/2) | Creating...")
|
||||
|
||||
# Создание таблицы с хранением - настроек
|
||||
if len(con.execute("PRAGMA table_info(storage_settings)").fetchall()) == 1:
|
||||
print("DB was found(2/2)")
|
||||
else:
|
||||
con.execute(
|
||||
ded(f"""
|
||||
CREATE TABLE storage_settings(
|
||||
status_work TEXT
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
con.execute(
|
||||
ded(f"""
|
||||
INSERT INTO storage_settings(
|
||||
status_work
|
||||
)
|
||||
VALUES (?)
|
||||
"""),
|
||||
[
|
||||
'True',
|
||||
]
|
||||
)
|
||||
print("DB was not found(2/2) | Creating...")
|
||||
@@ -0,0 +1,36 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import sqlite3
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from tgbot.data.config import PATH_DATABASE
|
||||
from tgbot.database.db_helper import dict_factory, update_format
|
||||
|
||||
|
||||
# Модель таблицы
|
||||
class SettingsModel(BaseModel):
|
||||
status_work: str
|
||||
|
||||
|
||||
# Работа с настройками
|
||||
class Settingsx:
|
||||
storage_name = "storage_settings"
|
||||
|
||||
# Получение записи
|
||||
@staticmethod
|
||||
def get() -> SettingsModel:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"SELECT * FROM {Settingsx.storage_name}"
|
||||
|
||||
return SettingsModel(**con.execute(sql).fetchone())
|
||||
|
||||
# Редактирование записи
|
||||
@staticmethod
|
||||
def update(**kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"UPDATE {Settingsx.storage_name} SET"
|
||||
sql, parameters = update_format(sql, kwargs)
|
||||
|
||||
con.execute(sql, parameters)
|
||||
@@ -0,0 +1,133 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import sqlite3
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from tgbot.data.config import PATH_DATABASE
|
||||
from tgbot.database.db_helper import dict_factory, update_format_where, update_format
|
||||
from tgbot.utils.const_functions import get_unix, ded
|
||||
|
||||
|
||||
# Модель таблицы
|
||||
class UserModel(BaseModel):
|
||||
increment: int
|
||||
user_id: int
|
||||
user_login: str
|
||||
user_name: str
|
||||
user_surname: str
|
||||
user_fullname: str
|
||||
user_unix: int
|
||||
|
||||
|
||||
# Работа с юзером
|
||||
class Userx:
|
||||
storage_name = "storage_users"
|
||||
|
||||
# Добавление записи
|
||||
@staticmethod
|
||||
def add(
|
||||
user_id: int,
|
||||
user_login: str,
|
||||
user_name: str,
|
||||
user_surname: str,
|
||||
user_fullname: str,
|
||||
):
|
||||
user_unix = get_unix()
|
||||
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
|
||||
con.execute(
|
||||
ded(f"""
|
||||
INSERT INTO {Userx.storage_name} (
|
||||
user_id,
|
||||
user_login,
|
||||
user_name,
|
||||
user_surname,
|
||||
user_fullname,
|
||||
user_unix
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
"""),
|
||||
[
|
||||
user_id,
|
||||
user_login,
|
||||
user_name,
|
||||
user_surname,
|
||||
user_fullname,
|
||||
user_unix,
|
||||
],
|
||||
)
|
||||
|
||||
# Получение записи
|
||||
@staticmethod
|
||||
def get(**kwargs) -> UserModel:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"SELECT * FROM {Userx.storage_name}"
|
||||
sql, parameters = update_format_where(sql, kwargs)
|
||||
|
||||
response = con.execute(sql, parameters).fetchone()
|
||||
|
||||
if response is not None:
|
||||
response = UserModel(**response)
|
||||
|
||||
return response
|
||||
|
||||
# Получение записей
|
||||
@staticmethod
|
||||
def gets(**kwargs) -> list[UserModel]:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"SELECT * FROM {Userx.storage_name}"
|
||||
sql, parameters = update_format_where(sql, kwargs)
|
||||
|
||||
response = con.execute(sql, parameters).fetchall()
|
||||
|
||||
if len(response) >= 1:
|
||||
response = [UserModel(**cache_object) for cache_object in response]
|
||||
|
||||
return response
|
||||
|
||||
# Получение всех записей
|
||||
@staticmethod
|
||||
def get_all() -> list[UserModel]:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"SELECT * FROM {Userx.storage_name}"
|
||||
|
||||
response = con.execute(sql).fetchall()
|
||||
|
||||
if len(response) >= 1:
|
||||
response = [UserModel(**cache_object) for cache_object in response]
|
||||
|
||||
return response
|
||||
|
||||
# Редактирование записи
|
||||
@staticmethod
|
||||
def update(user_id, **kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"UPDATE {Userx.storage_name} SET"
|
||||
sql, parameters = update_format(sql, kwargs)
|
||||
parameters.append(user_id)
|
||||
|
||||
con.execute(sql + "WHERE user_id = ?", parameters)
|
||||
|
||||
# Удаление записи
|
||||
@staticmethod
|
||||
def delete(**kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"DELETE FROM {Userx.storage_name}"
|
||||
sql, parameters = update_format_where(sql, kwargs)
|
||||
|
||||
con.execute(sql, parameters)
|
||||
|
||||
# Очистка всех записей
|
||||
@staticmethod
|
||||
def clear():
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"DELETE FROM {Userx.storage_name}"
|
||||
|
||||
con.execute(sql)
|
||||
@@ -1,8 +1,8 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
from aiogram import Dispatcher
|
||||
|
||||
from tgbot.middlewares.exists_user import ExistsUserMiddleware
|
||||
from tgbot.middlewares.throttling import ThrottlingMiddleware
|
||||
from tgbot.middlewares.middleware_user import ExistsUserMiddleware
|
||||
from tgbot.middlewares.middleware_throttling import ThrottlingMiddleware
|
||||
|
||||
|
||||
# Регистрация всех миддлварей
|
||||
|
||||
@@ -21,6 +21,9 @@ class ThrottlingMiddleware(BaseMiddleware):
|
||||
if get_flag(data, "rate") is not None:
|
||||
self.default_rate = get_flag(data, "rate")
|
||||
|
||||
if self.default_rate == 0:
|
||||
return await handler(event, data)
|
||||
|
||||
if this_user.id not in self.users:
|
||||
self.users[this_user.id] = {
|
||||
'last_throttled': int(time.time()),
|
||||
@@ -1,7 +1,7 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
from aiogram import BaseMiddleware
|
||||
|
||||
from tgbot.services.api_sqlite import get_userx, add_userx, update_userx
|
||||
from tgbot.database.db_users import Userx
|
||||
from tgbot.utils.const_functions import clear_html
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ class ExistsUserMiddleware(BaseMiddleware):
|
||||
this_user = data.get("event_from_user")
|
||||
|
||||
if not this_user.is_bot:
|
||||
get_user = get_userx(user_id=this_user.id)
|
||||
get_user = Userx.get(user_id=this_user.id)
|
||||
|
||||
user_id = this_user.id
|
||||
user_login = this_user.username
|
||||
@@ -29,20 +29,20 @@ class ExistsUserMiddleware(BaseMiddleware):
|
||||
if len(user_surname) >= 1: user_fullname += f" {user_surname}"
|
||||
|
||||
if get_user is None:
|
||||
add_userx(user_id, user_login.lower(), user_name, user_surname, user_fullname)
|
||||
Userx.add(user_id, user_login.lower(), user_name, user_surname, user_fullname)
|
||||
else:
|
||||
if user_name != get_user['user_name']:
|
||||
update_userx(get_user['user_id'], user_name=user_name)
|
||||
if user_name != get_user.user_name:
|
||||
Userx.update(get_user.user_id, user_name=user_name)
|
||||
|
||||
if user_surname != get_user['user_surname']:
|
||||
update_userx(get_user['user_id'], user_surname=user_surname)
|
||||
if user_surname != get_user.user_surname:
|
||||
Userx.update(get_user.user_id, user_surname=user_surname)
|
||||
|
||||
if user_fullname != get_user['user_fullname']:
|
||||
update_userx(get_user['user_id'], user_fullname=user_fullname)
|
||||
if user_fullname != get_user.user_fullname:
|
||||
Userx.update(get_user.user_id, user_fullname=user_fullname)
|
||||
|
||||
if user_login.lower() != get_user['user_login']:
|
||||
update_userx(get_user['user_id'], user_login=user_login.lower())
|
||||
if user_login.lower() != get_user.user_login:
|
||||
Userx.update(get_user.user_id, user_login=user_login.lower())
|
||||
|
||||
data['my_user'] = get_userx(user_id=user_id)
|
||||
data['User'] = Userx.get(user_id=user_id)
|
||||
|
||||
return await handler(event, data)
|
||||
@@ -1,20 +1,25 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import os
|
||||
|
||||
import aiofiles
|
||||
from aiogram import Router, Bot, F
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import FSInputFile, Message, CallbackQuery
|
||||
from aiogram.utils.media_group import MediaGroupBuilder
|
||||
|
||||
from tgbot.data.config import PATH_DATABASE, PATH_LOGS
|
||||
from tgbot.database.db_users import UserModel
|
||||
from tgbot.keyboards.inline_misc import admin_inl
|
||||
from tgbot.keyboards.reply_misc import admin_rep
|
||||
from tgbot.utils.const_functions import get_date
|
||||
from tgbot.utils.misc.bot_models import FSM, RS
|
||||
from tgbot.utils.misc.bot_models import FSM, ARS
|
||||
|
||||
router = Router(name=__name__)
|
||||
|
||||
|
||||
# Кнопка - Admin Inline
|
||||
@router.message(F.text == 'Admin Inline')
|
||||
async def admin_button_inline(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_button_inline(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer("Click Button - Admin Inline", reply_markup=admin_inl)
|
||||
@@ -22,7 +27,7 @@ async def admin_button_inline(message: Message, bot: Bot, state: FSM, rSession:
|
||||
|
||||
# Кнопка - Admin Reply
|
||||
@router.message(F.text == 'Admin Reply')
|
||||
async def admin_button_reply(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_button_reply(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer("Click Button - Admin Reply", reply_markup=admin_rep)
|
||||
@@ -30,13 +35,13 @@ async def admin_button_reply(message: Message, bot: Bot, state: FSM, rSession: R
|
||||
|
||||
# Колбэк - Admin X
|
||||
@router.callback_query(F.data == 'admin_inline_x')
|
||||
async def admin_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await call.answer(f"Click Admin X")
|
||||
|
||||
|
||||
# Колбэк - Admin
|
||||
@router.callback_query(F.data.startswith('admin_inline:'))
|
||||
async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
get_data = call.data.split(":")[1]
|
||||
|
||||
await call.answer(f"Click Admin - {get_data}", True)
|
||||
@@ -44,34 +49,51 @@ async def admin_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, rSess
|
||||
|
||||
# Получение Базы Данных
|
||||
@router.message(Command(commands=['db', 'database']))
|
||||
async def admin_database(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_database(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer_document(
|
||||
FSInputFile(PATH_DATABASE),
|
||||
caption=f"<b>📦 BACKUP</b>\n"
|
||||
f"🕰 <code>{get_date()}</code>",
|
||||
caption=f"<b>📦 #BACKUP | <code>{get_date(full=False)}</code></b>",
|
||||
)
|
||||
|
||||
|
||||
# Получение логов
|
||||
@router.message(Command(commands=['log', 'logs']))
|
||||
async def admin_log(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_log(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer_document(
|
||||
FSInputFile(PATH_LOGS),
|
||||
caption=f"<b>🖨 LOGS</b>\n"
|
||||
f"🕰 <code>{get_date()}</code>",
|
||||
media_group = MediaGroupBuilder(
|
||||
caption=f"<b>🖨 #LOGS | <code>{get_date(full=False)}</code></b>",
|
||||
)
|
||||
|
||||
if os.path.isfile(PATH_LOGS):
|
||||
media_group.add_document(media=FSInputFile(PATH_LOGS))
|
||||
|
||||
if os.path.isfile("tgbot/data/sv_log_err.log"):
|
||||
media_group.add_document(media=FSInputFile("tgbot/data/sv_log_err.log"))
|
||||
|
||||
if os.path.isfile("tgbot/data/sv_log_out.log"):
|
||||
media_group.add_document(media=FSInputFile("tgbot/data/sv_log_out.log"))
|
||||
|
||||
await message.answer_media_group(media=media_group.build())
|
||||
|
||||
|
||||
# Очистить логи
|
||||
@router.message(Command(commands=['clear_log', 'clear_logs', 'log_clear', 'logs_clear']))
|
||||
async def admin_logs_clear(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def admin_logs_clear(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
with open(PATH_LOGS, "w") as file:
|
||||
file.write(f"{get_date()} | LOGS WAS CLEAR")
|
||||
if os.path.isfile(PATH_LOGS):
|
||||
async with aiofiles.open(PATH_LOGS, "w") as file:
|
||||
await file.write(f"{get_date()} | LOGS WAS CLEAR")
|
||||
|
||||
await message.answer("<b>🖨 Логи были успешно очищены</b>")
|
||||
if os.path.isfile("tgbot/data/sv_log_err.log"):
|
||||
async with aiofiles.open("tgbot/data/sv_log_err.log", "w") as file:
|
||||
await file.write(f"{get_date()} | LOGS WAS CLEAR")
|
||||
|
||||
if os.path.isfile("tgbot/data/sv_log_out.log"):
|
||||
async with aiofiles.open("tgbot/data/sv_log_out.log", "w") as file:
|
||||
await file.write(f"{get_date()} | LOGS WAS CLEAR")
|
||||
|
||||
await message.answer("<b>🖨 The logs have been cleared</b>")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
from aiogram import Router
|
||||
from aiogram.exceptions import TelegramForbiddenError
|
||||
from aiogram.filters import ExceptionTypeFilter, ExceptionMessageFilter
|
||||
from aiogram.filters import ExceptionMessageFilter
|
||||
from aiogram.handlers import ErrorHandler
|
||||
|
||||
from tgbot.utils.misc.bot_logging import bot_logger
|
||||
@@ -10,10 +9,10 @@ router = Router(name=__name__)
|
||||
|
||||
|
||||
# Ошибка с блокировкой бота пользователем
|
||||
@router.errors(ExceptionTypeFilter(TelegramForbiddenError))
|
||||
class MyHandler(ErrorHandler):
|
||||
async def handle(self):
|
||||
pass
|
||||
# @router.errors(ExceptionTypeFilter(TelegramForbiddenError))
|
||||
# class MyHandler(ErrorHandler):
|
||||
# async def handle(self):
|
||||
# pass
|
||||
|
||||
|
||||
# Ошибка с редактированием одинакового сообщения
|
||||
|
||||
@@ -2,33 +2,34 @@
|
||||
from aiogram import Router, Bot, F
|
||||
from aiogram.types import CallbackQuery, Message
|
||||
|
||||
from tgbot.database.db_users import UserModel
|
||||
from tgbot.utils.const_functions import del_message
|
||||
from tgbot.utils.misc.bot_models import FSM, RS
|
||||
from tgbot.utils.misc.bot_models import FSM, ARS
|
||||
|
||||
router = Router(name=__name__)
|
||||
|
||||
|
||||
# Колбэк с удалением сообщения
|
||||
@router.callback_query(F.data == 'close_this')
|
||||
async def main_callback_close(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def main_callback_close(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await del_message(call.message)
|
||||
|
||||
|
||||
# Колбэк с обработкой кнопки
|
||||
@router.callback_query(F.data == '...')
|
||||
async def main_callback_answer(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def main_callback_answer(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await call.answer(cache_time=30)
|
||||
|
||||
|
||||
# Колбэк с обработкой удаления сообщений потерявших стейт
|
||||
@router.callback_query()
|
||||
async def main_callback_missed(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def main_callback_missed(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await call.answer(f"❗️ Miss callback: {call.data}", True)
|
||||
|
||||
|
||||
# Обработка всех неизвестных команд
|
||||
@router.message()
|
||||
async def main_message_missed(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def main_message_missed(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await message.answer(
|
||||
"♦️ Unknown command.\n"
|
||||
"♦️ Enter /start",
|
||||
|
||||
@@ -3,9 +3,10 @@ from aiogram import Router, Bot, F
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import Message
|
||||
|
||||
from tgbot.database.db_users import UserModel
|
||||
from tgbot.keyboards.reply_main import menu_frep
|
||||
from tgbot.utils.const_functions import ded
|
||||
from tgbot.utils.misc.bot_models import FSM, RS
|
||||
from tgbot.utils.misc.bot_models import FSM, ARS
|
||||
|
||||
router = Router(name=__name__)
|
||||
|
||||
@@ -13,12 +14,12 @@ router = Router(name=__name__)
|
||||
# Открытие главного меню
|
||||
@router.message(F.text.in_(('🔙 Main menu', '🔙 Return')))
|
||||
@router.message(Command(commands=['start']))
|
||||
async def main_start(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def main_start(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer(
|
||||
ded(f"""
|
||||
🔸 Hello, {my_user['user_name']}
|
||||
🔸 Hello, {User.user_name}
|
||||
🔸 Enter /start or /inline
|
||||
"""),
|
||||
reply_markup=menu_frep(message.from_user.id),
|
||||
|
||||
@@ -3,17 +3,18 @@ from aiogram import Router, Bot, F
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import Message, CallbackQuery
|
||||
|
||||
from tgbot.database.db_users import UserModel
|
||||
from tgbot.keyboards.inline_main import menu_finl
|
||||
from tgbot.keyboards.inline_misc import user_inl
|
||||
from tgbot.keyboards.reply_misc import user_rep
|
||||
from tgbot.utils.misc.bot_models import FSM, RS
|
||||
from tgbot.utils.misc.bot_models import FSM, ARS
|
||||
|
||||
router = Router(name=__name__)
|
||||
|
||||
|
||||
# Кнопка - User Inline
|
||||
@router.message(F.text == 'User Inline')
|
||||
async def user_button_inline(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def user_button_inline(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer(
|
||||
@@ -24,7 +25,7 @@ async def user_button_inline(message: Message, bot: Bot, state: FSM, rSession: R
|
||||
|
||||
# Кнопка - User Reply
|
||||
@router.message(F.text == 'User Reply')
|
||||
async def user_button_reply(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def user_button_reply(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer(
|
||||
@@ -35,7 +36,7 @@ async def user_button_reply(message: Message, bot: Bot, state: FSM, rSession: RS
|
||||
|
||||
# Команда - /inline
|
||||
@router.message(Command(commands="inline"))
|
||||
async def user_command_inline(message: Message, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def user_command_inline(message: Message, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await state.clear()
|
||||
|
||||
await message.answer(
|
||||
@@ -46,13 +47,13 @@ async def user_command_inline(message: Message, bot: Bot, state: FSM, rSession:
|
||||
|
||||
# Колбэк - User X
|
||||
@router.callback_query(F.data == 'user_inline_x')
|
||||
async def user_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def user_callback_inline_x(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
await call.answer(f"Click User X")
|
||||
|
||||
|
||||
# Колбэк - User
|
||||
@router.callback_query(F.data.startswith('user_inline:'))
|
||||
async def user_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, rSession: RS, my_user):
|
||||
async def user_callback_inline(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS, User: UserModel):
|
||||
get_data = call.data.split(":")[1]
|
||||
|
||||
await call.answer(f"Click User - {get_data}", True)
|
||||
|
||||
@@ -5,12 +5,12 @@ import aiohttp
|
||||
|
||||
|
||||
# In handler
|
||||
# session = await rSession.get_session()
|
||||
# session = await arSession.get_session()
|
||||
# response = await session.get(...)
|
||||
# response = await session.post(...)
|
||||
|
||||
# Асинхронная сессия для запросов
|
||||
class RequestSession:
|
||||
class AsyncRequestSession:
|
||||
def __init__(self) -> None:
|
||||
self._session: Optional[aiohttp.ClientSession] = None
|
||||
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
import sqlite3
|
||||
|
||||
from tgbot.data.config import PATH_DATABASE
|
||||
from tgbot.utils.const_functions import get_unix
|
||||
|
||||
|
||||
# Преобразование БД словаря
|
||||
def dict_factory(cursor, row) -> dict:
|
||||
this_dict = {}
|
||||
|
||||
for idx, col in enumerate(cursor.description):
|
||||
this_dict[col[0]] = row[idx]
|
||||
|
||||
return this_dict
|
||||
|
||||
|
||||
################################################################################
|
||||
########################### ФОРМАТИРОВАНИЕ ЗАПРОСОВ ############################
|
||||
# Форматирование запроса без аргументов
|
||||
def update_format(sql, parameters: dict) -> tuple[str, list]:
|
||||
values = ", ".join([
|
||||
f"{item} = ?" for item in parameters
|
||||
])
|
||||
sql += f" {values}"
|
||||
|
||||
return sql, list(parameters.values())
|
||||
|
||||
|
||||
# Форматирование запроса с аргументами
|
||||
def update_format_args(sql, parameters: dict) -> tuple[str, list]:
|
||||
sql += " WHERE "
|
||||
|
||||
sql += " AND ".join([
|
||||
f"{item} = ?" for item in parameters
|
||||
])
|
||||
|
||||
return sql, list(parameters.values())
|
||||
|
||||
|
||||
############################# ЗАПРОСЫ К БАЗЕ ДАННЫХ ############################
|
||||
################################################################################
|
||||
# Добавление пользователя
|
||||
def add_userx(user_id, user_login, user_name, user_surname, user_fullname):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
con.execute(
|
||||
"INSERT INTO storage_users "
|
||||
"(user_id, user_login, user_name, user_surname, user_fullname, user_unix) "
|
||||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||
[user_id, user_login, user_name, user_surname, user_fullname, get_unix()],
|
||||
)
|
||||
|
||||
|
||||
# Получение пользователя
|
||||
def get_userx(**kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = "SELECT * FROM storage_users"
|
||||
sql, parameters = update_format_args(sql, kwargs)
|
||||
|
||||
return con.execute(sql, parameters).fetchone()
|
||||
|
||||
|
||||
# Получение пользователей
|
||||
def get_usersx(**kwargs) -> list[dict]:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = "SELECT * FROM storage_users"
|
||||
sql, parameters = update_format_args(sql, kwargs)
|
||||
|
||||
return con.execute(sql, parameters).fetchall()
|
||||
|
||||
|
||||
# Получение всех пользователей
|
||||
def get_all_usersx() -> list[dict]:
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = "SELECT * FROM storage_users"
|
||||
|
||||
return con.execute(sql).fetchall()
|
||||
|
||||
|
||||
# Редактирование пользователя
|
||||
def update_userx(user_id, **kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = f"UPDATE storage_users SET"
|
||||
sql, parameters = update_format(sql, kwargs)
|
||||
parameters.append(user_id)
|
||||
con.execute(sql + "WHERE user_id = ?", parameters)
|
||||
|
||||
|
||||
# Удаление пользователя
|
||||
def delete_userx(**kwargs):
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
sql = "DELETE FROM storage_users"
|
||||
sql, parameters = update_format_args(sql, kwargs)
|
||||
con.execute(sql, parameters)
|
||||
|
||||
|
||||
############################## СОЗДАНИЕ БАЗЫ ДАННЫХ ############################
|
||||
# Создание всех таблиц для Базы Данных
|
||||
def create_dbx():
|
||||
with sqlite3.connect(PATH_DATABASE) as con:
|
||||
con.row_factory = dict_factory
|
||||
|
||||
# Таблица с хранением пользователей
|
||||
if len(con.execute("PRAGMA table_info(storage_users)").fetchall()) == 7:
|
||||
print("DB was found(1/1)")
|
||||
else:
|
||||
con.execute(
|
||||
"CREATE TABLE storage_users("
|
||||
"increment INTEGER PRIMARY KEY AUTOINCREMENT, "
|
||||
"user_id INTEGER,"
|
||||
"user_login TEXT,"
|
||||
"user_name TEXT,"
|
||||
"user_surname TEXT,"
|
||||
"user_fullname TEXT,"
|
||||
"user_unix INTEGER"
|
||||
")"
|
||||
)
|
||||
print("DB was not found(1/1) | Creating...")
|
||||
@@ -1,7 +1,7 @@
|
||||
# - *- coding: utf- 8 - *-
|
||||
from aiogram.fsm.context import FSMContext
|
||||
|
||||
from tgbot.services.api_session import RequestSession
|
||||
from tgbot.services.api_session import AsyncRequestSession
|
||||
|
||||
FSM = FSMContext
|
||||
RS = RequestSession
|
||||
ARS = AsyncRequestSession
|
||||
|
||||
Reference in New Issue
Block a user