Spaces:
Runtime error
Runtime error
Update bot/core/speedtest.py
Browse files- bot/core/speedtest.py +32 -0
bot/core/speedtest.py
CHANGED
|
@@ -45,6 +45,38 @@ async def ping_ms(host: str = "1.1.1.1", port: int = 443, timeout: float = 3.0)
|
|
| 45 |
return None
|
| 46 |
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
async def net_download_test(bytes_target: int = 8 * 1024 * 1024, timeout: float = 15.0) -> dict:
|
| 49 |
"""
|
| 50 |
Downloads bytes_target from Cloudflare endpoint and measures throughput.
|
|
|
|
| 45 |
return None
|
| 46 |
|
| 47 |
|
| 48 |
+
async def public_ip(timeout: float = 5.0) -> Optional[str]:
|
| 49 |
+
"""
|
| 50 |
+
Best-effort public IP detect.
|
| 51 |
+
Tries ipify, then Cloudflare trace.
|
| 52 |
+
"""
|
| 53 |
+
try:
|
| 54 |
+
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as c:
|
| 55 |
+
r = await c.get("https://api.ipify.org", params={"format": "json"})
|
| 56 |
+
if r.status_code < 400:
|
| 57 |
+
j = r.json()
|
| 58 |
+
ip = str(j.get("ip") or "").strip()
|
| 59 |
+
if ip:
|
| 60 |
+
return ip
|
| 61 |
+
except Exception:
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
# fallback: Cloudflare trace
|
| 65 |
+
try:
|
| 66 |
+
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as c:
|
| 67 |
+
r = await c.get("https://1.1.1.1/cdn-cgi/trace")
|
| 68 |
+
if r.status_code < 400:
|
| 69 |
+
# lines like: ip=1.2.3.4
|
| 70 |
+
for line in (r.text or "").splitlines():
|
| 71 |
+
if line.startswith("ip="):
|
| 72 |
+
ip = line.split("=", 1)[1].strip()
|
| 73 |
+
return ip or None
|
| 74 |
+
except Exception:
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
|
| 80 |
async def net_download_test(bytes_target: int = 8 * 1024 * 1024, timeout: float = 15.0) -> dict:
|
| 81 |
"""
|
| 82 |
Downloads bytes_target from Cloudflare endpoint and measures throughput.
|