fix(speedtest): bunch of fixes

This commit is contained in:
Seaswimmer 2024-05-25 17:19:48 -04:00
parent ef591224cd
commit c3ab7593c7
Signed by: cswimr
GPG key ID: 5D671B5D03D65A7F

View file

@ -5,6 +5,7 @@
# ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ | # ____) | __/ (_| \__ \\ V V /| | | | | | | | | | | | __/ |
# |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_| # |_____/ \___|\__,_|___/ \_/\_/ |_|_| |_| |_|_| |_| |_|\___|_|
import asyncio
import json import json
import subprocess import subprocess
@ -33,13 +34,27 @@ class Speedtest(commands.Cog):
] ]
return "\n".join(text) return "\n".join(text)
async def run_speedtest(self) -> str | asyncio.Any:
process = await asyncio.create_subprocess_exec(
"speedtest", "-f json", "--accept-license",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
return stderr.decode("utf-8")
return json.loads(stdout.decode("utf-8"))
@commands.command() @commands.command()
@commands.is_owner() @commands.is_owner()
async def speedtest(self, ctx: commands.Context): async def speedtest(self, ctx: commands.Context) -> None:
"""Run a speedtest.""" """Run a speedtest."""
msg = await ctx.maybe_send_embed("Running speedtest...") msg = await ctx.maybe_send_embed("Running speedtest...")
result = subprocess.run(["speedtest", "-f json", "--accept-license"], stdout=subprocess.PIPE) async with ctx.typing():
r = json.loads(result.stdout.decode("utf-8")) r = await self.run_speedtest()
if isinstance(r, str):
await msg.edit(content=f"An error occurred: {r}")
return
if await ctx.embed_requested(): if await ctx.embed_requested():
embed = discord.Embed(title="Speedtest Results", link=r["result"]["url"], color=await ctx.embed_color()) embed = discord.Embed(title="Speedtest Results", link=r["result"]["url"], color=await ctx.embed_color())
embed.add_field(name="Bandwidth", value=f"{r['download']['bandwidth'] / 1_000_000:.2f} Mbps down, {r['upload']['bandwidth'] / 1_000_000:.2f} Mbps up") embed.add_field(name="Bandwidth", value=f"{r['download']['bandwidth'] / 1_000_000:.2f} Mbps down, {r['upload']['bandwidth'] / 1_000_000:.2f} Mbps up")