2024-08-19 18:57:10 +01:00
|
|
|
import urllib.parse
|
|
|
|
|
2024-08-03 01:27:44 +01:00
|
|
|
import niobot
|
2024-08-19 18:48:36 +01:00
|
|
|
import time
|
|
|
|
import httpx
|
2024-08-03 01:27:44 +01:00
|
|
|
|
|
|
|
|
|
|
|
class LatencyModule(niobot.Module):
|
|
|
|
@niobot.command("latency")
|
2024-08-19 18:57:10 +01:00
|
|
|
async def latency(self, ctx: niobot.Context, homeserver: str = None):
|
2024-08-03 01:27:44 +01:00
|
|
|
"""See the bot's latency."""
|
|
|
|
latency = ctx.latency
|
2024-08-19 18:48:36 +01:00
|
|
|
|
2024-08-19 19:02:45 +01:00
|
|
|
homeserver = homeserver or ctx.message.sender.split(":")[1]
|
2024-08-19 18:57:10 +01:00
|
|
|
if not homeserver.startswith("http"):
|
|
|
|
homeserver = f"https://{homeserver}"
|
|
|
|
|
|
|
|
parsed = urllib.parse.urlparse(homeserver)
|
|
|
|
loc = "https://" + parsed.netloc
|
2024-08-19 19:06:38 +01:00
|
|
|
try:
|
2024-09-02 01:03:48 +01:00
|
|
|
start_resolv = time.perf_counter()
|
2024-08-19 19:06:38 +01:00
|
|
|
homeserver = await niobot.resolve_homeserver(parsed.netloc)
|
2024-09-02 01:03:48 +01:00
|
|
|
end_resolv = time.perf_counter()
|
|
|
|
resolv = round(end_resolv - start_resolv, 2)
|
|
|
|
except ValueError as e:
|
|
|
|
await ctx.respond("\N{WARNING SIGN} Failed to resolve homeserver: " + str(e))
|
2024-08-19 19:06:38 +01:00
|
|
|
homeserver = loc
|
2024-09-02 01:03:48 +01:00
|
|
|
resolv = -1
|
|
|
|
|
2024-08-19 18:48:36 +01:00
|
|
|
async with httpx.AsyncClient(headers={"User-Agent": niobot.__user_agent__}) as client:
|
|
|
|
timings = []
|
|
|
|
for rnd in range(5):
|
2024-09-02 01:03:48 +01:00
|
|
|
start = time.perf_counter()
|
2024-08-19 19:00:19 +01:00
|
|
|
try:
|
2024-08-19 19:05:07 +01:00
|
|
|
res = await client.get(f"{homeserver}/_matrix/federation/v1/version")
|
2024-08-19 19:00:19 +01:00
|
|
|
res.raise_for_status()
|
|
|
|
except httpx.HTTPError:
|
|
|
|
timings.append(-1)
|
2024-08-19 19:02:45 +01:00
|
|
|
else:
|
2024-09-02 01:03:48 +01:00
|
|
|
end = time.perf_counter()
|
2024-08-19 19:02:45 +01:00
|
|
|
timings.append(end - start)
|
2024-08-19 18:48:36 +01:00
|
|
|
fed_latency = sum(timings) / len(timings) * 1000
|
|
|
|
|
2024-08-19 19:05:07 +01:00
|
|
|
hs_target = homeserver[8:]
|
2024-08-19 18:48:36 +01:00
|
|
|
return await ctx.respond(
|
2024-09-02 01:03:48 +01:00
|
|
|
"Latency: {:,.2f}ms ({:,.2f}ms to resolve homeserver, federation latency to {!r}: {:,.2f}ms)".format(
|
|
|
|
latency,
|
|
|
|
resolv * 1000,
|
|
|
|
hs_target,
|
|
|
|
fed_latency
|
|
|
|
)
|
2024-08-19 18:48:36 +01:00
|
|
|
)
|