Creating an update checker that checks for updates

Sep 21, 2019
Creating an update checker that checks for updates
  • Creating an update checker, that checks for updates
    This is a simple tutorial on how to create an update checker for your plugin.
    There is only one requirement: Your resource must be uploaded on SpigotMC.org.

    Step 1 - Getting your resource's id
    At first, you need your resource's id which you can find in your resource's URL.
    Your resources URL should look similar like this:
    https://www.spigotmc.org/resources/<resource's name>.<resource's id>

    Step 2 - Getting the Spigot API URL
    This is very easy. This is the Spigot API URL:
    https://api.spigotmc.org/legacy/update.php?resource=<resource's id>
    Just replace the id at the end with your resource's id!


    Step 3 - Creating the update checker
    Code (Java):
    public class UpdateChecker {

        private Plugin plugin;
        private int resourceId;

        public UpdateChecker(Plugin plugin, int resourceId) {
            this.plugin = plugin;
            this.resourceId = resourceId;
        }

        public void getVersion(final Consumer<String> consumer) {
            Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> {
                try (InputStream inputStream = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + this.resourceId).openStream(); Scanner scanner = new Scanner(inputStream)) {
                    if (scanner.hasNext()) {
                        consumer.accept(scanner.next());
                    }
                } catch (IOException exception) {
                    this.plugin.getLogger().info("Cannot look for updates: " + exception.getMessage());
                }
            });
        }
    }
    You have to pass an instance of your class which extends JavaPlugin through its constructor to use a BukkitScheduler. The BukkitScheduler is used to run the update check asynchronously, otherwhise the whole server will freeze while it runs. You also have to pass the resource's id through the constructor.

    Then you can create a new instance of the update checker in your onEnable method like this:

    Code (Java):
        @Override
        public void onEnable() {
            Logger logger = this.getLogger();
     
            new UpdateChecker(this, 12345).getVersion(version -> {
                if (this.getDescription().getVersion().equalsIgnoreCase(version)) {
                    logger.info("There is not a new update available.");
                } else {
                    logger.info("There is a new update available.");
                }
            });
        }
    It looks for a resource with the id 12345 and compares its version with the version registered in the plugin.yml file.






  • Loading...
  • Loading...