add check

This commit is contained in:
Yuriy Yuriev
2026-05-22 18:22:41 +07:00
parent fbc01dd29f
commit 1529f27540
3 changed files with 146 additions and 41 deletions
+96
View File
@@ -266,6 +266,20 @@ class BotInterface:
await interface._show_status(callback.message, edit=True)
await callback.answer(f"✅ Прокси перезагружены: {count} шт.")
@dp.callback_query(F.data == "check_proxies")
async def cb_check_proxies(callback: CallbackQuery):
if not await require_admin(callback):
return
total = interface.proxy_manager.count
if total == 0:
await callback.answer("❌ Нет загруженных прокси", show_alert=True)
return
await callback.message.edit_text(
f"⏳ Проверка {total} прокси через туннель...\n\nЭто займёт несколько секунд."
)
await callback.answer()
asyncio.create_task(interface._check_all_proxies(callback.message))
@dp.callback_query(F.data == "bot_restart_confirm")
async def cb_restart_confirm(callback: CallbackQuery):
if not await require_admin(callback):
@@ -1687,6 +1701,7 @@ class BotInterface:
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text="🔄 Обновить", callback_data="menu_status"))
builder.row(InlineKeyboardButton(text="🔃 Перезагрузить прокси", callback_data="reload_proxies"))
builder.row(InlineKeyboardButton(text="🔍 Проверить прокси", callback_data="check_proxies"))
builder.row(InlineKeyboardButton(text="🔁 Перезапустить бота", callback_data="bot_restart_confirm"))
builder.row(InlineKeyboardButton(text="🔙 В меню", callback_data="menu_main"))
await self._edit_or_send(message, text, builder.as_markup(), edit)
@@ -1703,6 +1718,87 @@ class BotInterface:
finally:
await asyncio.sleep(0.5)
os.execv(sys.executable, [sys.executable] + sys.argv)
async def _check_all_proxies(self, message) -> None:
"""Проверяет все загруженные прокси через туннель и редактирует сообщение с результатами."""
from services.socks5_to_http_proxy import Socks5ToHttpProxy
from managers.proxy_manager import ProxyType
proxies = list(self.proxy_manager._proxies)
if not proxies:
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text="🔙 К статусу", callback_data="menu_status"))
try:
await message.edit_text("❌ Нет загруженных прокси", reply_markup=builder.as_markup())
except Exception:
pass
return
sem = asyncio.Semaphore(5)
results: dict[str, bool] = {}
async def _check_one(proxy):
async with sem:
try:
if proxy.proxy_type == ProxyType.SOCKS5:
tunnel = Socks5ToHttpProxy(
socks5_host=proxy.ip,
socks5_port=int(proxy.port),
username=proxy.login,
password=proxy.password,
)
await tunnel.start()
try:
ok = await tunnel.check_connection(timeout=8.0)
finally:
await tunnel.stop()
else:
from aiohttp import ClientSession, ClientTimeout
proxy_url = proxy.server
if proxy.login and proxy.password:
from urllib.parse import urlparse
parsed = urlparse(proxy_url)
proxy_url = f"{parsed.scheme}://{proxy.login}:{proxy.password}@{parsed.netloc}"
async with ClientSession(timeout=ClientTimeout(total=8)) as s:
async with s.get(
"https://www.google.com/generate_204",
proxy=proxy_url,
allow_redirects=False,
) as resp:
ok = resp.status in (200, 204)
except Exception:
ok = False
results[proxy.id] = ok
await asyncio.gather(*[_check_one(p) for p in proxies], return_exceptions=True)
ok_ids = [pid for pid, ok in results.items() if ok]
fail_ids = [pid for pid, ok in results.items() if not ok]
lines = [
f"🔍 Проверка прокси завершена\n",
f"✅ Рабочих: {len(ok_ids)} / {len(proxies)}",
f"❌ Нерабочих: {len(fail_ids)}\n",
]
if ok_ids:
lines.append("✅ Работают:")
for pid in ok_ids[:15]:
lines.append(f"{pid}")
if len(ok_ids) > 15:
lines.append(f" ...ещё {len(ok_ids) - 15}")
if fail_ids:
lines.append("\n❌ Не работают:")
for pid in fail_ids[:15]:
lines.append(f"{pid}")
if len(fail_ids) > 15:
lines.append(f" ...ещё {len(fail_ids) - 15}")
builder = InlineKeyboardBuilder()
builder.row(InlineKeyboardButton(text="🔙 К статусу", callback_data="menu_status"))
try:
await message.edit_text("\n".join(lines), reply_markup=builder.as_markup())
except Exception as e:
logger.error(f"Proxy check result edit failed: {e}")
# =========================================================================
# УПРАВЛЕНИЕ ЗАДАЧЕЙ