Compare commits

..

3 Commits

98
main.py
View File

@ -47,7 +47,7 @@ main_keyboard = InlineKeyboardMarkup(inline_keyboard=[
[
InlineKeyboardButton(text='Моя статистика', callback_data='stats'),
InlineKeyboardButton(text='Создать заявку на вывод средств', callback_data='withdraw')
],
]
])
# Вместо загрузки из файла будем хранить кэш токенов пользователей
@ -82,14 +82,15 @@ async def render_links_page(page: int = 0, token: str = None):
start = page * LINKS_PER_PAGE
end = start + LINKS_PER_PAGE
page_links = links[start:end]
header = f"{'ref':<36} | description"
sep = '-' * 36 + '-|-' + '-' * 30
header = f"{'ref':<36} | {'promocode':<10} | description"
sep = '-' * 36 + '-|-' + '-' * 10 + '-|-' + '-' * 30
rows = []
for item in page_links:
ref = item['ref']
promocode = item.get('promocode', '')
description = item['description']
url = f"https://{item['ref']}"
rows.append(f"{ref:<36} | <a href=\"{url}\">{description}</a>")
rows.append(f"{ref:<36} | {promocode:<10} | <a href=\"{url}\">{description}</a>")
if not rows:
table = 'Нет ссылок.'
else:
@ -175,6 +176,9 @@ class LinkStates(StatesGroup):
waiting_for_description = State()
link_created = State()
class WithdrawStates(StatesGroup):
waiting_for_amount = State()
@dp.callback_query(F.data == 'create_link')
async def create_link(callback: types.CallbackQuery, state: FSMContext):
sent = await callback.message.edit_text(
@ -207,7 +211,6 @@ async def process_new_link_description(message: types.Message, state: FSMContext
headers = {"Authorization": f"Bearer {token}"}
data = await state.get_data()
desc_msg_id = data.get('desc_msg_id')
# Убираем кнопки у сообщения с просьбой ввести описание
if desc_msg_id:
try:
await message.bot.edit_message_reply_markup(
@ -222,7 +225,8 @@ async def process_new_link_description(message: types.Message, state: FSMContext
if resp.status == 200:
data = await resp.json()
ref = data.get('ref')
text = f"Новая ссылка успешно создана!\n\n<pre>ref: {ref}\ndescription: {description}</pre>"
promocode = data.get('promocode')
text = f"Новая ссылка успешно создана!\n\n<pre>ref: {ref}\npromocode: {promocode}\ndescription: {description}</pre>"
keyboard = InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='Назад', callback_data='back_to_links_from_success')]]
)
@ -242,8 +246,86 @@ async def back_to_links_from_success(callback: types.CallbackQuery, state: FSMCo
await callback.answer()
@dp.callback_query(F.data == 'withdraw')
async def not_implemented_withdraw(callback: types.CallbackQuery):
await callback.answer('Функция вывода средств пока не реализована.', show_alert=True)
async def withdraw_funds(callback: types.CallbackQuery, state: FSMContext):
"""
Запрашивает сумму для вывода средств.
"""
sent = await callback.message.edit_text(
'Введите сумму для вывода:',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='Назад', callback_data='back_to_main_from_withdraw')]]
)
)
await state.set_state(WithdrawStates.waiting_for_amount)
await state.update_data(withdraw_msg_id=sent.message_id)
await callback.answer()
@dp.callback_query(F.data == 'back_to_main_from_withdraw', WithdrawStates.waiting_for_amount)
async def back_to_main_from_withdraw(callback: types.CallbackQuery, state: FSMContext):
await callback.message.edit_text(WELCOME_TEXT, reply_markup=main_keyboard)
await state.clear()
await callback.answer()
@dp.message(WithdrawStates.waiting_for_amount)
async def process_withdraw_amount(message: types.Message, state: FSMContext):
try:
amount = float(message.text.strip())
if amount <= 0:
await message.answer('Сумма для вывода должна быть положительной.')
return
except ValueError:
await message.answer('Пожалуйста, введите корректное число для суммы.')
return
tg_id = message.from_user.id
token = user_tokens.get(tg_id)
if not token:
await message.answer('Ошибка авторизации. Пожалуйста, перезапустите бота командой /start.')
await state.clear()
return
headers = {"Authorization": f"Bearer {token}"}
data = await state.get_data()
withdraw_msg_id = data.get('withdraw_msg_id')
if withdraw_msg_id:
try:
await message.bot.edit_message_reply_markup(
chat_id=message.chat.id,
message_id=withdraw_msg_id,
reply_markup=None
)
except Exception:
pass
async with aiohttp.ClientSession() as session:
try:
async with session.post(f'{API_URL}/withdraw', json={'tg_id': tg_id, 'amount': amount}, headers=headers) as resp:
if resp.status == 200:
response_data = await resp.json()
transaction_id = response_data.get('transaction_id')
await message.answer(
f'Запрос на вывод средств успешно создан!\nСумма: {amount:.2f}\nID транзакции: {transaction_id}',
reply_markup=InlineKeyboardMarkup(
inline_keyboard=[[InlineKeyboardButton(text='Назад', callback_data='back_to_main')]]
)
)
else:
error_detail = 'Неизвестная ошибка'
try:
error_json = await resp.json()
if 'detail' in error_json:
error_detail = error_json['detail']
except Exception:
pass
await message.answer(f'Ошибка при создании заявки на вывод средств: {error_detail}')
except aiohttp.ClientConnectorError:
await message.answer('Не удалось подключиться к серверу API. Пожалуйста, попробуйте позже.')
except Exception as e:
await message.answer(f'Произошла непредвиденная ошибка: {e}')
await state.clear()
@dp.callback_query(F.data == 'question')
async def not_implemented_question(callback: types.CallbackQuery):