Initial local state

This commit is contained in:
2026-07-15 07:17:25 +05:00
commit 68221821a5
78 changed files with 10318 additions and 0 deletions
View File
+187
View File
@@ -0,0 +1,187 @@
# - *- coding: utf- 8 - *-
import asyncio
from aiogram import Router, Bot, F
from aiogram.filters import Command
from aiogram.types import CallbackQuery, Message
from tgbot.data.config import BOT_VERSION, get_text_desc, get_text_warning
from tgbot.database import Purchasesx, Settingsx
from tgbot.keyboards.inline_user import user_support_finl
from tgbot.keyboards.inline_user_page import *
from tgbot.services.api_hosting_text import HostingAPI
from tgbot.utils.const_functions import ded, del_message, convert_date
from tgbot.utils.misc.bot_models import FSM, ARS
from tgbot.utils.misc_functions import insert_tags
from tgbot.utils.products_functions import get_items_available
from tgbot.utils.text_functions import open_profile_user
router = Router(name=__name__)
# Открытие товаров
@router.message(F.text == "🎁 Купить")
async def user_shop(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
get_categories = await get_categories_items()
if len(get_categories) >= 1:
await message.answer(
"<b>🎁 Выберите нужный вам товар</b>",
reply_markup=await prod_item_category_swipe_fp(0),
)
else:
await message.answer("<b>🎁 Увы, товары в данное время отсутствуют</b>")
# Открытие профиля
@router.message(F.text == "👤 Профиль")
async def user_profile(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
await open_profile_user(bot, message.from_user.id)
# Проверка товаров в наличии
@router.message(F.text == "🧮 Наличие товаров")
async def user_available(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
items_available, remover_max, remover_now = await get_items_available(0)
if len(items_available) >= 1:
await message.answer(
items_available,
reply_markup=prod_available_swipe_fp(remover_now, remover_max),
)
else:
await message.answer("<b>🎁 Увы, товары в данное время отсутствуют</b>")
# Открытие FAQ
@router.message(F.text.in_(('❔ FAQ', '/faq')))
async def user_faq(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
get_settings = await Settingsx().get()
if get_settings.misc_faq == "None":
return await message.answer(
ded(f"""
❔ Текст FAQ не указан. Измените его в настройках бота.
➖➖➖➖➖➖➖➖➖➖
{get_text_desc()}
➖➖➖➖➖➖➖➖➖➖
{get_text_warning()}
"""),
disable_web_page_preview=True,
)
await message.answer(
await insert_tags(message.from_user.id, get_settings.misc_faq),
disable_web_page_preview=True,
)
# Открытие сообщения с ссылкой на поддержку
@router.message(F.text.in_(('☎️ Поддержка', '/support')))
async def user_support(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
get_settings = await Settingsx().get()
if get_settings.misc_support == "None":
return await message.answer(
ded(f"""
☎️ Контакты поддержки не указаны. Измените их в настройках бота.
➖➖➖➖➖➖➖➖➖➖
{get_text_desc()}
➖➖➖➖➖➖➖➖➖➖
{get_text_warning()}
"""),
disable_web_page_preview=True,
)
await message.answer(
"<b>☎️ Нажмите кнопку ниже для связи с Администратором</b>",
reply_markup=user_support_finl(get_settings.misc_support),
)
# Получение версии бота
@router.message(Command(commands=['version']))
async def admin_version(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
await message.answer(f"<b>❇️ Текущая версия бота: <code>{BOT_VERSION}</code></b>")
# Получение информации о боте
@router.message(Command(commands=['dj_desc']))
async def admin_desc(message: Message, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
await message.answer(get_text_desc(), disable_web_page_preview=True)
################################################################################
# Переход к профилю
@router.callback_query(F.data == "user_profile")
async def user_profile_return(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
await state.clear()
await del_message(call.message)
await open_profile_user(bot, call.from_user.id)
# Просмотр истории покупок
@router.callback_query(F.data == "user_purchases")
async def user_purchases(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
get_purchases = await Purchasesx().gets(user_id=call.from_user.id)
get_purchases = get_purchases[-5:]
if len(get_purchases) >= 1:
await call.answer("🎁 Последние 5 покупок")
await del_message(call.message)
for purchase in get_purchases:
link_items = await (
await HostingAPI.connect(
bot=bot,
arSession=arSession,
)
).upload_text(purchase.purchase_data)
await call.message.answer(
ded(f"""
<b>🧾 Чек: <code>#{purchase.purchase_receipt}</code></b>
▪️ Товар: <code>{purchase.purchase_position_name} | {purchase.purchase_count}шт | {purchase.purchase_price}₽</code>
▪️ Дата покупки: <code>{convert_date(purchase.purchase_unix)}</code>
▪️ Товары: <a href='{link_items}'>кликабельно</a>
"""),
disable_web_page_preview=True,
)
await asyncio.sleep(0.2)
await open_profile_user(bot, call.from_user.id)
else:
await call.answer("❗ У вас отсутствуют покупки", True)
# Страницы наличия товаров
@router.callback_query(F.data.startswith("user_available_swipe:"))
async def user_available_swipe(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
remover = int(call.data.split(":")[1])
items_available, remover_max, remover_now = await get_items_available(remover)
await call.message.edit_text(
items_available,
reply_markup=prod_available_swipe_fp(remover_now, remover_max),
)
+276
View File
@@ -0,0 +1,276 @@
# - *- coding: utf- 8 - *-
import asyncio
from aiogram import Router, Bot, F
from aiogram.filters import StateFilter
from aiogram.types import CallbackQuery, Message
from tgbot.database import Positionx, Userx, Categoryx, Itemx, Paymentsx, Purchasesx, Settingsx
from tgbot.keyboards.inline_user import refill_method_buy_finl
from tgbot.keyboards.inline_user_page import *
from tgbot.keyboards.inline_user_products import products_buy_confirm_finl, products_return_finl
from tgbot.keyboards.reply_main import menu_frep
from tgbot.utils.const_functions import ded, del_message, convert_date, send_admins
from tgbot.utils.misc.bot_models import FSM, ARS
from tgbot.utils.products_functions import get_positions_items
from tgbot.utils.text_functions import position_open_user
router = Router(name=__name__)
# Страницы выбора категории для покупки товара
@router.callback_query(F.data.startswith("buy_category_swipe:"))
async def user_buy_category_swipe(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
remover = int(call.data.split(":")[1])
await call.message.edit_text(
"<b>🎁 Выберите нужный вам товар</b>",
reply_markup=await prod_item_category_swipe_fp(remover),
)
# Открытие категории с выбором позиции для покупки товара
@router.callback_query(F.data.startswith("buy_category_open:"))
async def user_buy_category_open(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
category_id = int(call.data.split(":")[1])
remover = int(call.data.split(":")[2])
get_category = await Categoryx().get_required(category_id=category_id)
get_positions = await get_positions_items(category_id)
if len(get_positions) >= 1:
await del_message(call.message)
await call.message.answer(
f"<b>🎁 Текущая категория: <code>{get_category.category_name}</code></b>",
reply_markup=await prod_item_position_swipe_fp(remover, category_id),
)
else:
await call.answer(
f"❕ Товары в категории {get_category.category_name} отсутствуют",
True,
cache_time=5,
)
# Страницы выбора позиции для покупки товара
@router.callback_query(F.data.startswith("buy_position_swipe:"))
async def user_buy_position_swipe(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
category_id = int(call.data.split(":")[1])
remover = int(call.data.split(":")[2])
get_category = await Categoryx().get_required(category_id=category_id)
await del_message(call.message)
await call.message.answer(
f"<b>🎁 Текущая категория: <code>{get_category.category_name}</code></b>",
reply_markup=await prod_item_position_swipe_fp(remover, category_id),
)
# Открытие позиции для покупки товара
@router.callback_query(F.data.startswith("buy_position_open:"))
async def user_buy_position_open(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
position_id = int(call.data.split(":")[1])
remover = int(call.data.split(":")[2])
await state.clear()
await del_message(call.message)
await position_open_user(bot, call.from_user.id, position_id, remover)
#################################### ПОКУПКА ###################################
# Покупка товара
@router.callback_query(F.data.startswith("buy_item_open:"))
async def user_buy_open(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
position_id = int(call.data.split(":")[1])
remover = int(call.data.split(":")[2])
get_payments = await Paymentsx().get()
get_position = await Positionx().get_required(position_id=position_id)
get_items = await Itemx().gets(position_id=position_id)
get_user = await Userx().get_required(user_id=call.from_user.id)
# Проверка, имеется ли на балансе пользователя достаточно средств
if get_user.user_balance < get_position.position_price:
if get_payments.status_cryptobot == "True" or get_payments.status_yoomoney == "True":
await call.message.answer(
"<b>❗ На вашем счёте недостаточно средств</b>\n"
"💰 Выберите способ пополнения баланса",
reply_markup=await refill_method_buy_finl(),
)
return await call.answer(cache_time=5)
else:
return await call.answer("❗ У вас недостаточно средств. Пополните баланс", True)
if len(get_items) < 1:
return await call.answer("❗ Товаров нет в наличии", True)
# Максимальное количество товаров к покупке, подстроенные под баланс пользователя
if get_position.position_price != 0:
max_buy_count = int(get_user.user_balance / get_position.position_price)
if max_buy_count > len(get_items):
available_count = len(get_items)
else:
available_count = max_buy_count
else:
available_count = len(get_items)
# Если в наличии всего один товар, то пропустить ввод количества товаров к покупке
if available_count == 1:
await state.clear()
await del_message(call.message)
await call.message.answer(
ded(f"""
<b>🎁 Вы действительно хотите купить товар(ы)?</b>
➖➖➖➖➖➖➖➖➖➖
▪️ Товар: <code>{get_position.position_name}</code>
▪️ Количество: <code>1шт</code>
▪️ Сумма к покупке: <code>{get_position.position_price}₽</code>
"""),
reply_markup=products_buy_confirm_finl(position_id, get_position.category_id, 1),
)
else:
await state.update_data(here_buy_position_id=position_id)
await state.set_state("here_item_count")
await del_message(call.message)
await call.message.answer(
ded(f"""
<b>🎁 Введите количество товаров для покупки</b>
❕ От <code>1</code> до <code>{available_count}</code>
➖➖➖➖➖➖➖➖➖➖
▪️ Товар: <code>{get_position.position_name}</code> - <code>{get_position.position_price}₽</code>
▪️ Ваш баланс: <code>{get_user.user_balance}₽</code>
"""),
reply_markup=products_return_finl(position_id, get_position.category_id),
)
# Принятие количества товаров для покупки
@router.message(F.text, StateFilter("here_item_count"))
async def user_buy_count(message: Message, bot: Bot, state: FSM, arSession: ARS):
position_id = (await state.get_data())['here_buy_position_id']
get_position = await Positionx().get_required(position_id=position_id)
get_user = await Userx().get_required(user_id=message.from_user.id)
get_items = await Itemx().gets(position_id=position_id)
# Максимальное количество товаров к покупке, подстроенные под баланс пользователя
if get_position.position_price != 0:
get_count = int(get_user.user_balance / get_position.position_price)
if get_count > len(get_items):
get_count = len(get_items)
else:
get_count = len(get_items)
send_message = ded(f"""
🎁 Введите количество товаров для покупки
❕ От <code>1</code> до <code>{get_count}</code>
➖➖➖➖➖➖➖➖➖➖
▪️ Товар: <code>{get_position.position_name}</code> - <code>{get_position.position_price}₽</code>
▪️ Ваш баланс: <code>{get_user.user_balance}₽</code>
""")
# Если было введено не число
if not message.text.isdigit():
return await message.answer(
f"<b>❌ Данные были введены неверно</b>\n" + send_message,
reply_markup=products_return_finl(position_id, get_position.category_id),
)
get_count = int(message.text)
amount_pay = round(get_position.position_price * get_count, 2)
# Если товаров нет в наличии
if len(get_items) < 1:
await state.clear()
return await message.answer("<b>🎁 Товар который вы хотели купить, закончился</b>")
# Если введено кол-во товаров меньше 1 или меньше кол-ва имеющегося в наличии
if get_count < 1 or get_count > len(get_items):
return await message.answer(
f"<b>❌ Неверное количество товаров</b>\n" + send_message,
reply_markup=products_return_finl(position_id, get_position.category_id),
)
# Если баланс пользователя меньше, чем общая цена покупки
if get_user.user_balance < amount_pay:
return await message.answer(
f"<b>❌ Недостаточно средств на счете</b>\n" + send_message,
reply_markup=products_return_finl(position_id, get_position.category_id),
)
await state.clear()
await message.answer(
ded(f"""
<b>🎁 Вы действительно хотите купить товар(ы)?</b>
➖➖➖➖➖➖➖➖➖➖
▪️ Товар: <code>{get_position.position_name}</code>
▪️ Количество: <code>{get_count}шт</code>
▪️ Сумма к покупке: <code>{amount_pay}₽</code>
"""),
reply_markup=products_buy_confirm_finl(position_id, get_position.category_id, get_count),
)
# Подтверждение покупки товара
@router.callback_query(F.data.startswith("buy_item_confirm:"))
async def user_buy_confirm(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
position_id = int(call.data.split(":")[1])
purchase_count = int(call.data.split(":")[2])
await call.message.edit_text("")
purchase_result = await Purchasesx().buy(
user_id=call.from_user.id,
position_id=position_id,
requested_count=purchase_count,
)
if purchase_result == "USER_NOT_FOUND":
return await call.message.edit_text("<b>❌ Пользователь не был найден</b>")
elif purchase_result == "POSITION_NOT_FOUND":
return await call.message.edit_text("<b>❌ Позиция не была найдена</b>")
elif purchase_result == "NOT_ENOUGH_ITEMS":
return await call.message.edit_text("<b>❌ В наличии недостаточно товаров. Попробуйте другое кол-во</b>")
elif purchase_result == "NOT_ENOUGH_BALANCE":
return await call.message.edit_text("<b>❌ На вашем балансе недостаточно средств</b>")
get_user = await Userx().get_required(user_id=call.from_user.id)
get_settings = await Settingsx().get()
for items in purchase_result.items:
await call.message.answer("\n\n".join(items), parse_mode="None")
await asyncio.sleep(0.3)
await del_message(call.message)
await call.message.answer(
ded(f"""
<b>✅ Вы успешно купили товар(ы)</b>
➖➖➖➖➖➖➖➖➖➖
▪️ Чек: <code>#{purchase_result.receipt}</code>
▪️ Товар: <code>{purchase_result.position_name} | {purchase_result.purchase_count}шт | {purchase_result.purchase_price}₽</code>
▪️ Дата покупки: <code>{convert_date(purchase_result.purchase_unix)}</code>
"""),
reply_markup=menu_frep(call.from_user.id),
)
if get_settings.notification_buy == "True":
await send_admins(
bot,
ded(f"""
<b>🎁 Покупка товара</b>
▪️ Пользователь: <b>@{get_user.user_login}</b> | <a href='tg://user?id={get_user.user_id}'>{get_user.user_name}</a> | <code>{get_user.user_id}</code>
▪️ Товар: <code>{purchase_result.position_name} | {purchase_result.purchase_count}шт | {purchase_result.purchase_price}₽</code>
▪️ Чек: <code>#{purchase_result.receipt}</code>
""")
)
+407
View File
@@ -0,0 +1,407 @@
# - *- coding: utf- 8 - *-
from typing import Optional, Tuple
from aiogram import Router, Bot, F
from aiogram.filters import StateFilter
from aiogram.types import CallbackQuery, Message, PreCheckoutQuery
from tgbot.database import Paymentsx, Refillx, Userx, Settingsx
from tgbot.keyboards.inline_user import refill_bill_finl, refill_method_finl
from tgbot.services.api_cryptobot import CryptobotAPI
from tgbot.services.api_stars import StarsAPI
from tgbot.services.api_yoomoney import YoomoneyAPI
from tgbot.utils.const_functions import is_number, to_number, gen_id, ded
from tgbot.utils.misc.bot_logging import bot_logger
from tgbot.utils.misc.bot_models import FSM, ARS
from tgbot.utils.misc_functions import send_admins
min_refill_rub = 5 # Минимальная сумма пополнения в рублях
router = Router(name=__name__)
# Выбор способа пополнения
@router.callback_query(F.data == "user_refill")
async def refill_method_list(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
get_payments = await Paymentsx().get()
if (
get_payments.status_cryptobot == "False" and
get_payments.status_yoomoney == "False" and
get_payments.status_stars == "False"
):
return await call.answer("❗️ Пополнения временно недоступны", True)
await call.message.edit_text(
"<b>💰 Выберите способ пополнения баланса</b>",
reply_markup=await refill_method_finl(),
)
# Выбор способа пополнения
@router.callback_query(F.data.startswith("user_refill_method:"))
async def refill_method_select(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
refill_method = call.data.split(":")[1]
get_payments = await Paymentsx().get()
if refill_method == "Cryptobot" and get_payments.status_cryptobot == "False":
return await call.answer("❌ Пополнение данным способом временно недоступно", True)
elif refill_method == "Yoomoney" and get_payments.status_yoomoney == "False":
return await call.answer("❌ Пополнение данным способом временно недоступно", True)
elif refill_method == "Stars" and get_payments.status_stars == "False":
return await call.answer("❌ Пополнение данным способом временно недоступно", True)
await state.update_data(here_refill_method=refill_method)
await state.set_state("here_refill_amount")
await call.message.edit_text("<b>💰 Введите сумму пополнения</b>")
################################################################################
################################### ВВОД СУММЫ #################################
# Принятие суммы для пополнения средств
@router.message(F.text, StateFilter("here_refill_amount"))
async def refill_amount_get(message: Message, bot: Bot, state: FSM, arSession: ARS):
if not is_number(message.text):
return await message.answer(
ded(f"""
<b>❌ Данные были введены неверно</b>
💰 Введите сумму для пополнения средств
"""),
)
if to_number(message.text) < min_refill_rub or to_number(message.text) > 150_000:
return await message.answer(
ded(f"""
<b>❌ Неверная сумма пополнения</b>
❗️ Cумма не должна быть меньше <code>{min_refill_rub}₽</code> и больше <code>150 000₽</code>
💰 Введите сумму для пополнения средств
"""),
)
cache_message = await message.answer("<b>♻️ Подождите, платёж генерируется..</b>")
refill_amount = to_number(message.text)
refill_method = (await state.get_data())['here_refill_method']
await state.clear()
# Генерация платежа
if refill_method == "Cryptobot":
bill_message, bill_link, bill_receipt = await (
await CryptobotAPI.connect(
bot=bot,
arSession=arSession,
update=cache_message,
)
).bill(refill_amount)
elif refill_method == "Yoomoney":
bill_message, bill_link, bill_receipt = await (
await YoomoneyAPI.connect(
bot=bot,
arSession=arSession,
update=cache_message,
)
).bill(refill_amount)
elif refill_method == "Stars":
bill_message, bill_link, bill_receipt = await (
await StarsAPI.connect(
bot=bot,
arSession=arSession,
update=cache_message,
)
).bill(refill_amount)
else:
return await cache_message.edit_text(
f"<b>❌ Данный способ пополнения не найден. Попробуйте позже: {refill_method}</b>"
)
# Обработка статуса генерации платежа
if bill_message:
await cache_message.edit_text(
bill_message,
reply_markup=refill_bill_finl(bill_link, bill_receipt, refill_method),
)
else:
await cache_message.edit_text(
f"<b>❌ Не удалось сгенерировать платёж. Попробуйте позже</b>"
)
################################################################################
############################### ПРОВЕРКА ПЛАТЕЖЕЙ ##############################
# Проверка оплаты - ЮMoney
@router.callback_query(F.data.startswith('Pay:Yoomoney'))
async def refill_check_yoomoney(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
pay_method = call.data.split(":")[1]
pay_receipt = call.data.split(":")[2]
pay_status, pay_amount = await (
await YoomoneyAPI.connect(
bot=bot,
arSession=arSession,
update=call,
)
).bill_check(pay_receipt)
if pay_status == 0:
refill_status = await refill_success(
bot=bot,
call=call,
pay_method=pay_method,
pay_amount=pay_amount,
pay_receipt=int(pay_receipt),
pay_comment=pay_receipt,
)
if refill_status == "ALREADY":
await call.answer("❗ Ваше пополнение уже зачислено.", True, cache_time=60)
await delete_refill_message(bot, call.message.chat.id, call.message.message_id)
elif refill_status == "USER_NOT_FOUND":
await call.answer("❗ Пользователь не найден. Напишите в поддержку.", True, cache_time=30)
elif pay_status == 1:
await call.answer("❗️ Не удалось проверить платёж. Попробуйте позже", True, cache_time=30)
elif pay_status == 2:
await call.answer("❗️ Оплата не была найдена. Попробуйте позже", True, cache_time=5)
elif pay_status == 3:
await call.answer("❗️ Оплата была произведена не в рублях", True, cache_time=5)
else:
await call.answer(f"❗ Неизвестная ошибка {pay_status}. Обратитесь в поддержку.", True, cache_time=5)
# Проверка оплаты - Cryptobot
@router.callback_query(F.data.startswith('Pay:Cryptobot'))
async def refill_check_cryptobot(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
pay_method = call.data.split(":")[1]
pay_comment = call.data.split(":")[2]
pay_status, pay_amount = await (
await CryptobotAPI.connect(
bot=bot,
arSession=arSession,
update=call,
)
).bill_check(pay_comment)
if pay_status == 0:
refill_status = await refill_success(
bot=bot,
call=call,
pay_method=pay_method,
pay_amount=pay_amount,
pay_comment=pay_comment,
)
if refill_status == "ALREADY":
await call.answer("❗ Ваше пополнение уже зачислено.", True, cache_time=60)
await delete_refill_message(bot, call.message.chat.id, call.message.message_id)
elif refill_status == "USER_NOT_FOUND":
await call.answer("❗ Пользователь не найден. Напишите в поддержку.", True, cache_time=30)
elif pay_status == 1:
await call.answer("❗️ Не удалось проверить платёж. Попробуйте позже", True, cache_time=30)
elif pay_status == 2:
await call.answer("❗️ Оплата не была найдена. Попробуйте позже", True, cache_time=5)
elif pay_status == 3:
await call.answer("❗️ Вы не успели оплатить счёт", True, cache_time=5)
await call.message.edit_reply_markup()
else:
await call.answer(f"❗ Неизвестная ошибка {pay_status}. Обратитесь в поддержку.", True, cache_time=5)
# Проверка оплаты - Звёзды
@router.callback_query(F.data.startswith('Pay:Stars'))
async def refill_check_stars(call: CallbackQuery, bot: Bot, state: FSM, arSession: ARS):
pay_method = call.data.split(":")[1]
pay_receipt = int(call.data.split(":")[2])
pay_status, pay_amount = await (
await StarsAPI.connect(
bot=bot,
arSession=arSession,
update=call,
)
).bill_check(pay_receipt)
if pay_status == 0:
refill_status = await refill_success(
bot=bot,
call=call,
pay_method=pay_method,
pay_amount=pay_amount,
pay_receipt=pay_receipt,
)
if refill_status == "ALREADY":
await call.answer("❗ Ваше пополнение уже зачислено.", True, cache_time=60)
await delete_refill_message(bot, call.message.chat.id, call.message.message_id)
elif refill_status == "USER_NOT_FOUND":
await call.answer("❗ Пользователь не найден. Напишите в поддержку.", True, cache_time=30)
elif pay_status == 1:
await call.answer("❗️ Не удалось проверить платёж. Попробуйте позже", True, cache_time=30)
elif pay_status == 2:
await call.answer("❗️ Оплата не была найдена. Попробуйте позже", True, cache_time=5)
else:
await call.answer(f"❗ Неизвестная ошибка {pay_status}. Обратитесь в поддержку.", True, cache_time=5)
################################################################################
#################################### ЗВЁЗДЫ ####################################
# Подтверждение платежа Telegram Stars
@router.pre_checkout_query()
async def refill_stars_pre_checkout(query: PreCheckoutQuery, bot: Bot, state: FSM, arSession: ARS):
await (
await StarsAPI.connect(
bot=bot,
arSession=arSession,
update=query,
)
).answer_pre_checkout(query)
# Автоматическое зачисление Telegram Stars
@router.message(F.successful_payment)
async def refill_stars_success(message: Message, bot: Bot, state: FSM, arSession: ARS):
payment = message.successful_payment
if payment is None:
return
stars_api = await StarsAPI.connect(
bot=bot,
arSession=arSession,
update=message,
)
try:
pay_receipt, pay_amount, pay_comment, bill_chat_id, bill_message_id = (
stars_api.parse_successful_payment(payment)
)
except ValueError:
bot_logger.warning("Некорректная successful_payment для Telegram Stars", exc_info=True)
return
refill_status, receipt = await save_refill_success(
bot=bot,
user_id=message.from_user.id,
pay_method="Stars",
pay_amount=pay_amount,
pay_receipt=pay_receipt,
pay_comment=pay_comment,
)
if refill_status == "ok":
if bill_chat_id == message.chat.id:
await delete_refill_message(bot, bill_chat_id, bill_message_id)
await message.answer(
ded(f"""
<b>💰 Вы пополнили баланс на сумму <code>{pay_amount}₽</code>. Удачи ❤️
🧾 Чек: <code>#{receipt}</code></b>
""")
)
elif refill_status == "ALREADY":
if bill_chat_id == message.chat.id:
await delete_refill_message(bot, bill_chat_id, bill_message_id)
await message.answer("<b>❗ Ваше пополнение уже было зачислено.</b>")
elif refill_status == "USER_NOT_FOUND":
await message.answer("<b>❗ Пользователь не найден. Напишите в поддержку.</b>")
################################################################################
#################################### ПРОЧЕЕ ####################################
# Зачисление средств
async def refill_success(
bot: Bot,
call: CallbackQuery,
pay_method: str,
pay_amount: float,
pay_receipt: Optional[int] = None,
pay_comment: Optional[str] = None,
):
user_id = call.from_user.id
if pay_receipt is None:
pay_receipt = gen_id(12)
if pay_comment is None:
pay_comment = ""
response_success, receipt = await save_refill_success(
bot=bot,
user_id=user_id,
pay_method=pay_method,
pay_amount=pay_amount,
pay_receipt=pay_receipt,
pay_comment=pay_comment,
)
if response_success != "ok":
return response_success
await call.message.answer(
ded(f"""
<b>💰 Вы пополнили баланс на сумму <code>{pay_amount}₽</code>. Удачи ❤️
🧾 Чек: <code>#{receipt}</code></b>
""")
)
await delete_refill_message(bot, call.message.chat.id, call.message.message_id)
return response_success
# Удаление сообщения со счётом
async def delete_refill_message(bot: Bot, chat_id: Optional[int], message_id: Optional[int]) -> None:
if chat_id is None or message_id is None:
return
try:
await bot.delete_message(chat_id=chat_id, message_id=message_id)
except Exception:
bot_logger.warning("Не удалось удалить сообщение со счётом", exc_info=True)
# Сохранение пополнения и уведомление админов
async def save_refill_success(
bot: Bot,
user_id: int,
pay_method: str,
pay_amount: float,
pay_receipt: int,
pay_comment: str,
) -> Tuple[str, int]:
if pay_method == "Yoomoney":
text_method = "ЮMoney"
elif pay_method == "Cryptobot":
text_method = "CryptoBot"
elif pay_method == "Stars":
text_method = "Telegram Stars"
else:
text_method = f"Unknown - {pay_method}"
response_success = await Refillx().success(
user_id=user_id,
pay_receipt=pay_receipt,
pay_comment=pay_comment,
pay_amount=pay_amount,
pay_method=pay_method,
)
if response_success != "ok":
return response_success, pay_receipt
get_user = await Userx().get_required(user_id=user_id)
get_settings = await Settingsx().get()
if get_settings.notification_refill == "True":
await send_admins(
bot,
ded(f"""
<b>💰 Пополнение баланса</b>
▪️ Пользователь: <b>@{get_user.user_login}</b> | <a href='tg://user?id={user_id}'>{get_user.user_name}</a> | <code>{user_id}</code>
▪️ Сумма пополнения: <code>{pay_amount}₽</code> <code>({text_method})</code>
▪️ Чек: <code>#{pay_receipt}</code>
""")
)
return response_success, pay_receipt