forked from FOSS/AutoShop-Djimbo
refactor: remove Alembic migrations and Discord integration
This commit is contained in:
@@ -29,13 +29,13 @@ def rkb(text: str) -> KeyboardButton:
|
||||
|
||||
# Быстрая сборка inline-кнопки
|
||||
def ikb(
|
||||
text: str,
|
||||
data: Optional[str] = None,
|
||||
url: Optional[str] = None,
|
||||
switch: Optional[str] = None,
|
||||
web: Optional[str] = None,
|
||||
copy: Optional[str] = None,
|
||||
login: Optional[str] = None,
|
||||
text: str,
|
||||
data: Optional[str] = None,
|
||||
url: Optional[str] = None,
|
||||
switch: Optional[str] = None,
|
||||
web: Optional[str] = None,
|
||||
copy: Optional[str] = None,
|
||||
login: Optional[str] = None,
|
||||
) -> InlineKeyboardButton:
|
||||
if data is not None:
|
||||
return InlineKeyboardButton(text=text, callback_data=data)
|
||||
@@ -61,36 +61,27 @@ async def del_message(message: Message) -> None:
|
||||
bot_logger.debug("Не удалось удалить сообщение", exc_info=True)
|
||||
|
||||
|
||||
# Отправка фото или обычного сообщения
|
||||
# Отправка обычного сообщения
|
||||
async def smart_message(
|
||||
bot: Bot,
|
||||
user_id: int,
|
||||
text: str,
|
||||
keyboard: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup]] = None,
|
||||
photo: Optional[str] = None,
|
||||
bot: Bot,
|
||||
user_id: int,
|
||||
text: str,
|
||||
keyboard: Optional[Union[InlineKeyboardMarkup, ReplyKeyboardMarkup]] = None,
|
||||
) -> None:
|
||||
if photo is not None and photo.title() != "None":
|
||||
await bot.send_photo(
|
||||
chat_id=user_id,
|
||||
photo=photo,
|
||||
caption=text,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
else:
|
||||
await bot.send_message(
|
||||
chat_id=user_id,
|
||||
text=text,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
await bot.send_message(
|
||||
chat_id=user_id,
|
||||
text=text,
|
||||
reply_markup=keyboard,
|
||||
)
|
||||
|
||||
|
||||
# Отправка сообщения всем админам
|
||||
async def send_admins(
|
||||
bot: Bot,
|
||||
text: str,
|
||||
keyboard: Optional[InlineKeyboardMarkup] = None,
|
||||
markup: Optional[InlineKeyboardMarkup] = None,
|
||||
not_me: int = 0,
|
||||
bot: Bot,
|
||||
text: str,
|
||||
keyboard: Optional[InlineKeyboardMarkup] = None,
|
||||
markup: Optional[InlineKeyboardMarkup] = None,
|
||||
not_me: int = 0,
|
||||
) -> None:
|
||||
reply_markup = markup or keyboard
|
||||
|
||||
@@ -104,7 +95,9 @@ async def send_admins(
|
||||
disable_web_page_preview=True,
|
||||
)
|
||||
except Exception:
|
||||
bot_logger.warning("Не удалось отправить сообщение админу %s", admin, exc_info=True)
|
||||
bot_logger.warning(
|
||||
"Не удалось отправить сообщение админу %s", admin, exc_info=True
|
||||
)
|
||||
|
||||
|
||||
# Логирование ошибки и отправка админам
|
||||
@@ -120,8 +113,10 @@ def ded(get_text: str) -> str:
|
||||
if get_text is not None:
|
||||
split_text = get_text.split("\n")
|
||||
|
||||
if split_text[0] == "": split_text.pop(0)
|
||||
if split_text[-1] == "": split_text.pop()
|
||||
if split_text[0] == "":
|
||||
split_text.pop(0)
|
||||
if split_text[-1] == "":
|
||||
split_text.pop()
|
||||
save_text = []
|
||||
|
||||
for text in split_text:
|
||||
@@ -163,7 +158,7 @@ def convert_list(get_lists: List[list]) -> list:
|
||||
|
||||
# Разделение списка на части нужного размера
|
||||
def split_list(get_list: list, count: int) -> List[list]:
|
||||
return [get_list[i:i + count] for i in range(0, len(get_list), count)]
|
||||
return [get_list[i : i + count] for i in range(0, len(get_list), count)]
|
||||
|
||||
|
||||
# Старое имя для разделения сообщений
|
||||
@@ -198,9 +193,13 @@ def convert_date(from_time, full=True, second=True) -> Union[str, int]:
|
||||
from_timestamp = int(from_time)
|
||||
|
||||
if full:
|
||||
return datetime.fromtimestamp(from_timestamp, bot_timezone).strftime("%d.%m.%Y %H:%M:%S")
|
||||
return datetime.fromtimestamp(from_timestamp, bot_timezone).strftime(
|
||||
"%d.%m.%Y %H:%M:%S"
|
||||
)
|
||||
if second:
|
||||
return datetime.fromtimestamp(from_timestamp, bot_timezone).strftime("%d.%m.%Y %H:%M")
|
||||
return datetime.fromtimestamp(from_timestamp, bot_timezone).strftime(
|
||||
"%d.%m.%Y %H:%M"
|
||||
)
|
||||
|
||||
return datetime.fromtimestamp(from_timestamp, bot_timezone).strftime("%d.%m.%Y")
|
||||
|
||||
|
||||
@@ -7,8 +7,13 @@ from typing import Union
|
||||
from aiogram import Bot
|
||||
from aiogram.types import FSInputFile, CallbackQuery, Message
|
||||
|
||||
from tgbot.data.config import BOT_DATABASE_EXPORT, BOT_STATUS_NOTIFICATION, BOT_VERSION, PATH_DATABASE, get_admins, \
|
||||
get_text_desc
|
||||
from tgbot.data.config import (
|
||||
BOT_DATABASE_EXPORT,
|
||||
BOT_STATUS_NOTIFICATION,
|
||||
BOT_VERSION,
|
||||
PATH_DATABASE,
|
||||
get_admins,
|
||||
)
|
||||
from tgbot.database import Userx, Settingsx
|
||||
from tgbot.utils.const_functions import get_unix, get_date, ded, send_admins
|
||||
from tgbot.utils.misc.bot_logging import bot_logger
|
||||
@@ -40,9 +45,17 @@ async def autosettings_unix():
|
||||
now_month = datetime.now().month
|
||||
now_year = datetime.now().year
|
||||
|
||||
unix_day = int(datetime.strptime(f"{now_day}.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S").timestamp())
|
||||
unix_day = int(
|
||||
datetime.strptime(
|
||||
f"{now_day}.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S"
|
||||
).timestamp()
|
||||
)
|
||||
unix_week = unix_day - (now_week * 86400)
|
||||
unix_month = int(datetime.strptime(f"1.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S").timestamp())
|
||||
unix_month = int(
|
||||
datetime.strptime(
|
||||
f"1.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S"
|
||||
).timestamp()
|
||||
)
|
||||
|
||||
await Settingsx().update(
|
||||
misc_profit_day=unix_day,
|
||||
@@ -68,8 +81,6 @@ async def startup_notify(bot: Bot, arSession: ARS):
|
||||
ded(f"""
|
||||
<b>✅ Бот был успешно запущен</b>
|
||||
➖➖➖➖➖➖➖➖➖➖
|
||||
{get_text_desc()}
|
||||
➖➖➖➖➖➖➖➖➖➖
|
||||
<code>❗ Данное сообщение видят только администраторы бота.</code>
|
||||
"""),
|
||||
)
|
||||
@@ -91,7 +102,9 @@ async def autobackup_admin(bot: Bot):
|
||||
disable_notification=True,
|
||||
)
|
||||
except Exception:
|
||||
bot_logger.warning("Не удалось отправить автобэкап админу %s", admin, exc_info=True)
|
||||
bot_logger.warning(
|
||||
"Не удалось отправить автобэкап админу %s", admin, exc_info=True
|
||||
)
|
||||
|
||||
|
||||
# Проверка наличия обновлений бота
|
||||
@@ -106,7 +119,7 @@ async def check_update(bot: Bot, arSession: ARS):
|
||||
|
||||
response_data = json.loads((await response.read()).decode())
|
||||
|
||||
if float(response_data['version']) > float(BOT_VERSION):
|
||||
if float(response_data["version"]) > float(BOT_VERSION):
|
||||
await send_admins(
|
||||
bot,
|
||||
ded(f"""
|
||||
@@ -132,7 +145,7 @@ async def check_mail(bot: Bot, arSession: ARS):
|
||||
)
|
||||
response_data = json.loads((await response.read()).decode())
|
||||
|
||||
if response_data['status']:
|
||||
if response_data["status"]:
|
||||
await send_admins(
|
||||
bot,
|
||||
ded(f"""
|
||||
@@ -176,21 +189,23 @@ async def functions_mail_make(bot: Bot, message: Message, call: CallbackQuery):
|
||||
users_receive += 1
|
||||
except Exception:
|
||||
users_block += 1
|
||||
bot_logger.debug("Пользователь %s не получил рассылку", user.user_id, exc_info=True)
|
||||
bot_logger.debug(
|
||||
"Пользователь %s не получил рассылку", user.user_id, exc_info=True
|
||||
)
|
||||
|
||||
users_count += 1
|
||||
|
||||
if users_count % 10 == 0:
|
||||
await call.message.edit_text(f"<b>📢 Рассылка началась... ({users_count}/{len(get_users)})</b>")
|
||||
await call.message.edit_text(
|
||||
f"<b>📢 Рассылка началась... ({users_count}/{len(get_users)})</b>"
|
||||
)
|
||||
|
||||
await asyncio.sleep(0.07)
|
||||
|
||||
await call.message.edit_text(
|
||||
ded(f"""
|
||||
await call.message.edit_text(ded(f"""
|
||||
<b>📢 Рассылка была завершена за <code>{get_unix() - get_time}сек</code></b>
|
||||
➖➖➖➖➖➖➖➖➖➖
|
||||
👤 Всего пользователей: <code>{len(get_users)}</code>
|
||||
✅ Пользователей получило сообщение: <code>{users_receive}</code>
|
||||
❌ Пользователей не получило сообщение: <code>{users_block}</code>
|
||||
""")
|
||||
)
|
||||
"""))
|
||||
|
||||
+100
-30
@@ -21,7 +21,11 @@ from tgbot.database import (
|
||||
ModelUser,
|
||||
)
|
||||
from tgbot.keyboards.inline_admin import profile_edit_finl
|
||||
from tgbot.keyboards.inline_admin_products import position_edit_open_finl, category_edit_open_finl, item_delete_finl
|
||||
from tgbot.keyboards.inline_admin_products import (
|
||||
position_edit_open_finl,
|
||||
category_edit_open_finl,
|
||||
item_delete_finl,
|
||||
)
|
||||
from tgbot.keyboards.inline_user import user_profile_finl
|
||||
from tgbot.keyboards.inline_user_products import products_open_finl
|
||||
from tgbot.services.api_hosting_text import HostingAPI
|
||||
@@ -68,7 +72,7 @@ async def position_open_user(bot: Bot, user_id: int, position_id: int, remover:
|
||||
await bot.send_message(
|
||||
chat_id=user_id,
|
||||
text=ded(f"""
|
||||
<b>🎁 Покупка товара</b>{hide_link(get_position.position_photo)}
|
||||
<b>🎁 Покупка товара</b>
|
||||
➖➖➖➖➖➖➖➖➖➖
|
||||
▪️ Название: <code>{get_position.position_name}</code>
|
||||
▪️ Категория: <code>{get_category.category_name}</code>
|
||||
@@ -78,7 +82,6 @@ async def position_open_user(bot: Bot, user_id: int, position_id: int, remover:
|
||||
"""),
|
||||
link_preview_options=LinkPreviewOptions(show_above_text=True),
|
||||
reply_markup=products_open_finl(position_id, get_position.category_id, remover),
|
||||
|
||||
)
|
||||
|
||||
|
||||
@@ -114,7 +117,7 @@ async def open_profile_admin(bot: Bot, user_id: int, get_user: ModelUser):
|
||||
async def refill_open_admin(bot: Bot, user_id: int, get_refill: ModelRefill):
|
||||
get_user = await Userx().get_required(user_id=get_refill.user_id)
|
||||
|
||||
if get_refill.refill_method in ['Form', 'Nickname', 'Number', 'QIWI']:
|
||||
if get_refill.refill_method in ["Form", "Nickname", "Number", "QIWI"]:
|
||||
pay_method = "QIWI 🥝"
|
||||
elif get_refill.refill_method == "Yoomoney":
|
||||
pay_method = "ЮMoney 🔮"
|
||||
@@ -138,7 +141,9 @@ async def refill_open_admin(bot: Bot, user_id: int, get_refill: ModelRefill):
|
||||
|
||||
|
||||
# Открытие покупки админом
|
||||
async def purchase_open_admin(bot: Bot, arSession: ARS, user_id: int, get_purchase: ModelPurchases):
|
||||
async def purchase_open_admin(
|
||||
bot: Bot, arSession: ARS, user_id: int, get_purchase: ModelPurchases
|
||||
):
|
||||
get_user = await Userx().get_required(user_id=get_purchase.user_id)
|
||||
|
||||
link_items = await (
|
||||
@@ -172,8 +177,18 @@ async def purchase_open_admin(bot: Bot, arSession: ARS, user_id: int, get_purcha
|
||||
|
||||
# Открытие категории админом
|
||||
async def category_open_admin(bot: Bot, user_id: int, category_id: int, remover: int):
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = 0, 0, 0, 0
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = 0, 0, 0, 0
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
|
||||
get_items = await Itemx().gets(category_id=category_id)
|
||||
get_category = await Categoryx().get_required(category_id=category_id)
|
||||
@@ -217,8 +232,18 @@ async def category_open_admin(bot: Bot, user_id: int, category_id: int, remover:
|
||||
|
||||
# Открытие позиции админом
|
||||
async def position_open_admin(bot: Bot, position_id: int, user_id: int):
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = 0, 0, 0, 0
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = 0, 0, 0, 0
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
|
||||
get_items = await Itemx().gets(position_id=position_id)
|
||||
get_position = await Positionx().get_required(position_id=position_id)
|
||||
@@ -227,12 +252,6 @@ async def position_open_admin(bot: Bot, position_id: int, user_id: int):
|
||||
get_settings = await Settingsx().get()
|
||||
get_purchases = await Purchasesx().gets(purchase_position_id=position_id)
|
||||
|
||||
# Наличие фото
|
||||
if get_position.position_photo != "None":
|
||||
position_photo_text = "<code>Присутствует ✅</code>"
|
||||
else:
|
||||
position_photo_text = "<code>Отсутствует ❌</code>"
|
||||
|
||||
# Наличие описания
|
||||
if get_position.position_desc != "None":
|
||||
position_desc = f"{get_position.position_desc}"
|
||||
@@ -257,14 +276,13 @@ async def position_open_admin(bot: Bot, position_id: int, user_id: int):
|
||||
await bot.send_message(
|
||||
chat_id=user_id,
|
||||
text=ded(f"""
|
||||
<b>📁 Редактирование позиции</b>{hide_link(get_position.position_photo)}
|
||||
<b>📁 Редактирование позиции</b>
|
||||
➖➖➖➖➖➖➖➖➖➖
|
||||
▪️ Категория: <code>{get_category.category_name}</code>
|
||||
▪️ Позиция: <code>{get_position.position_name}</code>
|
||||
▪️ Стоимость: <code>{get_position.position_price}₽</code>
|
||||
▪️ Количество: <code>{len(get_items)}шт</code>
|
||||
▪️ Дата создания: <code>{convert_date(get_category.category_unix)}</code>
|
||||
▪️ Изображение: {position_photo_text}
|
||||
▪️ Описание: {position_desc}
|
||||
|
||||
💸 Продаж за День: <code>{profit_count_day}шт</code> - <code>{round(profit_amount_day, 2)}₽</code>
|
||||
@@ -274,7 +292,6 @@ async def position_open_admin(bot: Bot, position_id: int, user_id: int):
|
||||
"""),
|
||||
link_preview_options=LinkPreviewOptions(show_above_text=True),
|
||||
reply_markup=await position_edit_open_finl(bot, position_id, 0),
|
||||
|
||||
)
|
||||
|
||||
|
||||
@@ -303,11 +320,38 @@ async def item_open_admin(bot: Bot, item_id: int, user_id: int):
|
||||
################################################################################
|
||||
# Статистика бота
|
||||
async def get_statistics() -> str:
|
||||
refill_amount_all, refill_amount_day, refill_amount_week, refill_amount_month = 0, 0, 0, 0
|
||||
refill_count_all, refill_count_day, refill_count_week, refill_count_month = 0, 0, 0, 0
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = 0, 0, 0, 0
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = 0, 0, 0, 0
|
||||
users_all, users_day, users_week, users_month, users_money_have, users_money_give = 0, 0, 0, 0, 0, 0
|
||||
refill_amount_all, refill_amount_day, refill_amount_week, refill_amount_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
refill_count_all, refill_count_day, refill_count_week, refill_count_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
profit_amount_all, profit_amount_day, profit_amount_week, profit_amount_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
profit_count_all, profit_count_day, profit_count_week, profit_count_month = (
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
(
|
||||
users_all,
|
||||
users_day,
|
||||
users_week,
|
||||
users_month,
|
||||
users_money_have,
|
||||
users_money_give,
|
||||
) = (0, 0, 0, 0, 0, 0)
|
||||
refill_cryptobot_count, refill_cryptobot_amount = 0, 0
|
||||
refill_yoomoney_count, refill_yoomoney_amount = 0, 0
|
||||
refill_stars_count, refill_stars_amount = 0, 0
|
||||
@@ -375,12 +419,28 @@ async def get_statistics() -> str:
|
||||
|
||||
# Даты обновления статистики
|
||||
all_days = [
|
||||
'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье',
|
||||
"Понедельник",
|
||||
"Вторник",
|
||||
"Среда",
|
||||
"Четверг",
|
||||
"Пятница",
|
||||
"Суббота",
|
||||
"Воскресенье",
|
||||
]
|
||||
|
||||
all_months = [
|
||||
'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь',
|
||||
'Октябрь', 'Ноябрь', 'Декабрь'
|
||||
"Январь",
|
||||
"Февраль",
|
||||
"Март",
|
||||
"Апрель",
|
||||
"Май",
|
||||
"Июнь",
|
||||
"Июль",
|
||||
"Август",
|
||||
"Сентябрь",
|
||||
"Октябрь",
|
||||
"Ноябрь",
|
||||
"Декабрь",
|
||||
]
|
||||
|
||||
now_day = datetime.now().day
|
||||
@@ -388,12 +448,22 @@ async def get_statistics() -> str:
|
||||
now_month = datetime.now().month
|
||||
now_year = datetime.now().year
|
||||
|
||||
unix_day = int(datetime.strptime(f"{now_day}.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S").timestamp())
|
||||
unix_day = int(
|
||||
datetime.strptime(
|
||||
f"{now_day}.{now_month}.{now_year} 0:0:0", "%d.%m.%Y %H:%M:%S"
|
||||
).timestamp()
|
||||
)
|
||||
unix_week = unix_day - (now_week * 86400)
|
||||
|
||||
week_day = int(datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%d"))
|
||||
week_month = int(datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%m"))
|
||||
week_week = int(datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).weekday())
|
||||
week_day = int(
|
||||
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%d")
|
||||
)
|
||||
week_month = int(
|
||||
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).strftime("%m")
|
||||
)
|
||||
week_week = int(
|
||||
datetime.fromtimestamp(unix_week, pytz.timezone(BOT_TIMEZONE)).weekday()
|
||||
)
|
||||
|
||||
return ded(f"""
|
||||
<b>📊 СТАТИСТИКА БОТА</b>
|
||||
|
||||
Reference in New Issue
Block a user