доработка кода

This commit is contained in:
Vlad
2024-09-20 05:48:09 +03:00
parent f8015ced70
commit fe6fef3174
7 changed files with 190 additions and 52 deletions
+1
View File
@@ -5,3 +5,4 @@
/database.db
/bot_old.py
/bot_old_2.py
/database.db
+7 -7
View File
@@ -11,17 +11,18 @@ async def init_db():
client_id TEXT NOT NULL,
email TEXT NOT NULL,
expiry_time INTEGER NOT NULL,
balance REAL NOT NULL DEFAULT 0.0, -- Добавлено поле для баланса
balance REAL NOT NULL DEFAULT 0.0,
PRIMARY KEY (tg_id, client_id)
)
''')
await db.execute('''
CREATE TABLE IF NOT EXISTS keys (
tg_id INTEGER NOT NULL, -- Добавлено поле tg_id
client_id TEXT NOT NULL,
email TEXT NOT NULL,
created_at INTEGER NOT NULL,
key TEXT NOT NULL,
PRIMARY KEY (client_id)
PRIMARY KEY (tg_id, client_id) -- Изменено на (tg_id, client_id)
)
''')
await db.commit()
@@ -34,12 +35,12 @@ async def add_connection(tg_id: int, client_id: str, email: str, expiry_time: in
''', (tg_id, client_id, email, expiry_time, balance))
await db.commit()
async def store_key(client_id: str, email: str, key: str):
async def store_key(tg_id: int, client_id: str, email: str, key: str):
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute('''
INSERT INTO keys (client_id, email, created_at, key)
VALUES (?, ?, ?, ?)
''', (client_id, email, int(datetime.utcnow().timestamp() * 1000), key))
INSERT INTO keys (tg_id, client_id, email, created_at, key)
VALUES (?, ?, ?, ?, ?)
''', (tg_id, client_id, email, int(datetime.utcnow().timestamp() * 1000), key))
await db.commit()
async def get_keys(tg_id: int):
@@ -51,7 +52,6 @@ async def get_keys(tg_id: int):
''', (tg_id,)) as cursor:
return await cursor.fetchall()
async def has_active_key(tg_id: int) -> bool:
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute("SELECT COUNT(*) FROM connections WHERE tg_id = ? AND expiry_time > ?",
Binary file not shown.
Binary file not shown.
+52 -14
View File
@@ -13,21 +13,48 @@ router = Router()
async def process_callback_view_keys(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
# Создаем клавиатуру
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[
[types.InlineKeyboardButton(text='Инструкции по использованию', callback_data='instructions')],
[types.InlineKeyboardButton(text='Продлить ключ', callback_data='renew_key')],
[types.InlineKeyboardButton(text='Назад', callback_data='view_profile')]
])
try:
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute('''
SELECT email FROM connections WHERE tg_id = ?
''', (tg_id,)) as cursor:
records = await cursor.fetchall()
if records:
# Создаем кнопки для каждого ключа
buttons = []
for record in records:
key_name = record[0] # Предполагается, что email - это название ключа
button = types.InlineKeyboardButton(text=key_name, callback_data=f'view_key_{key_name}')
buttons.append([button])
# Создаем клавиатуру с кнопками
inline_keyboard = types.InlineKeyboardMarkup(inline_keyboard=buttons)
response_message = "Выберите ключ для просмотра информации:"
else:
response_message = "У вас нет ключей."
await bot.edit_message_text(response_message, chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=inline_keyboard)
except Exception as e:
await handle_error(tg_id, callback_query, f"Ошибка при получении ключей: {e}")
await callback_query.answer()
# Обработка запроса на просмотр информации о ключе
@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 = callback_query.data.split('_', 2)[2] # Получаем имя ключа
try:
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute('''
SELECT k.key, c.expiry_time
FROM keys k
JOIN connections c ON k.client_id = c.client_id
WHERE c.tg_id = ?
''', (tg_id,)) as cursor:
WHERE c.tg_id = ? AND c.email = ?
''', (tg_id, key_name)) as cursor:
record = await cursor.fetchone()
if record:
@@ -41,17 +68,28 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery):
f"Дата окончания: <b>{expiry_date.strftime('%Y-%m-%d %H:%M:%S')}</b>\n"
f"{days_left_message}")
else:
response_message = "У вас нет ключей."
# Кнопки для продления и инструкций
renew_button = types.InlineKeyboardButton(text='Продлить ключ', callback_data='renew_key')
instructions_button = types.InlineKeyboardButton(text='Инструкции по использованию', callback_data='instructions')
back_button = types.InlineKeyboardButton(text='Назад в профиль', callback_data='view_profile')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[renew_button], [instructions_button], [back_button]])
await delete_previous_message(callback_query)
await bot.send_message(tg_id, response_message, parse_mode="HTML", reply_markup=keyboard)
await bot.edit_message_text(response_message, chat_id=tg_id, message_id=callback_query.message.message_id, reply_markup=keyboard, parse_mode="HTML")
else:
await bot.edit_message_text("Информация о ключе не найдена.", chat_id=tg_id, message_id=callback_query.message.message_id, parse_mode="HTML")
except Exception as e:
await handle_error(tg_id, callback_query, f"Ошибка при получении ключей: {e}")
await handle_error(tg_id, callback_query, f"Ошибка при получении информации о ключе: {e}")
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, parse_mode="HTML")
# Обработка запроса на продление ключа
@router.callback_query(lambda c: c.data == 'renew_key')
async def process_callback_renew_key(callback_query: types.CallbackQuery):
+44 -20
View File
@@ -10,7 +10,6 @@ from handlers.profile import process_callback_view_profile
router = Router()
# Определение состояний
class ReplenishBalanceState(StatesGroup):
choosing_transfer_method = State()
choosing_amount = State()
@@ -18,7 +17,7 @@ class ReplenishBalanceState(StatesGroup):
async def send_message_with_deletion(chat_id, text, reply_markup=None, state=None, message_key='last_message_id'):
"""
Отправляет сообщение и удаляет предыдущее, если оно существует.
Отправляет новое сообщение и удаляет предыдущее сообщение (если оно существует), сохраненное в состоянии FSM.
"""
if state:
try:
@@ -29,7 +28,8 @@ async def send_message_with_deletion(chat_id, text, reply_markup=None, state=Non
await bot.delete_message(chat_id=chat_id, message_id=previous_message_id)
sent_message = await bot.send_message(chat_id=chat_id, text=text, reply_markup=reply_markup)
await state.update_data({message_key: sent_message.message_id})
if state:
await state.update_data({message_key: sent_message.message_id})
except Exception as e:
print(f"Ошибка при удалении/отправке сообщения: {e}")
@@ -43,12 +43,7 @@ async def process_callback_replenish_balance(callback_query: types.CallbackQuery
key_count = await get_key_count(tg_id)
if key_count <= 0:
await send_message_with_deletion(
tg_id,
"У вас нет ключей. Пополнение баланса возможно только при наличии ключа.",
state=state,
message_key='key_error_message_id'
)
await send_message_with_deletion(tg_id, "У вас нет ключей. Пополнение баланса возможно только при наличии ключа.", state=state, message_key='key_error_message_id')
create_key_button = InlineKeyboardButton(text='Создать ключ', callback_data='create_key')
keyboard = InlineKeyboardMarkup(inline_keyboard=[[create_key_button]])
@@ -61,7 +56,7 @@ async def process_callback_replenish_balance(callback_query: types.CallbackQuery
await state.set_state(ReplenishBalanceState.choosing_transfer_method)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='По реквизитам', callback_data='transfer_method_requisites')],
[InlineKeyboardButton(text='⬅️ Назад', callback_data='back_to_profile')]
[InlineKeyboardButton(text='⬅️ Назад', callback_data='back_to_profile')] # Кнопка "Назад"
])
await callback_query.message.edit_text(
@@ -74,6 +69,8 @@ async def process_callback_replenish_balance(callback_query: types.CallbackQuery
async def back_to_profile_handler(callback_query: types.CallbackQuery, state: FSMContext):
await process_callback_view_profile(callback_query, state)
@router.callback_query(lambda c: c.data.startswith('transfer_method_'))
async def process_transfer_method_selection(callback_query: types.CallbackQuery, state: FSMContext):
data = callback_query.data.split('_', 2)
@@ -89,7 +86,7 @@ async def process_transfer_method_selection(callback_query: types.CallbackQuery,
[InlineKeyboardButton(text='100 RUB', callback_data='amount_100')],
[InlineKeyboardButton(text='300 RUB', callback_data='amount_300')],
[InlineKeyboardButton(text='500 RUB', callback_data='amount_500')],
[InlineKeyboardButton(text='⬅️ Назад', callback_data='back_to_profile')]
[InlineKeyboardButton(text='⬅️ Назад', callback_data='back_to_profile')] # Кнопка "Назад"
])
await callback_query.message.edit_text(
@@ -98,8 +95,11 @@ async def process_transfer_method_selection(callback_query: types.CallbackQuery,
)
await state.update_data(transfer_method=transfer_method)
await state.set_state(ReplenishBalanceState.choosing_amount)
else:
await send_message_with_deletion(callback_query.from_user.id, "Неверный метод перевода.", state=state, message_key='transfer_method_error_message_id')
return
@router.callback_query(lambda c: c.data.startswith('amount_'))
async def process_amount_selection(callback_query: types.CallbackQuery, state: FSMContext):
@@ -112,16 +112,18 @@ async def process_amount_selection(callback_query: types.CallbackQuery, state: F
amount_str = data[1]
amount = int(amount_str)
# Удаляем сообщение с кнопками выбора суммы
# Получаем ID сообщения с кнопками выбора суммы
state_data = await state.get_data()
amount_selection_message_id = state_data.get('amount_selection_message_id')
# Удаляем сообщение с кнопками выбора суммы
if amount_selection_message_id:
try:
await bot.delete_message(chat_id=callback_query.from_user.id, message_id=amount_selection_message_id)
except Exception as e:
print(f"Ошибка при удалении сообщения: {e}")
# Обновляем состояние и сохраняем выбранную сумму
await state.update_data(amount=amount)
await state.set_state(ReplenishBalanceState.waiting_for_admin_confirmation)
@@ -134,7 +136,11 @@ async def process_amount_selection(callback_query: types.CallbackQuery, state: F
"После перевода отправьте чек и дождитесь подтверждения."
)
await callback_query.message.edit_text(text=message, reply_markup=None)
# Редактируем текущее сообщение
await callback_query.message.edit_text(
text=message,
reply_markup=None # Или добавьте клавиатуру, если нужно
)
admin_keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Подтвердить', callback_data=f'admin_confirm_{callback_query.from_user.id}_{transfer_method}_{amount}')],
@@ -151,6 +157,8 @@ async def process_amount_selection(callback_query: types.CallbackQuery, state: F
await send_message_with_deletion(ADMIN_ID, admin_message, reply_markup=admin_keyboard, state=state, message_key='admin_request_message_id')
await callback_query.answer()
@router.callback_query(lambda c: c.data.startswith('admin_'))
async def process_admin_confirmation(callback_query: types.CallbackQuery, state: FSMContext):
if callback_query.from_user.id != ADMIN_ID:
@@ -164,20 +172,38 @@ async def process_admin_confirmation(callback_query: types.CallbackQuery, state:
return
action = data[1]
user_id = int(data[2])
user_id_str = data[2]
transfer_method = data[3]
amount = int(data[4])
try:
user_id = int(user_id_str)
# Получаем данные из состояния для удаления сообщения с реквизитами
state_data = await state.get_data()
requisites_message_id = state_data.get('requisites_message_id')
if action == 'confirm':
async with aiosqlite.connect(DATABASE_PATH) as db:
await update_balance(user_id, amount)
await db.commit()
balance = await get_balance(user_id)
# Создаем клавиатуру с кнопкой "Профиль"
profile_button = InlineKeyboardButton(text='Профиль', callback_data='view_profile')
profile_keyboard = InlineKeyboardMarkup(inline_keyboard=[[profile_button]])
# Отправляем уведомление с кнопкой "Профиль" администратору
await send_message_with_deletion(callback_query.from_user.id, f"Баланс пользователя успешно пополнен на {amount} RUB.\nТекущий баланс: {balance}", state=state, message_key='admin_confirm_message_id')
await bot.send_message(user_id, f"Ваш баланс был успешно пополнен на {amount} RUB.")
# Отправляем уведомление пользователю с кнопкой "Профиль"
await bot.send_message(
user_id,
f"Ваш баланс был успешно пополнен на {amount} RUB.",
reply_markup=profile_keyboard
)
# Удаляем сообщение с реквизитами
state_data = await state.get_data()
@@ -188,10 +214,6 @@ async def process_admin_confirmation(callback_query: types.CallbackQuery, state:
except Exception as e:
print(f"Ошибка при удалении сообщения с реквизитами: {e}")
profile_button = InlineKeyboardButton(text='Профиль', callback_data='view_profile')
profile_keyboard = InlineKeyboardMarkup(inline_keyboard=[[profile_button]])
await bot.send_message(user_id, "После пополнения баланса вы можете просмотреть свой профиль.", reply_markup=profile_keyboard)
elif action == 'decline':
await send_message_with_deletion(callback_query.from_user.id, "Пополнение баланса отклонено.", state=state, message_key='admin_decline_message_id')
await bot.send_message(user_id, "Ваш запрос на пополнение баланса был отклонен.")
@@ -203,6 +225,8 @@ async def process_admin_confirmation(callback_query: types.CallbackQuery, state:
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
+86 -11
View File
@@ -33,10 +33,44 @@ class Form(StatesGroup):
# Обработка нажатия кнопки создания ключа
@dp.callback_query(F.data == 'create_key')
async def process_callback_create_key(callback_query: CallbackQuery, state: FSMContext):
await callback_query.message.edit_text("Вам будет выдан пробный ключ. Пожалуйста, выберите имя для вашего ключа:")
await state.set_state(Form.waiting_for_key_name)
tg_id = callback_query.from_user.id
if await has_active_key(tg_id):
await callback_query.message.edit_text(
"У вас уже есть активный ключ. Вы можете создать новый ключ за дополнительную плату в размере 100 рублей. "
"Хотите продолжить?",
reply_markup=InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Да, создать новый ключ', callback_data='confirm_create_new_key')],
[InlineKeyboardButton(text='Назад', callback_data='cancel_create_key')] # Изменили текст на "Назад"
])
)
await state.update_data(creating_new_key=True) # Сохраняем состояние создания нового ключа
else:
await callback_query.message.edit_text("Вам будет выдан пробный ключ. Пожалуйста, выберите имя для вашего ключа:")
await state.set_state(Form.waiting_for_key_name)
await callback_query.answer()
@dp.callback_query(F.data == 'cancel_create_key')
async def cancel_create_key(callback_query: CallbackQuery, state: FSMContext):
await process_callback_view_profile(callback_query, state) # Возвращаем в профиль
await callback_query.answer()
@dp.callback_query(F.data == 'confirm_create_new_key')
async def confirm_create_new_key(callback_query: CallbackQuery, state: FSMContext):
await callback_query.message.edit_text("Пожалуйста, выберите имя для вашего нового ключа:")
await state.set_state(Form.waiting_for_key_name)
await state.update_data(creating_new_key=True) # Убедитесь, что это состояние сохранено
await callback_query.answer()
@dp.callback_query(F.data == 'cancel_create_key')
async def cancel_create_key(callback_query: CallbackQuery):
await callback_query.message.edit_text("Создание нового ключа отменено.")
await callback_query.answer()
# Обработка текстовых сообщений
@dp.message()
async def handle_text(message: Message, state: FSMContext):
@@ -63,22 +97,18 @@ async def handle_text(message: Message, state: FSMContext):
if current_state == Form.waiting_for_key_name.state:
await handle_key_name_input(message, state)
# Обработка ввода имени ключа
async def handle_key_name_input(message: Message, state: FSMContext):
tg_id = message.from_user.id
key_name = sanitize_key_name(message.text)
if not key_name:
await message.reply("Имя профиля не указано. Введите имя на английском языке.")
await message.reply("Имя ключа не указано. Введите имя на английском языке.")
await state.clear()
return
if await has_active_key(tg_id):
await message.reply("У вас уже есть активный ключ. Вы не можете создать новый.")
await state.clear()
return
await state.update_data(key_name=key_name, tg_id=tg_id)
# Получаем данные состояния
data = await state.get_data()
creating_new_key = data.get('creating_new_key', False)
session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD)
client_id = str(uuid.uuid4())
@@ -86,13 +116,24 @@ async def handle_key_name_input(message: Message, state: FSMContext):
current_time = datetime.utcnow()
expiry_time = int((current_time + timedelta(days=1)).timestamp() * 1000)
if creating_new_key:
balance = await get_balance(tg_id)
if balance < 100:
replenish_button = InlineKeyboardButton(text='Перейти в профиль', callback_data='view_profile')
keyboard = InlineKeyboardMarkup(inline_keyboard=[[replenish_button]])
await message.reply("Недостаточно средств на балансе для создания нового ключа.", reply_markup=keyboard)
await state.clear()
return
await update_balance(tg_id, -100) # Списание 100 рублей за новый ключ
try:
# Создание клиента и получение ссылки
add_client(session, client_id, email, tg_id, limit_ip=1, total_gb=0, expiry_time=expiry_time, enable=True, flow="xtls-rprx-vision")
connection_link = link(session, client_id, email)
await add_connection(tg_id, client_id, email, expiry_time, 0)
await store_key(client_id, email, connection_link)
await store_key(tg_id, client_id, email, connection_link)
keyboard = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Инструкции по использованию', callback_data='instructions')],
@@ -107,6 +148,40 @@ async def handle_key_name_input(message: Message, state: FSMContext):
await state.clear()
# Обработка нажатия кнопки создания ключа
@dp.callback_query(F.data == 'create_key')
async def process_callback_create_key(callback_query: CallbackQuery, state: FSMContext):
tg_id = callback_query.from_user.id
if await has_active_key(tg_id):
await callback_query.message.edit_text(
"У вас уже есть активный ключ. Вы можете создать новый ключ за дополнительную плату в размере 100 рублей. "
"Хотите продолжить?",
reply_markup=InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text='Да, создать новый ключ', callback_data='confirm_create_new_key')],
[InlineKeyboardButton(text='Нет, оставить текущий', callback_data='cancel_create_key')]
])
)
await state.update_data(creating_new_key=True) # Сохраняем состояние создания нового ключа
else:
await callback_query.message.edit_text("Вам будет выдан пробный ключ. Пожалуйста, выберите имя для вашего ключа:")
await state.set_state(Form.waiting_for_key_name)
await callback_query.answer()
@dp.callback_query(F.data == 'confirm_create_new_key')
async def confirm_create_new_key(callback_query: CallbackQuery, state: FSMContext):
await callback_query.message.edit_text("Пожалуйста, выберите имя для вашего нового ключа:")
await state.set_state(Form.waiting_for_key_name)
await callback_query.answer()
@dp.callback_query(F.data == 'cancel_create_key')
async def cancel_create_key(callback_query: CallbackQuery):
await callback_query.message.edit_text("Создание нового ключа отменено.")
await callback_query.answer()
# Обработка кнопки "Инструкции"
@dp.callback_query(F.data == 'instructions')
async def handle_instructions(callback_query: CallbackQuery):