understanding commited on
Commit
61b7300
·
verified ·
1 Parent(s): 9f107af

Update bot/core/speedtest.py

Browse files
Files changed (1) hide show
  1. bot/core/speedtest.py +25 -11
bot/core/speedtest.py CHANGED
@@ -21,6 +21,7 @@ def bytes_per_sec_to_mb_s(bps: float) -> float:
21
  def disk_total_free(path: str = "/") -> dict:
22
  st = os.statvfs(path)
23
  total = st.f_frsize * st.f_blocks
 
24
  free = st.f_frsize * st.f_bavail
25
  return {"total": int(total), "free": int(free)}
26
 
@@ -45,22 +46,35 @@ 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 public_ip(timeout: float = 4.0) -> Optional[str]:
49
  """
50
- Gets public IP using Cloudflare trace.
51
- Returns string IP or None.
52
  """
53
  try:
54
  async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as c:
55
- r = await c.get("https://1.1.1.1/cdn-cgi/trace")
56
- if r.status_code >= 400:
57
- return None
58
- # trace format: key=value lines
59
- for line in (r.text or "").splitlines():
60
- if line.startswith("ip="):
61
- return line.split("=", 1)[1].strip() or None
62
  except Exception:
63
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  return None
65
 
66
 
 
21
  def disk_total_free(path: str = "/") -> dict:
22
  st = os.statvfs(path)
23
  total = st.f_frsize * st.f_blocks
24
+ free = st.f_frsize * st.f_frsize * (st.f_bavail // st.f_frsize) if st.f_frsize else st.f_frsize * st.f_bavail
25
  free = st.f_frsize * st.f_bavail
26
  return {"total": int(total), "free": int(free)}
27
 
 
46
  return None
47
 
48
 
49
+ async def public_ip(timeout: float = 6.0) -> Optional[str]:
50
  """
51
+ Best-effort public IP.
52
+ Tries ipify, then Cloudflare trace.
53
  """
54
  try:
55
  async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as c:
56
+ r = await c.get("https://api.ipify.org?format=json")
57
+ if r.status_code < 400:
58
+ j = r.json()
59
+ ip = str(j.get("ip") or "").strip()
60
+ if ip:
61
+ return ip
 
62
  except Exception:
63
+ pass
64
+
65
+ try:
66
+ async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as c:
67
+ r = await c.get("https://cloudflare.com/cdn-cgi/trace")
68
+ if r.status_code < 400:
69
+ txt = r.text or ""
70
+ for ln in txt.splitlines():
71
+ if ln.startswith("ip="):
72
+ ip = ln.split("=", 1)[1].strip()
73
+ if ip:
74
+ return ip
75
+ except Exception:
76
+ pass
77
+
78
  return None
79
 
80