|
| 1 | +import struct |
| 2 | +import time |
| 3 | +import aiohttp |
| 4 | + |
| 5 | +from opengsq.responses.palworld import Status |
| 6 | +from opengsq.protocol_base import ProtocolBase |
| 7 | + |
| 8 | + |
| 9 | +class Palworld(ProtocolBase): |
| 10 | + """ |
| 11 | + This class represents the Palworld Protocol. It provides methods to interact with the Palworld REST API. |
| 12 | + """ |
| 13 | + |
| 14 | + full_name = "Palworld Protocol" |
| 15 | + |
| 16 | + def __init__(self, host: str, port: int, api_username: str, api_password: str, timeout: float = 5): |
| 17 | + """ |
| 18 | + Initializes the Palworld object with the given parameters. |
| 19 | +
|
| 20 | + :param host: The host of the server. |
| 21 | + :param port: The port of the server. |
| 22 | + :param api_username: The API username. |
| 23 | + :param api_password: The API password. |
| 24 | + :param timeout: The timeout for the server connection. |
| 25 | + """ |
| 26 | + |
| 27 | + super().__init__(host, port, timeout) |
| 28 | + |
| 29 | + if api_username is None: |
| 30 | + raise ValueError("api_username must not be None") |
| 31 | + if api_password is None: |
| 32 | + raise ValueError("api_password must not be None") |
| 33 | + |
| 34 | + self.api_url = f"http://{self._host}:{self._port}/v1/api" |
| 35 | + self.api_username = api_username |
| 36 | + self.api_password = api_password |
| 37 | + |
| 38 | + async def api_request(self,url): |
| 39 | + """ |
| 40 | + Asynchronously retrieves data from the game server through the REST API. |
| 41 | + """ |
| 42 | + auth = aiohttp.BasicAuth(self.api_username,self.api_password) |
| 43 | + async with aiohttp.ClientSession(auth=auth) as session: |
| 44 | + async with session.get(url) as response: |
| 45 | + data = await response.json() |
| 46 | + return data |
| 47 | + |
| 48 | + async def get_status(self) -> Status: |
| 49 | + """ |
| 50 | + Retrieves the status of the game server. The status includes the server state, name, player count and max player count. |
| 51 | + """ |
| 52 | + info_data = await self.api_request(f"{self.api_url}/info") |
| 53 | + metrics_data = await self.api_request(f"{self.api_url}/metrics") |
| 54 | + |
| 55 | + server_name = info_data["servername"] |
| 56 | + server_cur_players = metrics_data["currentplayernum"] |
| 57 | + server_max_players = metrics_data["maxplayernum"] |
| 58 | + |
| 59 | + return Status( |
| 60 | + server_name=server_name, |
| 61 | + num_players=server_cur_players, |
| 62 | + max_players=server_max_players, |
| 63 | + ) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + import asyncio |
| 68 | + |
| 69 | + async def main_async(): |
| 70 | + palworld = Palworld( |
| 71 | + host="79.136.0.124", |
| 72 | + port=8212, |
| 73 | + timeout=5.0, |
| 74 | + api_username="admin", |
| 75 | + api_password="", |
| 76 | + ) |
| 77 | + status = await palworld.get_status() |
| 78 | + print(status) |
| 79 | + |
| 80 | + asyncio.run(main_async()) |
0 commit comments