апдейт юзеров

This commit is contained in:
Vlad
2024-09-19 03:41:44 +03:00
parent bfc7ffe024
commit 2b869aa9b8
6 changed files with 164 additions and 10 deletions
+2
View File
@@ -1,6 +1,7 @@
import requests
from config import ADMIN_USERNAME, ADMIN_PASSWORD, GET_INBOUNDS_URL
import json
import httpx
session = None
@@ -19,6 +20,7 @@ def login_with_credentials(username, password):
else:
raise Exception(f"Ошибка авторизации: {response.status_code}, {response.text}")
def get_clients(session):
response = session.get(GET_INBOUNDS_URL)
if response.status_code == 200:
+64 -3
View File
@@ -1,7 +1,10 @@
import requests
import json
from config import ADMIN_USERNAME, ADMIN_PASSWORD, GET_INBOUNDS_URL
from config import ADMIN_USERNAME, ADMIN_PASSWORD, GET_INBOUNDS_URL, DATABASE_PATH
import uuid
from auth import login_with_credentials
from datetime import datetime, timedelta
import aiosqlite
def add_client(session, client_id: str, email: str, tg_id: str, limit_ip: int, total_gb: int, expiry_time: int, enable: bool, flow: str):
url = 'https://solonet.pocomacho.ru:62553/solonet/panel/api/inbounds/addClient'
@@ -48,7 +51,65 @@ def add_client(session, client_id: str, email: str, tg_id: str, limit_ip: int, t
else:
print(f"Ошибка при добавлении клиента: {response.status_code}, {response.text}")
import json
def extend_client_key(session, tg_id, client_id, email: str, new_expiry_time: int) -> bool:
# Получаем текущие данные клиента
response = session.get(f"https://solonet.pocomacho.ru:62553/solonet/panel/api/inbounds/getClientTraffics/{email}")
print(f"GET {response.url} Status: {response.status_code}")
print(f"GET Response: {response.text}")
if response.status_code != 200:
print(f"Ошибка при получении данных клиента: {response.status_code} - {response.text}")
return False
client_data = response.json().get("obj", {})
print(client_data)
def generate_client_id():
return str(uuid.uuid4())
if not client_data:
print("Не удалось получить данные клиента.")
return False
# Обновляем данные клиента
client_data['expiryTime'] = new_expiry_time
# Формируем данные для обновления
payload = {
"id": 1, # Если id динамически изменяется, замените это значение
"settings": json.dumps({
"clients": [
{
"id": client_id,
"alterId": 0,
"email": client_data['email'],
"limitIp": 1,
# "totalGB": 2,
"expiryTime": new_expiry_time,
"enable": client_data['enable'],
"tgId": tg_id,
"subId": '',
"flow": 'xtls-rprx-vision'
}
]
})
}
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
try:
response = session.post(f"https://solonet.pocomacho.ru:62553/solonet/panel/api/inbounds/updateClient/{client_id}", json=payload, headers=headers)
print(f"POST {response.url} Status: {response.status_code}")
print(f"POST Request Data: {json.dumps(payload, indent=2)}")
print(f"POST Response: {response.text}")
if response.status_code == 200:
return True
else:
print(f"Ошибка при продлении ключа: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"Ошибка запроса: {e}")
return False
Binary file not shown.
+59 -4
View File
@@ -1,8 +1,11 @@
from aiogram import types, Router
import aiosqlite
from config import DATABASE_PATH
from bot import bot
from datetime import datetime
from datetime import datetime, timedelta
from database import get_active_key_email, get_balance, store_key, update_balance
from client import extend_client_key
from client import extend_client_key, login_with_credentials
from config import ADMIN_ID, ADMIN_PASSWORD, ADMIN_USERNAME, DATABASE_PATH
router = Router()
@@ -26,9 +29,14 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery):
expiry_date = datetime.utcfromtimestamp(expiry_time / 1000).strftime("%Y-%m-%d %H:%M:%S")
response_message = f"Ваш ключ:\n<pre>{key}</pre>\nДата окончания: <b>{expiry_date}</b>"
# Добавляем кнопку с инструкциями
# Кнопки для инструкций и продления
instructions_button = types.InlineKeyboardButton(text='Инструкции по использованию', callback_data='instructions')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[[instructions_button]])
renew_button = types.InlineKeyboardButton(text='Продлить ключ', callback_data='renew_key')
keyboard = types.InlineKeyboardMarkup(inline_keyboard=[
[instructions_button],
[renew_button]
])
await bot.send_message(tg_id, response_message, parse_mode="HTML", reply_markup=keyboard)
else:
@@ -40,3 +48,50 @@ async def process_callback_view_keys(callback_query: types.CallbackQuery):
await bot.send_message(tg_id, response_message, reply_to_message_id=callback_query.message.message_id)
await callback_query.answer()
@router.callback_query(lambda c: c.data == 'renew_key')
async def process_callback_renew_key(callback_query: types.CallbackQuery):
tg_id = callback_query.from_user.id
try:
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute('SELECT client_id, email, expiry_time FROM connections WHERE tg_id = ?', (tg_id,)) as cursor:
record = await cursor.fetchone()
if record:
client_id = record[0]
email = record[1] # Получаем email
expiry_time = record[2]
current_time = datetime.utcnow().timestamp() * 1000
new_expiry_time = int((datetime.utcnow() + timedelta(days=30)).timestamp() * 1000)
if expiry_time <= current_time:
await callback_query.message.answer("Ваш ключ уже истек и не может быть продлен.")
return
# Проверка баланса
balance = await get_balance(tg_id)
if balance < 100:
await callback_query.message.answer("Недостаточно средств для продления ключа.")
return
# Создаем сессию для API-запросов
session = login_with_credentials(ADMIN_USERNAME, ADMIN_PASSWORD)
# Обновляем ключ через API
success = extend_client_key(session, tg_id, client_id, email, new_expiry_time)
if success:
await update_balance(tg_id, -100) # Списание 100 рублей с баланса
await db.execute('UPDATE connections SET expiry_time = ? WHERE client_id = ?', (new_expiry_time, client_id))
await db.commit()
await callback_query.message.answer("Ваш ключ был успешно продлен на месяц.")
else:
await callback_query.message.answer("Ошибка при продлении ключа.")
else:
await callback_query.message.answer("У вас нет ключей для продления.")
except Exception as e:
await callback_query.message.answer(f"Ошибка при продлении ключа: {e}")
await callback_query.answer()
+39 -3
View File
@@ -8,7 +8,8 @@ from auth import login_with_credentials, link
from client import add_client
from datetime import datetime, timedelta
from config import API_TOKEN, ADMIN_PASSWORD, ADMIN_USERNAME, ADMIN_CHAT_ID, DATABASE_PATH
from database import add_connection, has_active_key, get_active_key_email, get_balance, store_key
from database import add_connection, has_active_key, get_active_key_email, get_balance, store_key, update_balance
from client import extend_client_key
import uuid
import aiosqlite
import re
@@ -16,6 +17,8 @@ from bot import dp
from handlers.start import start_command
from bot import bot
from handlers.profile import process_callback_view_profile
import asyncio
router = Router()
@@ -49,6 +52,7 @@ async def process_callback_create_key(callback_query: types.CallbackQuery, state
@dp.message()
async def handle_text(message: types.Message, state: FSMContext):
current_state = await state.get_state()
print(f"Received message: {message.text}, Current state: {current_state}")
if message.text == "Мой профиль":
# Создайте фейковый объект CallbackQuery для вызова функции
@@ -121,7 +125,15 @@ async def handle_admin_confirmation(callback_query: CallbackQuery, state: FSMCon
limit_ip = 1
total_gb = 0
current_time = datetime.utcnow()
expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000)
# Определяем время истечения ключа
if await has_active_key(tg_id):
# Если есть активный ключ, устанавливаем срок действия на 30 дней
expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000)
else:
# Первый ключ устанавливаем на 1 день
expiry_time = int((current_time + timedelta(days=1)).timestamp() * 1000)
enable = True
flow = "xtls-rprx-vision"
balance = 0
@@ -151,7 +163,6 @@ async def handle_admin_confirmation(callback_query: CallbackQuery, state: FSMCon
await callback_query.answer()
@dp.callback_query(F.data == 'instructions')
async def handle_instructions(callback_query: CallbackQuery):
instructions_message = (
@@ -169,3 +180,28 @@ async def handle_instructions(callback_query: CallbackQuery):
parse_mode='Markdown'
)
await callback_query.answer()
async def renew_expired_keys():
while True:
current_time = datetime.utcnow()
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute('SELECT tg_id, client_id FROM connections WHERE expiry_time <= ?', (int(current_time.timestamp() * 1000),)) as cursor:
expired_keys = await cursor.fetchall()
for tg_id, client_id in expired_keys:
balance = await get_balance(tg_id)
if balance >= 100:
new_expiry_time = int((current_time + timedelta(days=30)).timestamp() * 1000)
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute('UPDATE connections SET expiry_time = ? WHERE tg_id = ? AND client_id = ?', (new_expiry_time, tg_id, client_id))
await db.commit()
await update_balance(tg_id, -100)
await extend_client_key(client_id)
print(f"Ключ для клиента {client_id} продлен на месяц и списано 100 рублей.")
else:
print(f"Недостаточно средств на балансе для клиента {client_id}.")
await asyncio.sleep(3600)
View File