feat: Implement payment notification system and API structure

- Added notifications for successful payments in `api/core/notifications.py`.
- Created main API entry point in `api/main.py` with FastAPI integration.
- Established routing structure in `api/routes/__init__.py` and `api/routes/pally.py` for handling payment callbacks.
- Developed billing handlers in `bot/handlers/billing.py` and `bot/handlers/buy.py` for subscription management.
- Introduced state management for user interactions in `bot/states/`.
- Created user interface elements in `bot/keyboards/` for navigation and payment processing.
- Set up middleware for dependency injection in `bot/middlewares/di.py`.
- Added support for user commands and interactions in `bot/handlers/common.py` and `bot/handlers/support.py`.
- Implemented logging and error handling throughout the bot's functionality.
- Created entry point script for API server in `entrypoints/api.sh`.
This commit is contained in:
2026-04-24 17:41:42 +07:00
parent d98383285e
commit 049f31118d
37 changed files with 292 additions and 41 deletions

19
bot/handlers/__init__.py Normal file
View File

@@ -0,0 +1,19 @@
from .ads import router as ads_router
from .billing import router as billing_router
from .buy import router as buy_router
from .common import router as common_router
from .menus import router as menus_router
from .prehandling import router as prehandling_router
from .referals import router as referal_router
from .support import router as support_router
routers = [
prehandling_router,
referal_router,
billing_router,
menus_router,
ads_router,
support_router,
buy_router,
common_router,
]

5
bot/handlers/ads.py Normal file
View File

@@ -0,0 +1,5 @@
from aiogram import Router
router = Router()
# FIXME: Refine newsletter system

49
bot/handlers/billing.py Normal file
View File

@@ -0,0 +1,49 @@
import logging
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery
from sqlalchemy.ext.asyncio import AsyncSession
from bot.keyboards.client import pay_url, return_to_menu
from bot.states.buy import BillingStorage
from bot.texts import BILL_CREATED, BILL_CREATION, CALLBACK_FALLBACK
from schemas.billing import BillingContext, BillingProviders
from schemas.di import DependenciesDTO
router = Router()
logger = logging.getLogger(__name__)
@router.callback_query(BillingStorage.pending, F.data == "billing:pally")
async def pally_init(
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
):
data = await state.get_data()
ctx: BillingContext | None = data.get("ctx")
if not ctx:
logger.warning("ctx not found on billing choice")
await cb.message.edit_text(CALLBACK_FALLBACK, reply_markup=return_to_menu)
return
await state.clear()
ctx.provider = BillingProviders.PALLY
await cb.message.edit_text(
BILL_CREATION.format(amount=ctx.amount, provider=ctx.provider.value.title())
)
bill = await deps.billing_service.pally_initiate_payment(
session, deps.pally_client, user_id=cb.from_user.id, amount=ctx.amount
)
if not bill:
await cb.message.edit_text(CALLBACK_FALLBACK, reply_markup=return_to_menu)
logger.critical("bill creation prompted, but bill is None")
return
await cb.message.edit_text(
BILL_CREATED.format(amount=ctx.amount, provider=ctx.provider.value.title()),
reply_markup=pay_url(bill.link_page_url),
)

176
bot/handlers/buy.py Normal file
View File

@@ -0,0 +1,176 @@
import logging
import math
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery
from bot.keyboards.client import (
devices_selector,
duration_selector,
payment_gateways,
return_to_menu,
)
from bot.states.buy import BillingStorage, SubscriptionStorage
from bot.texts import (
CALLBACK_FALLBACK,
CHECKOUT_PAYMENT_CHOICE,
CONTEXT_REINITIATED,
NOTHING_PLACEHOLDER,
STANDARD_FALLBACK,
SUBSCRIPTION_DEVICE_SELECTOR,
SUBSCRIPTION_DURATION_SELECTOR,
)
from config import settings
from misc.utils import (
calculate_price,
convert_duration_to_int,
convert_int_to_duration,
get_discount,
)
from schemas.billing import BillingContext
from schemas.subscriptions import SubscriptionPlan
router = Router()
logger = logging.getLogger(__name__)
@router.callback_query(F.data == "buy")
async def buy_init(cb: CallbackQuery, state: FSMContext):
await state.clear()
ctx = SubscriptionPlan()
await cb.message.edit_text(
SUBSCRIPTION_DEVICE_SELECTOR.format(price=calculate_price(ctx)),
reply_markup=devices_selector(settings.min_devices),
)
await state.set_state(SubscriptionStorage.devices)
await state.set_data({"ctx": ctx})
@router.callback_query(F.data.startswith("devices:"))
async def device_count_select(cb: CallbackQuery, state: FSMContext):
data = await state.get_data()
await state.clear()
ctx: SubscriptionPlan | None = data.get("ctx", SubscriptionPlan())
cb_data = cb.data.split(":")
devices = int(cb_data[1]) if cb_data[1].isdigit() else settings.min_devices
ctx.devices = devices
ctx.whitelists = ctx.whitelists or devices >= settings.whitelist_device_threshold
await cb.message.edit_text(
SUBSCRIPTION_DEVICE_SELECTOR.format(price=calculate_price(ctx)),
reply_markup=devices_selector(current=ctx.devices, whitelists=ctx.whitelists),
)
await state.set_state(SubscriptionStorage.devices)
await state.set_data({"ctx": ctx})
@router.callback_query(SubscriptionStorage.devices, F.data == "whitelist:toggle")
async def toggle_whitelists(cb: CallbackQuery, state: FSMContext):
data = await state.get_data()
await state.clear()
ctx: SubscriptionPlan | None = data.get("ctx", SubscriptionPlan())
ctx.whitelists = not ctx.whitelists or ctx.devices >= settings.whitelist_device_threshold
try:
await cb.message.edit_text(
SUBSCRIPTION_DEVICE_SELECTOR.format(price=calculate_price(ctx)),
reply_markup=devices_selector(current=ctx.devices, whitelists=ctx.whitelists),
)
except Exception as exc:
if "message is not modified:" in str(exc):
await cb.answer(NOTHING_PLACEHOLDER)
else:
await cb.answer(CALLBACK_FALLBACK)
await state.set_state(SubscriptionStorage.devices)
await state.set_data({"ctx": ctx})
@router.callback_query(SubscriptionStorage.devices, F.data == "confirm")
async def select_duration_init(cb: CallbackQuery, state: FSMContext):
data = await state.get_data()
await state.clear()
ctx: SubscriptionPlan | None = data.get("ctx")
if not ctx:
await cb.answer(CALLBACK_FALLBACK)
return
try:
discount = get_discount(convert_duration_to_int(ctx.duration))
ctx.discount = 1 - discount / 100
await cb.message.edit_text(
SUBSCRIPTION_DURATION_SELECTOR.format(
price=calculate_price(ctx),
discount=math.floor(discount),
),
reply_markup=duration_selector(current=ctx.duration, back_cb=f"devices:{ctx.devices}"),
)
except Exception as exc:
if "message is not modified:" in str(exc):
await cb.answer(NOTHING_PLACEHOLDER)
else:
await cb.answer(CALLBACK_FALLBACK)
raise
await state.set_state(SubscriptionStorage.duration)
await state.set_data({"ctx": ctx})
@router.callback_query(F.data.startswith("duration:"))
async def select_duration(cb: CallbackQuery, state: FSMContext):
data = await state.get_data()
await state.clear()
ctx: SubscriptionPlan | None = data.get("ctx")
if not ctx:
await cb.answer(CONTEXT_REINITIATED)
ctx = SubscriptionPlan()
cb_data = cb.data.split(":")
duration = int(cb_data[1]) if cb_data[1].isdigit() else 1
ctx.duration = convert_int_to_duration(duration)
try:
discount = get_discount(convert_duration_to_int(ctx.duration))
ctx.discount = 1 - discount / 100
await cb.message.edit_text(
SUBSCRIPTION_DURATION_SELECTOR.format(
price=calculate_price(ctx),
discount=math.floor(discount),
),
reply_markup=duration_selector(current=ctx.duration, back_cb=f"devices:{ctx.devices}"),
)
except Exception as exc:
if "message is not modified:" in str(exc):
await cb.answer(NOTHING_PLACEHOLDER)
else:
await cb.answer(CALLBACK_FALLBACK)
raise
await state.set_state(SubscriptionStorage.duration)
await state.set_data({"ctx": ctx})
@router.callback_query(SubscriptionStorage.duration, F.data == "confirm")
async def proceed_to_checkout(cb: CallbackQuery, state: FSMContext):
data = await state.get_data()
await state.clear()
ctx: SubscriptionPlan | None = data.get("ctx")
if not ctx:
await cb.message.edit_text(STANDARD_FALLBACK, reply_markup=return_to_menu)
return
await cb.message.edit_text(
CHECKOUT_PAYMENT_CHOICE,
reply_markup=payment_gateways,
) # FIXME: temp solution that's incredibly stupid
await state.set_state(BillingStorage.pending)
billing_context = BillingContext(amount=calculate_price(ctx))
await state.set_data({"ctx": billing_context})

19
bot/handlers/common.py Normal file
View File

@@ -0,0 +1,19 @@
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message
from bot.texts import UNDEFINED_MESSAGE
router = Router()
@router.message()
async def undefined_cmd(msg: Message):
await msg.delete()
await msg.answer(UNDEFINED_MESSAGE)
@router.callback_query(F.data == "delete")
async def delete_cb(cb: CallbackQuery, state: FSMContext):
await state.clear()
await cb.message.delete()

107
bot/handlers/menus.py Normal file
View File

@@ -0,0 +1,107 @@
from aiogram import F, Router
from aiogram.filters import Command, CommandObject, CommandStart
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message
from sqlalchemy.ext.asyncio import AsyncSession
from bot.keyboards.client import close_kb, main_menu, return_to_menu
from bot.texts import FAQ_TEXT, GENERAL_PROCESSING
from misc.utils import build_main_menu_text, format_subscription_link
from schemas.di import DependenciesDTO
from services.rw import get_user_by_telegram_id
router = Router()
@router.message(CommandStart(deep_link=True, deep_link_encoded=True))
async def fetch_referal(
msg: Message,
command: CommandObject,
state: FSMContext,
session: AsyncSession,
deps: DependenciesDTO,
):
await state.clear()
data = command.args.split("_")
if not data:
await standard_start(msg, command, state)
return
referal = int(data[1])
user = await deps.user_service.add_user(
session, user_id=msg.from_user.id, referal=referal, rw_sdk=deps.rw_sdk
)
await msg.answer(
build_main_menu_text(format_subscription_link(user.subscription_link)),
reply_markup=main_menu,
)
@router.message(Command(commands=["start", "cancel"]))
async def standard_start(
msg: Message,
state: FSMContext,
session: AsyncSession,
deps: DependenciesDTO,
):
await state.clear()
user = await deps.user_service.add_user(session, user_id=msg.from_user.id, rw_sdk=deps.rw_sdk)
await msg.answer(
build_main_menu_text(format_subscription_link(user.subscription_link)),
reply_markup=main_menu,
)
@router.callback_query(F.data == "menu:main")
async def main_menu_cb(
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
):
await state.clear()
user = await deps.user_repository.get_user_by_id(session, cb.from_user.id)
await cb.message.edit_text(
build_main_menu_text(format_subscription_link(user.subscription_link)),
reply_markup=main_menu,
)
@router.callback_query(F.data == "update_link")
async def update_link(
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
):
await state.clear()
await cb.message.edit_text(GENERAL_PROCESSING)
user = await deps.user_service.update_user_link(session, cb.from_user.id, deps.rw_sdk)
await cb.answer("")
await cb.message.edit_text(
build_main_menu_text(format_subscription_link(user.subscription_link)),
reply_markup=main_menu,
)
@router.callback_query(F.data == "faq")
async def faq(cb: CallbackQuery, state: FSMContext):
await state.clear()
await cb.message.edit_text(FAQ_TEXT, reply_markup=return_to_menu)
@router.callback_query(F.data == "sub_info")
async def sub_info(
cb: CallbackQuery, state: FSMContext, deps: DependenciesDTO, session: AsyncSession
):
await state.clear()
await cb.message.edit_text(GENERAL_PROCESSING, reply_markup=close_kb)
rw_user = await get_user_by_telegram_id(deps.rw_sdk, cb.from_user.id)
user = await deps.user_service.update_user_link(session, cb.from_user.id, deps.rw_sdk)
await cb.message.edit_text(
deps.user_service.format_subscription_message(rw_user, link=user.subscription_link),
reply_markup=return_to_menu,
)

View File

@@ -0,0 +1,9 @@
from aiogram import F, Router
from aiogram.types import Message
router = Router()
@router.message(F.chat.type != "private")
async def prehandle_non_private(msg: Message):
return

28
bot/handlers/referals.py Normal file
View File

@@ -0,0 +1,28 @@
from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery
from aiogram.utils.deep_linking import create_start_link
from sqlalchemy.ext.asyncio import AsyncSession
from bot.keyboards.client import referals_kb
from bot.texts import REFERALS_MENU
from misc.utils import format_share_deep_link
from schemas.di import DependenciesDTO
router = Router()
@router.callback_query(F.data == "referal")
async def referal_menu(
cb: CallbackQuery, state: FSMContext, session: AsyncSession, deps: DependenciesDTO
):
await state.clear()
user = await deps.user_repository.get_user_by_id(session, cb.from_user.id)
referal_link = await create_start_link(cb.bot, f"ref_{user.id}", encode=True)
share_link = format_share_deep_link(referal_link)
await cb.message.edit_text(
REFERALS_MENU.format(balance=user.balance, link=referal_link),
reply_markup=referals_kb(share_link),
)

27
bot/handlers/support.py Normal file
View File

@@ -0,0 +1,27 @@
import logging
from aiogram import F, Router
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message
from bot.keyboards.client import support_url_kb
from bot.texts import SUPPORT_INIT
router = Router()
logger = logging.getLogger(__name__)
@router.callback_query(F.data == "support")
async def support_init(cb: CallbackQuery, state: FSMContext):
await state.clear()
await cb.message.edit_text(text=SUPPORT_INIT, reply_markup=support_url_kb)
@router.message(Command("support"))
async def support_init_cmd(msg: Message, state: FSMContext):
await state.clear()
await msg.delete()
await msg.answer(text=SUPPORT_INIT, reply_markup=support_url_kb)