изменена логика поиска ключей в базе данных

This commit is contained in:
Vlad
2024-09-25 01:45:37 +03:00
parent ecad56e445
commit 11d30fe58b
7 changed files with 36 additions and 130 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30 -76
View File
@@ -29,7 +29,8 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery):
for record in records:
key_name = record['email']
client_id = record['client_id']
button = types.InlineKeyboardButton(text=key_name, callback_data=f'view_key_{key_name}_{client_id}')
# Заменяем подчеркивание на вертикальную черту в callback_data
button = types.InlineKeyboardButton(text=key_name, callback_data=f'view_key|{key_name}|{client_id}')
buttons.append([button])
# Создаем клавиатуру с кнопками
@@ -58,10 +59,11 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery):
await callback_query.answer()
@router.callback_query(lambda c: c.data.startswith('view_key_'))
@router.callback_query(lambda c: c.data.startswith('view_key|'))
async def process_callback_view_key(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
key_name, client_id = callback_query.data.split('_')[2], callback_query.data.split('_')[3]
# Разделяем данные по вертикальной черте
key_name, client_id = callback_query.data.split('|')[1], callback_query.data.split('|')[2]
try:
conn = await asyncpg.connect(DATABASE_URL)
@@ -85,9 +87,9 @@ async def process_callback_view_key(callback_query: types.CallbackQuery):
f"{days_left_message}")
# Кнопки для продления, инструкций и удаления
renew_button = types.InlineKeyboardButton(text='Продлить ключ', callback_data=f'renew_key_{client_id}')
renew_button = types.InlineKeyboardButton(text='Продлить ключ', callback_data=f'renew_key|{client_id}')
instructions_button = types.InlineKeyboardButton(text='Инструкции по использованию', callback_data='instructions')
delete_button = types.InlineKeyboardButton(text='Удалить ключ', callback_data=f'delete_key_{client_id}')
delete_button = types.InlineKeyboardButton(text='Удалить ключ', callback_data=f'delete_key|{client_id}')
back_button = types.InlineKeyboardButton(text='Назад в профиль', callback_data='view_profile')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[renew_button], [instructions_button], [delete_button], [back_button]])
@@ -104,62 +106,25 @@ async def process_callback_view_key(callback_query: types.CallbackQuery):
await callback_query.answer()
# Обработка запроса на удаление ключа
@router.callback_query(lambda c: c.data.startswith('delete_key_'))
@router.callback_query(lambda c: c.data.startswith('delete_key|'))
async def process_callback_delete_key(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
client_id = callback_query.data.split('_')[2]
client_id = callback_query.data.split('|')[1] # Используем разделитель вертикальная черта
confirmation_keyboard = types.InlineKeyboardMarkup(inline_keyboard=[
[types.InlineKeyboardButton(text='Да, удалить', callback_data=f'confirm_delete_{client_id}')],
[types.InlineKeyboardButton(text='Да, удалить', callback_data=f'confirm_delete|{client_id}')],
[types.InlineKeyboardButton(text='Нет, отменить', callback_data='view_keys')]
])
await bot.edit_message_text("Вы уверены, что хотите удалить ключ?", chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=confirmation_keyboard)
await callback_query.answer()
@router.callback_query(lambda c: c.data.startswith('confirm_delete_'))
async def process_callback_confirm_delete(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
client_id = callback_query.data.split('_')[2]
try:
conn = await asyncpg.connect(DATABASE_URL)
try:
record = await conn.fetchrow('SELECT email FROM keys WHERE client_id = $1', client_id)
if record:
email = record['email']
session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD)
success = delete_client(session, client_id)
if success:
await conn.execute('DELETE FROM keys WHERE client_id = $1', client_id)
response_message = "Ключ был успешно удален."
else:
response_message = "Ошибка при удалении клиента через API."
else:
response_message = "Ключ не найден или уже удален."
back_button = types.InlineKeyboardButton(text='Назад', callback_data='view_keys')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]])
await bot.edit_message_text(response_message, chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=keyboard)
finally:
await conn.close()
except Exception as e:
await bot.edit_message_text(f"Ошибка при удалении ключа: {e}", chat_id=tg_id, message_id=callback_query.message.message_id)
await callback_query.answer()
@router.callback_query(lambda c: c.data.startswith('renew_key_'))
# Подтверждение удаления
@router.callback_query(lambda c: c.data.startswith('renew_key|'))
async def process_callback_renew_key(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
client_id = callback_query.data.split('_')[2]
client_id = callback_query.data.split('|')[1] # Используем разделитель вертикальная черта
try:
conn = await asyncpg.connect(DATABASE_URL)
@@ -169,32 +134,19 @@ async def process_callback_renew_key(callback_query: types.CallbackQuery):
if record:
email = record['email']
expiry_time = record['expiry_time']
current_time = datetime.utcnow().timestamp() * 1000
if expiry_time <= current_time:
# Кнопка для удаления ключа и возврата в профиль
delete_button = types.InlineKeyboardButton(text='Удалить ключ', callback_data=f'delete_key_{client_id}')
back_button = types.InlineKeyboardButton(text='Назад в профиль', callback_data='view_profile')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[delete_button], [back_button]])
await bot.edit_message_text(
"Ваш ключ уже истек и не может быть продлен.",
chat_id=tg_id,
message_id=callback_query.message.message_id,
reply_markup=keyboard
)
return
current_time = datetime.utcnow().timestamp() * 1000 # Получаем текущее время в миллисекундах
# Убираем проверку на истекший ключ
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[
[types.InlineKeyboardButton(text='Продлить на 1 месяц (100 руб.)', callback_data=f'renew_1_month_{client_id}')],
[types.InlineKeyboardButton(text='Продлить на 3 месяца (250 руб.)', callback_data=f'renew_3_months_{client_id}')],
[types.InlineKeyboardButton(text='Продлить на 1 месяц (100 руб.)', callback_data=f'renew_plan|1|{client_id}')],
[types.InlineKeyboardButton(text='Продлить на 3 месяца (250 руб.)', callback_data=f'renew_plan|3|{client_id}')],
[types.InlineKeyboardButton(text='Назад', callback_data='view_profile')]
])
balance = await get_balance(tg_id)
response_message = (f"Выберите план продления:\n"
f"Баланс: <b>{balance} руб.</b>\n"
f"Действующий ключ истекает <b>{datetime.utcfromtimestamp(expiry_time / 1000).strftime('%Y-%m-%d %H:%M:%S')}</b>")
f"Текущая дата истечения ключа: <b>{datetime.utcfromtimestamp(expiry_time / 1000).strftime('%Y-%m-%d %H:%M:%S')}</b>")
await bot.edit_message_text(response_message, chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=keyboard, parse_mode="HTML")
@@ -207,10 +159,10 @@ async def process_callback_renew_key(callback_query: types.CallbackQuery):
await callback_query.answer()
# Обработка выбора плана продления
@router.callback_query(lambda c: c.data.startswith('renew_'))
@router.callback_query(lambda c: c.data.startswith('renew_plan|'))
async def process_callback_renew_plan(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
plan, client_id = callback_query.data.split('_')[1], callback_query.data.split('_')[3] # '1' или '3' и client_id
plan, client_id = callback_query.data.split('|')[1], callback_query.data.split('|')[2] # '1' или '3' и client_id
days_to_extend = 30 * int(plan)
try:
@@ -221,38 +173,42 @@ async def process_callback_renew_plan(callback_query: types.CallbackQuery):
if record:
email = record['email']
expiry_time = record['expiry_time']
current_time = datetime.utcnow().timestamp() * 1000
current_time = datetime.utcnow().timestamp() * 1000 # Текущее время в миллисекундах
if expiry_time <= current_time:
# Если ключ уже истек, он не может быть продлен
await bot.edit_message_text("Ваш ключ уже истек и не может быть продлен.", chat_id=tg_id, message_id=callback_query.message.message_id)
return
# Рассчитываем новую дату истечения
new_expiry_time = int(expiry_time + timedelta(days=days_to_extend).total_seconds() * 1000)
cost = 100 if plan == '1' else 250
balance = await get_balance(tg_id)
if balance < cost:
replenish_button = types.InlineKeyboardButton(text='Пополнить баланс', callback_data='replenish_balance')
back_button = types.InlineKeyboardButton(text='Назад', callback_data='view_keys')
back_button = types.InlineKeyboardButton(text='Назад', callback_data='view_profile')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[replenish_button], [back_button]])
await bot.edit_message_text("Недостаточно средств для продления ключа.", chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=keyboard)
return
# Продлеваем ключ через API
session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD)
success = extend_client_key(session, tg_id, client_id, email, new_expiry_time)
if success:
# Обновляем баланс и ключ в базе данных
await update_balance(tg_id, -cost)
await conn.execute('UPDATE keys SET expiry_time = $1 WHERE client_id = $2', new_expiry_time, client_id)
response_message = f"Ваш ключ был успешно продлен на {days_to_extend // 30} месяц(-)."
back_button = types.InlineKeyboardButton(text='Назад', callback_data='view_keys')
response_message = f"Ваш ключ был успешно продлен на {days_to_extend // 30} месяц(-а)."
back_button = types.InlineKeyboardButton(text='Назад', callback_data='view_profile')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[back_button]])
await bot.edit_message_text(response_message, chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=keyboard)
else:
await bot.edit_message_text("Ошибка при продлении ключа.", chat_id=tg_id, message_id=callback_query.message.message_id)
else:
await bot.edit_message_text("У вас нет ключей для продления.", chat_id=tg_id, message_id=callback_query.message.message_id)
await bot.edit_message_text("Ключ не найден.", chat_id=tg_id, message_id=callback_query.message.message_id)
finally:
await conn.close()
@@ -262,7 +218,5 @@ async def process_callback_renew_plan(callback_query: types.CallbackQuery):
await callback_query.answer()
# Обработка ошибок
async def handle_error(tg_id, callback_query, message):
await bot.edit_message_text(message, chat_id=tg_id, message_id=callback_query.message.message_id)
await bot.edit_message_text(message, chat_id=tg_id, message_id=callback_query.message.message_id)
+4 -13
View File
@@ -217,10 +217,9 @@ async def process_admin_confirmation(callback_query: types.CallbackQuery, state:
try:
await bot.delete_message(chat_id=user_id, message_id=requisites_message_id)
except Exception as e:
print(f"Ошибка при удалении сообщения с реквизитами: {e}")
print(f"Ошибка при удалении сообщения: {e}")
finally:
# Закрываем соединение с базой данных
await conn.close()
elif action == 'decline':
@@ -231,14 +230,6 @@ async def process_admin_confirmation(callback_query: types.CallbackQuery, state:
await send_message_with_deletion(callback_query.from_user.id, f"Ошибка при пополнении баланса: {e}", state=state, message_key='admin_error_message_id')
print(f"Ошибка при пополнении баланса: {e}")
await state.clear()
await callback_query.answer()
@router.message(lambda m: m.text and m.text.startswith('Недостаточно средств для продления'))
async def handle_insufficient_funds(message: types.Message):
user_id = message.from_user.id
replenish_keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Пополнить баланс', callback_data='replenish_balance')]
])
await send_message_with_deletion(user_id, "Ваш баланс недостаточен для продления ключа. Пожалуйста, пополните баланс.", reply_markup=replenish_keyboard, state=None, message_key='insufficient_funds_message_id')
finally:
await state.clear()
await callback_query.answer()
+2 -39
View File
@@ -19,8 +19,6 @@ from database import (add_connection, get_balance, has_active_key, store_key,
update_balance)
from handlers.profile import process_callback_view_profile
from handlers.start import start_command
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton
router = Router()
@@ -89,12 +87,6 @@ async def cancel_create_key(callback_query: CallbackQuery, state: FSMContext):
await process_callback_view_profile(callback_query, state)
await callback_query.answer()
def start_keyboard():
keyboard = ReplyKeyboardMarkup(resize_keyboard=True)
start_button = KeyboardButton(text='/start')
keyboard.add(start_button)
return keyboard
# Обработка текстовых сообщений
@dp.message()
async def handle_text(message: Message, state: FSMContext):
@@ -114,16 +106,10 @@ async def handle_text(message: Message, state: FSMContext):
if message.text in ["/start", "Меню"]:
await start_command(message)
return
if message.text.lower() == "карина кринж":
await message.answer("Это и так всем понятно, но лучше займемся доступом к впн. Кстати, с днем рождения!")
return
if current_state == Form.waiting_for_key_name.state:
await handle_key_name_input(message, state)
await message.answer("Выберите действие:", reply_markup=start_keyboard())
async def handle_key_name_input(message: Message, state: FSMContext):
tg_id = message.from_user.id
@@ -258,27 +244,4 @@ async def renew_expired_keys():
])
await bot.send_message(tg_id, "Ваш баланс недостаточен для продления ключа. Пожалуйста, пополните баланс.", reply_markup=replenish_keyboard)
await asyncio.sleep(3600)
async def notify_expiring_keys():
while True:
current_time = datetime.utcnow()
threshold_time = int((current_time + timedelta(hours=10)).timestamp() * 1000)
conn = await asyncpg.connect(DATABASE_URL)
try:
# Получаем пользователей с истекающими ключами
expiring_keys = await conn.fetch('SELECT tg_id, expiry_time FROM keys WHERE expiry_time <= $1', threshold_time)
for record in expiring_keys:
tg_id = record['tg_id']
expiry_time = record['expiry_time']
# Отправляем уведомление пользователю
await bot.send_message(tg_id, f"🔔 Ваш ключ истекает через 10 часов. Пожалуйста, продлите его, чтобы избежать отключения.")
finally:
await conn.close()
await asyncio.sleep(3600) # Проверяем каждый час
await asyncio.sleep(3600)
-2
View File
@@ -2,12 +2,10 @@ import asyncio
from bot import bot, dp, router
from database import init_db
from key_management import notify_expiring_keys
async def main():
await init_db()
asyncio.create_task(notify_expiring_keys())
dp.include_router(router) # Подключение роутера
await dp.start_polling(bot) # Запуск поллинга