2024-02-27 23:02:03 -05:00
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
|
2024-02-28 12:43:26 -05:00
|
|
|
import discord
|
2024-02-27 23:02:03 -05:00
|
|
|
import websockets
|
|
|
|
from pydactyl import PterodactylClient, exceptions
|
|
|
|
from redbot.core import Config, commands
|
|
|
|
from redbot.core.bot import Red
|
|
|
|
|
|
|
|
|
|
|
|
class Pterodactyl(commands.Cog):
|
|
|
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
|
|
|
|
|
|
|
def __init__(self, bot: Red):
|
|
|
|
self.bot = bot
|
2024-02-27 23:18:17 -05:00
|
|
|
self.config = Config.get_conf(self, identifier=457581387213637448123567, force_registration=True)
|
2024-02-27 23:02:03 -05:00
|
|
|
self.config.register_global(
|
2024-02-27 23:18:17 -05:00
|
|
|
base_url=None,
|
|
|
|
api_key=None,
|
|
|
|
server_id=None,
|
2024-02-28 12:43:26 -05:00
|
|
|
console_channel=None,
|
2024-02-27 23:02:03 -05:00
|
|
|
startup_jar=None,
|
|
|
|
startup_arguments=None,
|
|
|
|
power_action_in_progress=False
|
|
|
|
)
|
|
|
|
self.logger = logging.getLogger('red.sea.pterodactyl')
|
|
|
|
self.client = None
|
2024-02-28 08:47:24 -05:00
|
|
|
self.task = None
|
2024-02-27 23:02:03 -05:00
|
|
|
self.websocket = None
|
|
|
|
|
2024-02-28 08:11:15 -05:00
|
|
|
async def establish_websocket_connection(self):
|
2024-02-28 08:49:02 -05:00
|
|
|
self.logger.debug("Establishing WebSocket connection")
|
2024-02-28 08:11:15 -05:00
|
|
|
base_url = await self.config.base_url()
|
|
|
|
api_key = await self.config.api_key()
|
|
|
|
server_id = await self.config.server_id()
|
2024-02-28 08:14:40 -05:00
|
|
|
|
|
|
|
extra_headers = {
|
2024-02-28 12:03:16 -05:00
|
|
|
"origin": base_url
|
2024-02-28 08:14:40 -05:00
|
|
|
}
|
|
|
|
|
2024-02-27 23:02:03 -05:00
|
|
|
try:
|
2024-02-28 11:57:39 -05:00
|
|
|
client = PterodactylClient(base_url, api_key, debug=True).client
|
2024-02-27 23:02:03 -05:00
|
|
|
websocket_credentials = client.servers.get_websocket(server_id)
|
2024-02-28 08:37:02 -05:00
|
|
|
self.logger.debug("Websocket connection details retrieved:\nSocket: %s\nToken: %s", websocket_credentials['data']['socket'], websocket_credentials['data']['token'])
|
2024-02-27 23:02:03 -05:00
|
|
|
except exceptions.ClientConfigError as e:
|
2024-02-28 11:08:16 -05:00
|
|
|
self.logger.error('Failed to initialize Pterodactyl client: %s', e)
|
2024-02-27 23:02:03 -05:00
|
|
|
return
|
|
|
|
except exceptions.PterodactylApiError as e:
|
2024-02-28 11:08:16 -05:00
|
|
|
self.logger.error('Failed to retrieve Pterodactyl websocket: %s', e)
|
2024-02-27 23:02:03 -05:00
|
|
|
return
|
|
|
|
|
2024-02-28 11:46:00 -05:00
|
|
|
async for websocket in websockets.connect(websocket_credentials['data']['socket'], extra_headers=extra_headers):
|
|
|
|
try:
|
|
|
|
self.logger.debug("WebSocket connection established")
|
2024-02-27 23:02:03 -05:00
|
|
|
|
2024-02-28 11:46:00 -05:00
|
|
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
|
|
|
await websocket.send(auth_message)
|
|
|
|
self.logger.debug("Authentication message sent")
|
2024-02-27 23:02:03 -05:00
|
|
|
|
2024-02-28 11:46:00 -05:00
|
|
|
self.client = client
|
|
|
|
self.websocket = websocket
|
2024-02-27 23:02:03 -05:00
|
|
|
|
2024-02-28 11:46:00 -05:00
|
|
|
while True:
|
|
|
|
message = await websocket.recv()
|
|
|
|
if json.loads(message)['event'] in ['token expiring', 'token expired']:
|
|
|
|
self.logger.debug("Received token expiring/expired event. Refreshing token.")
|
|
|
|
websocket_credentials = client.servers.get_websocket(server_id)
|
|
|
|
auth_message = json.dumps({"event": "auth", "args": [websocket_credentials['data']['token']]})
|
|
|
|
await websocket.send(auth_message)
|
|
|
|
self.logger.debug("Authentication message sent")
|
2024-02-28 12:43:26 -05:00
|
|
|
|
2024-02-28 11:46:00 -05:00
|
|
|
if json.loads(message)['event'] == 'auth success':
|
|
|
|
self.logger.debug("Authentication successful")
|
2024-02-28 12:43:26 -05:00
|
|
|
|
|
|
|
if json.loads(message)['event'] == 'console output' and await self.config.console_channel() is not None:
|
|
|
|
channel = self.bot.get_channel(await self.config.console_channel)
|
|
|
|
await channel.send(json.loads(message)['args'][0])
|
|
|
|
#FIXME - Add pagification for long messages to prevent Discord API errors
|
2024-02-28 11:46:00 -05:00
|
|
|
except websockets.exceptions.ConnectionClosed as e:
|
|
|
|
self.logger.debug("WebSocket connection closed: %s", e)
|
|
|
|
websocket_credentials = client.servers.get_websocket(server_id)
|
|
|
|
continue
|
2024-02-27 23:02:03 -05:00
|
|
|
|
2024-02-28 11:54:16 -05:00
|
|
|
def get_task(self):
|
|
|
|
return self.bot.loop.create_task(self.establish_websocket_connection(), name="Pterodactyl Websocket Connection")
|
2024-02-28 08:47:24 -05:00
|
|
|
|
2024-02-27 23:02:03 -05:00
|
|
|
async def cog_load(self):
|
2024-02-28 11:54:16 -05:00
|
|
|
self.task = self.get_task()
|
2024-02-27 23:02:03 -05:00
|
|
|
|
|
|
|
async def cog_unload(self):
|
2024-02-28 11:08:16 -05:00
|
|
|
self.task.cancel()
|
|
|
|
await self.client._session.close() # pylint: disable=protected-access
|
2024-02-28 08:11:23 -05:00
|
|
|
|
2024-02-28 12:43:26 -05:00
|
|
|
@commands.cog.listener()
|
|
|
|
async def on_message(self, message: discord.Message):
|
|
|
|
if message.channel.id == await self.config.console_channel():
|
|
|
|
self.websocket.send(json.dumps({"event": "send command", "args": [message.content]}))
|
|
|
|
|
2024-02-28 08:11:23 -05:00
|
|
|
@commands.group(autohelp = True, name = "pterodactyl", aliases = ["ptero"])
|
|
|
|
async def pterodactyl(self, ctx: commands.Context):
|
|
|
|
"""Pterodactyl allows you to manage your Pterodactyl Panel from Discord."""
|
|
|
|
|
|
|
|
@pterodactyl.group(autohelp = True, name = "config", aliases = ["settings", "set"])
|
|
|
|
async def pterodactyl_config(self, ctx: commands.Context):
|
|
|
|
"""Configure Pterodactyl settings."""
|
|
|
|
|
|
|
|
@pterodactyl_config.command(name = "url")
|
|
|
|
async def pterodactyl_config_base_url(self, ctx: commands.Context, base_url: str):
|
|
|
|
"""Set the base URL of your Pterodactyl Panel. Please include the protocol (http/https)."""
|
|
|
|
await self.config.base_url.set(base_url)
|
|
|
|
await ctx.send(f"Base URL set to {base_url}")
|
2024-02-28 08:56:47 -05:00
|
|
|
self.logger.debug("Configuration value set: base_url = %s\nRestarting task...", base_url)
|
2024-02-28 10:46:42 -05:00
|
|
|
self.task.cancel()
|
2024-02-28 11:54:16 -05:00
|
|
|
self.task = self.get_task()
|
2024-02-28 08:11:23 -05:00
|
|
|
|
|
|
|
@pterodactyl_config.command(name = "apikey")
|
|
|
|
async def pterodactyl_config_api_key(self, ctx: commands.Context, api_key: str):
|
|
|
|
"""Set the API key for your Pterodactyl Panel."""
|
|
|
|
await self.config.api_key.set(api_key)
|
|
|
|
await ctx.send(f"API key set to `{api_key[:5]}...{api_key[-4:]}`")
|
2024-02-28 08:56:47 -05:00
|
|
|
self.logger.debug("Configuration value set: api_key = %s\nRestarting task...", api_key)
|
2024-02-28 10:46:42 -05:00
|
|
|
self.task.cancel()
|
2024-02-28 11:54:16 -05:00
|
|
|
self.task = self.get_task()
|
2024-02-28 08:11:23 -05:00
|
|
|
|
|
|
|
@pterodactyl_config.command(name = "serverid")
|
|
|
|
async def pterodactyl_config_server_id(self, ctx: commands.Context, server_id: str):
|
|
|
|
"""Set the server ID for your Pterodactyl Panel."""
|
|
|
|
await self.config.server_id.set(server_id)
|
|
|
|
await ctx.send(f"Server ID set to {server_id}")
|
2024-02-28 08:56:47 -05:00
|
|
|
self.logger.debug("Configuration value set: server_id = %s\nRestarting task...", server_id)
|
2024-02-28 10:46:42 -05:00
|
|
|
self.task.cancel()
|
2024-02-28 11:54:16 -05:00
|
|
|
self.task = self.get_task()
|
2024-02-28 12:44:12 -05:00
|
|
|
|
|
|
|
@pterodactyl_config.command(name = "consolechannel")
|
|
|
|
async def pterodactyl_config_console_channel(self, ctx: commands.Context, channel: discord.TextChannel):
|
|
|
|
"""Set the channel to send console output to."""
|
|
|
|
await self.config.console_channel.set(channel.id)
|
|
|
|
await ctx.send(f"Console channel set to {channel.mention}")
|