Refactored

This commit is contained in:
Malasaur 2025-12-14 21:05:51 +01:00
parent 7a2948570b
commit e7248723f5
No known key found for this signature in database
5 changed files with 164 additions and 107 deletions

View file

@ -1,5 +1,3 @@
import asyncio
import atexit
from re import compile
from typing import Any, Callable
@ -11,35 +9,32 @@ class Minecraft:
self.host = host.rstrip("/")
self.port = port
self.headers = {"Authorization": password}
self.session = ClientSession()
atexit.register(self.exit)
self._hooks: list[Callable] = []
def exit(self):
asyncio.run(self.session.close())
async def _get(self, method: str, **json: Any):
async with self.session.get(
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
) as response:
if response.status == 200:
return await response.json()
raise ConnectionError(
f"Error while sending {method} to Server: HTTP code {response.status}."
)
async def _stream(self, method: str, **json: Any):
async with self.session.get(
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
) as response:
if response.status == 200:
async for chunk, _ in response.content.iter_chunks():
yield chunk
else:
async with ClientSession() as session:
async with session.get(
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
) as response:
if response.status == 200:
return await response.json()
raise ConnectionError(
f"Error while sending {method} to Server: HTTP code {response.status}."
)
async def _stream(self, method: str, **json: Any):
async with ClientSession() as session:
async with session.get(
f"{self.host}:{self.port}{method}", json=json, headers=self.headers
) as response:
if response.status == 200:
async for chunk, _ in response.content.iter_chunks():
yield chunk
else:
raise ConnectionError(
f"Error while sending {method} to Server: HTTP code {response.status}."
)
async def start(self):
return await self._get("/start")