Coder Social home page Coder Social logo

ptero4j's Introduction

Ptero4J

A java library to interact with the Admin API of Pterodactyl Panel.

This project is currently not finished! Feel free to use it, but there's no guarantee it will 100% work.

Content:

General Concepts

Controllers

Controllers are the objects that make the requests to the panel. There is a controller class for every Model and they all derive from Controller. With a controller class you can fetch resources from the panel, instantiate Action objects and perform generic actions. All Controllers are instantiated and 'kept' in the PteroAdminAPI or PteroUserAPI class. Example:

UsersController usersController = api.getUsersController();
List<User> users = usersController.getAllUsers();

Actions

There are two type of actions in this library; Explicit and Generic. Explicit Actions often need more details.

  • An example of an explicit action is ServerUpdateDetailsAction. When calling this action an object of this class will be returned and it behaves like a builder, when all wanted settings have been set you call the execute() method and it will make the call to the panel API.
  • An example of a generic action is suspending a server, this can simply be done by calling suspend() on a Server object.

Example:

// Explicit Action
server.editBuild().setMemory(2048).execute();

// Generic Action
server.suspend();

Admin and User API

The library is split into two seperate APIs, the PteroUserAPI and the PteroAdminAPI. This is done because the Pterodactyl Panel API is actually split up into these two sections aswell.

  • The Admin API is used to get/modify/create objects in the Panel.
  • The User API is used to send commands and power options to servers.

Maven Repository

In your pom.xml you need add the Jitpack repository and the panel dependency

    <repositories>
        <!-- Jitpack repo -->
        <repository>
            <id>jitpack</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>
    
    <dependencies>
        <!-- Panel API -->
        <dependency>
            <groupId>com.github.stanjg</groupId>
            <artifactId>Ptero4J</artifactId>
            <version>master-SNAPSHOT</version>
        </dependency>
    </dependencies>

Or you can clone the project and run a "mvn clean install" to get a compiled jar file.

Usage Examples

Let's imagine that a server is overdue, you have it's ID and you want to suspend the server

public static void main(String[] args) {
    // First you instantiate the API class (Admin in this case) 
    // and give it your panel URL and API key
    PteroAdminAPI api = new PteroAdminAPI("https://panel.pterodactyl.io/", "api key");
    
    // Then fetch the server using the ServersController
    Server server = api.getServersController().getServer(12 /* Server ID */);
    
    // Now you can suspend the server using it's generic action
    server.suspend();
    
    // You're all set! The server has been suspended.
}

Now let's imagine that you want to change the amount of ram a server can use, here's how:

public static void main(String[] args) {
    // First you instantiate the API class (Admin in this case) 
    // and give it your panel URL and API key
    PteroAdminAPI api = new PteroAdminAPI("https://panel.pterodactyl.io/", "api key");
    
    // Then fetch the server using the ServersController
    Server server = api.getServersController().getServer(12 /* Server ID */);
    
    // Now you can update memory of the server using it's explicit action
    server.editBuild().setMemory(4096 /* in MBs, so this is 4GB */).execute();
    
    // You're all set! The memory has been updated.
}

One last example, you want to update the email and the name of a user

public static void main(String[] args) {
    // First you instantiate the API class (Admin in this case) 
    // and give it your panel URL and API key
    PteroAdminAPI api = new PteroAdminAPI("https://panel.pterodactyl.io/", "api key");
    
    // Then fetch the user using the UsersController
    User user = api.getUsersController().getUser(88 /* User ID */);
    
    // Now you can update the users emai and username using it's explicit action
    user.edit().setEmail("[email protected]").setName("stanjg").execute();
    
    // You're all set! The email and username has been updated.
}

Documentation

Admin API

Servers

Server Object
// Fields
server.getLongId()
server.getName()
server.getDescription()
server.getUuid()
server.getShortId()
server.getAllocationId()
server.getEggId()
server.getNestId()
server.getExternalId()
server.getPackId()
server.getNodeId()
server.getOwnerId()
server.isSuspended()

// Field sub classes
server.getContainer()
    container.getStartupCommand()
    container.getImage()
    container.isInstalled()
    container.getEnvironmentVariables()
    
server.getLimits()
    limits.getDisk()
    limits.getMemory()
    limits.getSwap()
    limits.getIo()
    limits.getCpu()
    
server.getFeatureLimits()
    featureLimits.getMaxDatabases()
    featureLimits.getMaxAllocations()

// Relationships
server.getOwner()
server.getLocation()
server.getNode()
Server Controller
ServersController controller = api.getServersController();

// Fetch All Servers
List<Server> servers = controller.getAllServers();

// Fetch Servers With Search Query
List<Server> servers = controller.getServers("search");

// Fetch Single Server By ID
Server server = controller.getServer(8888);

// Fetch Page of Servers
List<Server> servers = controller.getServerPage(1);

// Fetch Servers For User by ID
List<Server> servers = controller.getServersForUser(88);
Server Actions
// Explicit Actions
server.editDetails()            -> ServerUpdateDetailsAction
server.editBuild()              -> ServerUpdateBuildAction
server.editStartup()            -> ServerUpdateStartupAction
serversController.createNew()   -> ServerCreateAction

// Generic Actions
server.suspend()
server.unsuspend()
server.reinstall()
server.rebuild()
server.delete()

Users

User Object
// Fields
user.getId()
user.getExternalId()
user.getUuid()
user.getUsername()
user.getEmail()
user.getFirstName()
user.getLastName()
user.getLangauge()
user.isAdmin()
user.hasTotpEnabled()

// Relationships
user.getServers()
User Controller
UsersController controller = api.getUsersController();

// Fetch All Users
List<User> users = controller.getAllUsers();

// Fetch Users With Search Query
List<User> users = controller.getUsers("search");

// Fetch Single User By ID
User users = controller.getUser(8888);

// Fetch Page of Users
List<User> users = controller.getUserPage(1);

// Fetch Users For User by ID
List<User> users = controller.getServersForUser(88);
User Actions
// Explicit Actions
user.edit()                 -> UserUpdateAction
usersController.createNew() -> UserCreateAction

// Generic Actions
user.delete()

User API

User Servers

UserServer Object
// Fields
server.getId()
server.getUuid()
server.getName()
server.getDescription()
server.isOwner()
server.getLimits()
server.getFeatureLimits()

// Field sub classes
server.getLimits()
    limits.getDisk()
    limits.getMemory()
    limits.getSwap()
    limits.getIo()
    limits.getCpu()
    
server.getFeatureLimits()
    featureLimits.getMaxDatabases()
    featureLimits.getMaxAllocations()
UserServers Controller
UserServersController controller = api.getServersController();

// Fetch all servers you have access to
List<Server> servers = controller.getServers();

// Fetch server by ID
UserServer server = controller.getServer("aaaa88");
UserServers Actions
// Generic Actions
server.sendCommand("kick stanjg")
server.start()
server.stop()
server.restart()
server.kill()
server.sendPowerAction(PowerAction.START)

That's it :)

ptero4j's People

Contributors

doc94 avatar erdbeerbaerlp avatar stanjg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ptero4j's Issues

ServerCreateAction Documentation

From what I could find, there is no documentation for the ServerCreateAction class. I'm looking to use this api to create servers and I've been unable to figure out the ServerCreateAction class. Perhaps documentation for it could be made?

Probably an update caused the API fully unusable

Hey.

First of all, i really appreciate this project. A really good idea, and would be very useful if you make it working.
So now, i'm trying to use it first time and found the issue
Exception in thread "main" org.json.JSONException: JSONObject["databases"] is not an int. when tried to get a server's name from userServersController.

Probably the code isn't working with the latest version of Pterodactyl panel, there was a huge API update, everything changed. For the reasons mentioned above, I do not think the code will work at all.

Hope you enjoy coding, and will fix it as you can.

Permissions

Im not the admin of the panel and just got a user key. Can i use it anyways? And how do I get my server?

Very stupidly easy error, but just can't seem to fix

This is my error
Ptero4J loaded! Successfully made contact with the panel. Exception in thread "main" java.lang.NoSuchMethodError: org.json.JSONObject.keySet()Ljava/util/Set; at com.stanjg.ptero4j.entities.objects.server.ServerContainer.getEnvironmentVariablesMap(ServerContainer.java:32) at com.stanjg.ptero4j.entities.objects.server.ServerContainer.<init>(ServerContainer.java:27) at com.stanjg.ptero4j.entities.objects.server.ServerContainer.<init>(ServerContainer.java:15) at com.stanjg.ptero4j.entities.panel.admin.Server.<init>(Server.java:39) at com.stanjg.ptero4j.controllers.admin.ServersController.getNewInstance(ServersController.java:70) at com.stanjg.ptero4j.controllers.admin.ServersController.getNewInstance(ServersController.java:18) at com.stanjg.ptero4j.controllers.admin.ResourceController.addPageToList(ResourceController.java:266) at com.stanjg.ptero4j.controllers.admin.ResourceController.getAllResources(ResourceController.java:204) at com.stanjg.ptero4j.controllers.admin.ServersController.getAllServers(ServersController.java:41) at Test.main(Test.java:21)
And this is my code
`import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.List;
import com.stanjg.ptero4j.PteroAdminAPI;
import com.stanjg.ptero4j.controllers.admin.ServersController;
import com.stanjg.ptero4j.controllers.admin.UsersController;
import com.stanjg.ptero4j.entities.panel.admin.Server;
import com.stanjg.ptero4j.entities.panel.admin.User;

public class Test {

public static void main(String[] args) {
	PteroAdminAPI api = new PteroAdminAPI("http://panel.themajesticnetwork.com/", "s4nCuW6BAacGTcUQVXtq559AR6UrqhUyWm8LiZxIcrUlanwH");

    // Then fetch the server using the ServersController
    ServersController servers = api.getServersController();

    List<Server> server = servers.getAllServers();
    
    List<Server> serverPage = servers.getServerPage(1);
    
    
    
    UsersController usersController = api.getUsersController();
    List<User> users = usersController.getUsers("search");
	try{
	  
		String serverSection = "SYHAT";
		String userSection = "UYA";
  	  // Create file 
  	  FileWriter fstream = new FileWriter("details.txt");
  	  BufferedWriter out = new BufferedWriter(fstream);
  	  out.write(serverSection + ": " + serverPage);
  	  
  	  
  	  //Close the output stream
  	  out.close();
  	  }catch (Exception e){//Catch exception if any
  	  System.err.println("Error: " + e.getMessage());
  	  }
}

}
`
And I cant seem to find out how to fix this, help me please.

Starting servers via the API

Hello,
I have a question. I want to use the API as a admin-tool. So I tried to add a function which could start the servers:
(Server.java, package: com.stanjg.ptero4.entities.panel.admin)
`public boolean start() {

    JSONObject test;
    test = new JSONObject();
    test.put("signal", "start");
    System.out.println(test);
    return new GenericAdminAction(api, "/servers/"+this.shortId+"/power", HTTPMethod.POST, test).execute() == 204;
}`

But the console returns an warning and the server doesn't start:
An invalid request was made by the library, please create an issue on github. POST https://control.junico.de/api/application/servers/8/power

I saw that you have to transmit a parameter to the server via the url so that the server know what poweraction you want to perform: https://dashflo.net/docs/api/pterodactyl/v0.7/#send-power-action

Now my question is: Is it possible to send poweractions with this API or what have I done wrong?
Sorry for my bad english.

I hope anyone can help me out with this. If you need any more informations just tell me.
I whish you all a beautiful day.

TheAimWolf

Error 422 When creating server from BungeeCord

Hi there,

I'm trying to make a system where I can deploy new servers from inside our Bungeecord proxy using this API. But now comes the point where I'm getting errors... I'm getting this:

>.... [02:27:49 INFO]: An error occurred while making a request to the panel, if the issue persists please create an issue on github.
>.... [02:27:49 INFO]: 422 POST https://panel.snl.bruijns.tech/api/application/servers

And this is my code:

public class ServerHandler extends Command {

    public ServerHandler(ServerDeployer serverDeployer) {
        super("deploypf");
    }

    public static void deployNew() {
        PteroAdminAPI api = new PteroAdminAPI("https://panel.snl.bruijns.tech/", "I HAVE MY KEY HERE USUALLY, BUT REMOVED IT FOR NOW.");
        ServerCreateAction server = api.getServersController().createNew();
        server.setName("pf01").setDescription("TEST FOR PF01").setUserId(2).setAllocation(1).setPortRange(String.valueOf(25657)).setLimits(1024, -1, 0, 500, 0).setEggId(17).setPackId(1).setDockerImage("quay.io/pterodactyl/core:java").setStartOnCompletion(true).execute();
    }

    @Override
    public void execute(CommandSender sender, String[] args) {
        if(sender instanceof ProxiedPlayer) {
            ProxiedPlayer p = (ProxiedPlayer) sender;
            deployNew();
        }
    }
}

Is there any possibility you can help me solving my issue?

I hope to hear from you!

Server Create

Hello, how to create server? I have code, but code dont working:

		try {
			Main.api.getServersController()
			.createNew()
			.setName(serverowner)
			.setDescription("Owner: " + serverowner)
			.setUserId(9)
			.setEggId(3)
			.setAllocation(1)
			.setPackId(1)
			.setDockerImage("quay.io/pterodactyl/core:java")
			.setLimits(512, 0, 3000, 0, 100)
			.setFeatureLimits(0, 0)
			.setDedicatedIp(true)
			.setPortRange(portRange)
			.setStartOnCompletion(true)
			.setFeatureLimits(0, 0)
			.setDeployLocations(ids)
			.setSkipScripts(false)
			.setExternalId(503)
			.execute();
		} catch(Exception e) {
			e.printStackTrace();
		}

why?

error:
An error occurred while making a request to the panel, if the issue persists please create an issue on github.
422 POST https://panel.gamerhost.pro/api/application/servers

I can't start a connection

public static void main(String[] args) {
System.out.println("test");
PteroUserAPI api = new PteroUserAPI("https://ptero.correct.url", "ptero.correct.api.token");
System.out.println(api.getServersController().getServers());
}

As soon as I run this code, it just shuts down and nothing appears on the console
I apologize for the terrible formatting here of the issue on github, I have no experience

image

Getting a server ID through a string

Hi im trying to use the api to get the server ID through a string such as Game1 so i can restart/suspend ect however i'm not entirely sure how i can do this iv tried an array and a list but i just don't know

any help would be much appreciated

HTTP 201 is not a error?

Hey, got the following while creating the user (creating worked)

An error occurred while making a request to the panel, if the issue persists please create an issue on github.
201 POST https://panel.example.com/api/application/users

Code used:

            adminInterface.getAdminAPI().getUsersController().createNew()
                    .setEmail(customerId.toString() + "@example.com")
                    .setUsername(customerId.toString())
                    .setPassword(customerId.toString())
                    .setFirstName("Han")
                    .setLastName("Solo")
                    .setLanguage("en")
                    .execute();

Regards

[Suggestion] Get console log from server

It would be great if it would be possible to get the current console log as an string or an string array.

I think about something like this:

int logLines = 2;
String[] logList = userServer.getLogAsList(logLines);
//Output: {"Player234 joined the game","<Player234> Hi"}

String log = userServer.getLogAsString(logLines);
//Output: "Player234 joined the game\n<Player234> Hi"

Start using exceptions

Currently there is no error catching. For example if a key does not have permission for a certain action the result will not be pretty.

Start using the exceptions that I have created.

Console

Bonjour,

Je voulais savoir est t'il possible de récupérer la console du panel Client ?

Error okhttp3/MediaType

Good evening,

I want to use this API but when I get the panel url and the key it shows me this error I don't understand why.

Someone can help me please ?

Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: okhttp3/MediaType
	at com.stanjg.ptero4j.controllers.Controller.<clinit>(Controller.java:20)
	at com.stanjg.ptero4j.PteroAdminAPI.<init>(PteroAdminAPI.java:29)
	at fr.blackbalrog.info.Connect.getInfo(Connect.java:12)
	at fr.blackbalrog.PPanel.onEvent(PPanel.java:44)
	at fr.theshark34.swinger.abstractcomponents.AbstractButton.mouseReleased(AbstractButton.java:81)
	at java.desktop/java.awt.Component.processMouseEvent(Component.java:6614)
	at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
	at java.desktop/java.awt.Component.processEvent(Component.java:6379)
	at java.desktop/java.awt.Container.processEvent(Container.java:2263)
	at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4990)
	at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2321)
	at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
	at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4919)
	at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4548)
	at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4489)
	at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2307)
	at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2769)
	at java.desktop/java.awt.Component.dispatchEvent(Component.java:4822)
	at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
	at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
	at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
	at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
	at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
	at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.ClassNotFoundException: okhttp3.MediaType
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
	... 35 more

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.