async def restart(self, ctx, serverid: int): db = sqlite3.connect("main.db") cursor = db.cursor() cursor.execute(f"SELECT * FROM userconfiguration WHERE user_id ='{ctx.author.id}'") result = cursor.fetchone() if result is None: #FFuW4JxjmxfZrBYeC24m3PVkrDQp6U58PeTJnLYSnQLUJ65q em = discord.Embed(colour = discord.Colour.dark_red()) em.add_field(name = f"<a:anim_cross:757875533030883379> No API Error <a:anim_cross:757875533030883379>", value = "You didnt set an API Token Only! Please set one by typing `{}addapi <api_token>` or type `{}getstarted` to learn how to get an API Token".format(ctx.prefix, ctx.prefix)) #: await ctx.send(embed=em) # await ctx.author.send(embed=em) # await ctx.send("You didnt set any api, serverid or name. Please add one") elif result is not None and result[1] is None: em = discord.Embed(colour = discord.Colour.dark_red()) em.add_field(name = f"<a:anim_cross:757875533030883379> No API Error <a:anim_cross:757875533030883379>", value = "You didnt set an API Token Only! Please set one by typing `{}addapi <api_token>` or type `{}getstarted` to learn how to get an API Token".format(ctx.prefix, ctx.prefix)) #: await ctx.send(embed=em) # await ctx.author.send(embed=em)#await ctx.send(embed=em) elif result is not None: client = PterodactylClient('https://panel.danbot.host', result[1]) id1 = client.client.list_servers() client.client.send_power_action(id1[serverid-1]['identifier'], 'restart') em = discord.Embed(colour = discord.Colour.greyple()) em1 = discord.Embed(colour = discord.Colour.green()) em1.description = f"<a:anim_check:757875556615192587> **Server Restart Command Sent**" #: await ctx.send(embed=em1) # await ctx.author.send(embed=em1) else: #: await ctx.send("Invalid ID")
def __init__(self, bot: commands.Bot): self.bot = bot self.pclient = PterodactylClient(config_panel_url, config_panel_token) # possible: offline, online, starting, stopping, error self.server_power_status = "offline" self.current_vote_action = None self.voters = [] self.votable_messages = [] self.voting_time_start = 0 self.was_empty_last_check = False self.logger = logging.getLogger("tonymc.panel_cog") self.periodically_get_status.add_exception_type(NewConnectionError) self.periodically_get_status.add_exception_type(gaierror) self.periodically_get_status.add_exception_type(ConnectionError) self.periodically_get_status.add_exception_type(HTTPError) self.periodically_get_status.start() self.has_motion_expired.start() if config_shutdown_empty_server: self.check_if_should_turn_off.start()
def setUp(self): self.api = PterodactylClient(url='dummy', api_key='dummy')
# coding=utf-8 from pydactyl import PterodactylClient import os import datetime import zipfile import subprocess import logging import threading import sys from time import sleep client = PterodactylClient('PANEL_URL_HERE', '') logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") logging.disable(logging.DEBUG) currentDTStamp = datetime.datetime.now() CURRENT_TIME = currentDTStamp.strftime("%m-%d-%Y.%H-%M-%S") BUNGEE_SERVERS = [ "" ] # If you have any servers that do not support the /save-off, /save-on, and /save-all commands, add their UUID to this list. They will not be backed up BACKUP_DIRS = f"/srvBackup/{CURRENT_TIME}" CLEAN_BACKUP = True # If servers are offline right now (will not send any console commands) os.makedirs(BACKUP_DIRS, exist_ok=True) os.chdir(BACKUP_DIRS) def backupServer(_server: dict): serverID = _server["identifier"] serverUUID = _server["uuid"]
import discord import mysql.connector as mysql import private from pydactyl import PterodactylClient from discord.ext import commands, tasks # Enable Intents intents = discord.Intents.default() intents.members = True # Set Discord Client (aka "bot") discordClient = commands.Bot(command_prefix="w!", intents=intents) # Set MC Pterodactyl Console Client MCClient = PterodactylClient("https://panel.primedhosting.com/", private.PH_API_KEY) # Connect To DB DB_conn = mysql.connect( host=private.DB_conn, user=private.DBuser, password=private.DBpassword, ) # Set Up Vars cur = DB_conn.cursor() srv_id = "bf9213e8" # Ping the DB every 2 hours to keep the connection open. @tasks.loop(hours=2) async def db_ping(): # set default DB cur.execute(f"USE {private.DB_name};")
from discord.ext.commands import Bot from pydactyl import PterodactylClient from discord import Game import requests import os from time import sleep BOT_PREFIX = ('!') TOKEN = os.environ['BOT_TOKEN'] srv_id = os.environ['SERVER_ID'] client = Bot(command_prefix=BOT_PREFIX) panel_client = PterodactylClient('https://panel.freemc.host', os.environ['PTERO_TOKEN']) @client.command(name="start", description="Starts the Minecraft server", brief="Starts server", pass_context=True) async def startserver(ctx): try: response = panel_client.client.send_power_action(srv_id, 'start') if response.status_code == 204: await ctx.send("Starting the server, " + ctx.author.mention + ", enjoy!") except requests.exceptions.HTTPError: await ctx.send("Shit. There was a server error, " + ctx.author.mention + ". Try again later?")
async def show(self,ctx): em = discord.Embed(colour = discord.Colour.green()) db = sqlite3.connect("main.db") cursor = db.cursor() cursor.execute(f"SELECT * FROM USERCONFIGURATION WHERE user_id = '{ctx.author.id}'") result = cursor.fetchone() if result is None: em = discord.Embed(colour = discord.Colour.dark_red()) em.add_field(name= "<a:anim_cross:757875533030883379> Error <a:anim_cross:757875533030883379>", value= f"You aren't registered in the database! Please run the command {ctx.prefix}addapi") await ctx.send(embed=em) elif result is not None and result[1] is None: em = discord.Embed(colour = discord.Colour.dark_red()) em.add_field(name= "<a:anim_cross:757875533030883379> Error <a:anim_cross:757875533030883379>", value= f"You aren't registered in the database! Please run the command {ctx.prefix}addapi") await ctx.send(embed=em) # await ctx.author.send(embed=em) elif result is not None: token = str(result[1]) client = PterodactylClient('https://panel.danbot.host', token) myservers = client.client.list_servers() #myservers1 = client.servers.get_server_info(server_id='ce98995a') #myservers1 = client.client.get_server('1ccc3f0b', detail=True) #await ctx.send(myservers1) a = 0 a1 = 0 allo_id = 1 em.set_author(name = myservers[a1]['name']) em.description = f"ID: {allo_id}" em.add_field(name = "Server UUID: ", value = myservers[a1]['identifier']) em.add_field(name = "Memory: ", value = myservers[a1]['limits']['memory']) em.add_field(name = "Swap: ", value = myservers[a1]['limits']['swap']) em.add_field(name = "Disk: ", value = myservers[a1]['limits']['disk']) em.add_field(name = "IO : ", value = myservers[a1]['limits']['io']) em.add_field(name = "Cpu: ", value = myservers[a1]['limits']['cpu']) em.add_field(name = "Databases: ", value = myservers[a1]['feature_limits']['databases']) try: current = 1 pages2 = len(myservers) message = await ctx.send(f"Page {current}/{pages2}:") message1 = await ctx.send(embed=em) await message1.add_reaction("◀️") await message1.add_reaction("▶️") def check1(reaction, user): return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"] while True: reaction, user = await self.bot.wait_for("reaction_add", timeout=60, check=check1) if str(reaction.emoji) == "▶️" and current != pages2: current+=1 a1 +=1 allo_id +=1 em1 = discord.Embed(colour= discord.Colour.green()) em1.set_author(name = myservers[a1]['name']) em1.description = f"ID: {allo_id}" em1.add_field(name = "Server UUID: ", value = myservers[a1]['identifier']) em1.add_field(name = "Memory: ", value = myservers[a1]['limits']['memory']) em1.add_field(name = "Swap: ", value = myservers[a1]['limits']['swap']) em1.add_field(name = "Disk: ", value = myservers[a1]['limits']['disk']) em1.add_field(name = "IO : ", value = myservers[a1]['limits']['io']) em1.add_field(name = "Cpu: ", value = myservers[a1]['limits']['cpu']) em1.add_field(name = "Databases: ", value = myservers[a1]['feature_limits']['databases']) await message.edit(content = f"Page {current}/{pages2}:") await message1.edit(embed=em1) await message1.remove_reaction(reaction, user) elif str(reaction.emoji) == "◀️" and current > 1: current-=1 a1-=1 allo_id-=1 em2 = discord.Embed(colour= discord.Colour.green()) em2.description = f"ID: {allo_id}" em2.set_author(name = myservers[a1]['name']) em2.add_field(name = "Server UUID: ", value = myservers[a1]['identifier']) em2.add_field(name = "Memory: ", value = myservers[a1]['limits']['memory']) em2.add_field(name = "Swap: ", value = myservers[a1]['limits']['swap']) em2.add_field(name = "Disk: ", value = myservers[a1]['limits']['disk']) em2.add_field(name = "IO : ", value = myservers[a1]['limits']['io']) em2.add_field(name = "Cpu: ", value = myservers[a1]['limits']['cpu']) em2.add_field(name = "Databases: ", value = myservers[a1]['feature_limits']['databases']) await message.edit(content=f"Page {current}/{pages2}:") await message1.edit(embed=em2) await message1.remove_reaction(reaction, user) else: await message1.remove_reaction(reaction, user) except asyncio.TimeoutError: pass
""" Pterodactyl module helper class Ref: https://github.com/iamkubi/pydactyl """ import datetime import os from pydactyl import PterodactylClient restart_delay = 60 next_can_restart = 0 allowed_servers = {"sandbox": "Sandbox Vanilla"} pterodactylAPI = PterodactylClient(os.getenv("PTERODACTYL_URL"), os.getenv("PTERODACTYL_TOKEN")) def restart_server(server_name: str): global next_can_restart time_now = datetime.datetime.now() #Check can restart if next_can_restart > time_now.timestamp(): seconds = round(next_can_restart - time_now.timestamp()) seconds_str = "second" if seconds > 1: seconds_str += "s" return False, "restart timeout, try again in {0} {1}!".format( seconds, seconds_str)
from pydactyl import PterodactylClient import json import time import os import subprocess import importlib print("ATTEMPTING CONNECTION...") # Create a client to connect to the panel and authenticate with your API key. client = PterodactylClient('API ENDPOINT GOES HERE', 'API KEY GOES HERE') # Get a list of all servers the user has access to my_servers = client.client.list_servers() # Get the unique identifier for the first server. srv_id = my_servers[0]['identifier'] print("CONNECTION ESTABLISHED") def panic(): print("*********************************") print("*** PANIC MODE ACTIVATED ***") print("*********************************") srv_utilization = client.client.get_server_utilization(srv_id) print(json.dumps(srv_utilization, indent=4)) print("") print("") t = time.localtime() current_time = time.strftime("%H:%M:%S", t) print(current_time) print("")
import discord from discord.ext import commands import os, json, typing from pydactyl import PterodactylClient import traceback import textwrap import secrets try: serverclient = PterodactylClient(secrets.secrets_server_url, secrets.secrets_server_key) my_servers = serverclient.client.list_servers() srv_id = my_servers[0]['identifier'] except: pass class devCog(commands.Cog): """Developer commands""" def __init__(self, bot): self.bot = bot self.db_conn = bot.db_conn self.colour = 0xff9300 self.footer = 'Bot developed by DevilJamJar#0001\nWith a lot of help from ♿nizcomix#7532' self.thumb = 'https://styles.redditmedia.com/t5_3el0q/styles/communityIcon_iag4ayvh1eq41.jpg' #async def cog_check(self, ctx): #return ctx.author.id == 670564722218762240 # check for all commands in this cog @commands.group(invoke_without_command=True, aliases=['err']) async def error(self, ctx):
import random import sys import time import traceback import typing from datetime import datetime, date, time, timezone import discord import pymongo from discord.ext import commands from pydactyl import PterodactylClient bot = commands.Bot(command_prefix=',', case_insensitve=True) bot.launch_time = datetime.utcnow() client = PterodactylClient('PANEL_LINK', 'SECRET_APPLICATION_API') # ONLINE + STATUS EVENT @bot.event async def on_ready(): print( f'\n\nLogged in as: {bot.user.name} - {bot.user.id}\nVersion: {discord.__version__}\n' ) activity = discord.Activity(name='CUSTOM_STATUS', type=discord.ActivityType.watching) await bot.change_presence(activity=activity) print(f'Successfully logged in and booted...!') # UPTIME COMMAND