nonsensebot/app/modules/latency.py

26 lines
925 B
Python
Raw Normal View History

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")
async def latency(self, ctx: niobot.Context):
"""See the bot's latency."""
latency = ctx.latency
2024-08-19 18:48:36 +01:00
homeserver = await niobot.resolve_homeserver(ctx.message.sender.split(":")[1])
async with httpx.AsyncClient(headers={"User-Agent": niobot.__user_agent__}) as client:
timings = []
for rnd in range(5):
start = time.time()
await client.get(f"{homeserver}/_matrix/client/v1/ping")
end = time.time()
timings.append(end - start)
fed_latency = sum(timings) / len(timings) * 1000
2024-08-19 18:50:21 +01:00
hs_target = ctx.message.sender.split(":")[1]
2024-08-19 18:48:36 +01:00
return await ctx.respond(
2024-08-19 18:50:21 +01:00
"Latency: {:,.2f}ms (federation latency to {!r}: {:,.2f}ms)".format(latency, hs_target, fed_latency)
2024-08-19 18:48:36 +01:00
)