> For the complete documentation index, see [llms.txt](https://pintux.gitbook.io/pintux-support/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://pintux.gitbook.io/pintux-support/developers/building-an-addon.md).

# Building an Addon

An addon is a normal Paper plugin that turns another plugin's chest GUIs into Bedrock forms, using BedrockGUI to send the forms. The four official addons (Essentials, Bedwars, Homestead, PhoenixDuels) are built the same way, and this page follows them step by step, so your addon behaves like theirs and server owners already know how to configure it.

{% hint style="info" %}
Addons run on Paper or Folia with BedrockGUI and Floodgate installed. Proxies (Velocity, BungeeCord) have no inventories or plugin GUIs to wrap, so addons are Paper only. For the API reference see [BedrockGUI API](https://pintux.gitbook.io/pintux-support/developers/bedrockgui-api.md).
{% endhint %}

### What an addon does

Every official addon does four things:

1. **Reads the wrapped plugin** through its API: homes, arenas, regions, duel queues.
2. **Builds Bedrock forms** from that data with the BedrockGUI form builders.
3. **Registers actions** (`bw_shop_main`, `hs_regions`, `essentials_hub`) so every button, and every hand-written menu on the server, can open its screens.
4. **Intercepts** the plugin's own commands, events or chest menus, for Bedrock players only, and opens the form instead. Java players keep the original GUI.

### 1. Project setup

The official addons are modules of the BedrockGUI repository and compile against the core modules directly. Your own addon compiles against the released jar instead. Take `BedrockGUI-Paper-<version>.jar` from the [GitHub release](https://github.com/pintux98/BedrockGUI/releases/latest): it contains the whole API plus the Paper helpers in `it.pintux.life.paper.addon`. (`BedrockGUI-API.jar` has the platform-independent API only, without those helpers.)

```groovy
plugins {
    id 'java'
}

java {
    toolchain.languageVersion = JavaLanguageVersion.of(21)
}

repositories {
    mavenCentral()
    maven { url = "https://repo.papermc.io/repository/maven-public/" }
    maven { url = "https://repo.opencollab.dev/main/" }
}

dependencies {
    compileOnly "io.papermc.paper:paper-api:1.20.6-R0.1-SNAPSHOT"
    compileOnly "org.geysermc.floodgate:api:2.2.5-SNAPSHOT"
    compileOnly files("libs/BedrockGUI-Paper-2.0.12.jar")
    compileOnly "com.example:wrapped-plugin-api:1.0"
}

processResources {
    filesMatching('plugin.yml') {
        expand(version: project.version)
    }
}
```

Everything is `compileOnly`: BedrockGUI, Floodgate and the wrapped plugin are already on the server, so never shade them into your jar. The Floodgate API brings in Cumulus, which the form builders use.

### 2. plugin.yml

```yaml
name: MyAddon
version: '${version}'
main: com.example.myaddon.MyAddonPlugin
api-version: '1.20.6'
depend:
  - BedrockGUI
softdepend:
  - WrappedPlugin
  - floodgate
commands:
  myaddon:
    description: Reload MyAddon
    usage: /myaddon reload
```

* `depend: BedrockGUI` makes your plugin enable after BedrockGUI, so `BedrockGUIApi.getInstance()` is ready in `onEnable`.
* The wrapped plugin is a `softdepend`, never a `depend`. Your jar must still load when it is missing, and say "unavailable" instead of failing to enable.
* The official addons do not declare `folia-supported`, because they schedule with the Bukkit scheduler. Only add it if you schedule on the player or region scheduler throughout.

### 3. Package layout

All four addons split the code the same way. Copy the shape even for a small addon; it keeps the wrapped plugin's API out of your form code.

| Package                   | Holds                                                                                  | Example                                           |
| ------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------- |
| `api`                     | One interface per feature the forms need                                               | `ShopProvider`, `ArenaProvider`                   |
| `provider` (or `gateway`) | One implementation per supported plugin or version, the only code that touches its API | `BedWars2023ShopProvider`, `HomesteadGatewayImpl` |
| `service`                 | Builds and sends the forms; one `Bedrock…Service` per screen group                     | `BedrockShopService`                              |
| `action`                  | `ActionHandler`s that open screens or run operations                                   | `OpenShopMainAction`                              |
| `listener`                | Command, event and inventory interception                                              | `BedwarsCommandListener`, `MenuInterceptListener` |
| `config`                  | Typed access to `config.yml`                                                           | `BedwarsAddonConfiguration`                       |
| `command`                 | `/myaddon reload`                                                                      | `BedwarsAddonCommand`                             |

### 4. Enabling the addon

The Bedwars Addon's `onEnable` is the template the others follow:

```java
public final class MyAddonPlugin extends JavaPlugin {
    private MyAddonConfiguration config;
    private BedrockPlayerDetector detector;
    private BedrockShopService shopService;

    @Override
    public void onEnable() {
        getCommand("myaddon").setExecutor(new MyAddonCommand(this));
        config = MyAddonConfiguration.load(this);
        setup();
    }

    private void setup() {
        detector = new FloodgateBedrockPlayerDetector();

        ShopProvider provider = null;
        if (getServer().getPluginManager().isPluginEnabled("WrappedPlugin")) {
            provider = new WrappedPluginShopProvider();
        } else {
            getLogger().warning("WrappedPlugin not found; forms will say the shop is unavailable.");
        }

        if (config.moduleShop()) {
            shopService = new BedrockShopService(config, provider, detector);
        }

        if (config.integratedGui()) {
            getServer().getPluginManager().registerEvents(new MyCommandListener(this, config, shopService), this);
        }

        BedrockGUIApi api = apiOrNull();
        if (api != null && (config.integratedGui() || config.registerActions())) {
            api.registerActionHandler(new OpenShopAction(shopService));
            api.registerActionHandler(new ShopBuyAction(shopService));
        }
    }

    private BedrockGUIApi apiOrNull() {
        try {
            return BedrockGUIApi.getInstance();
        } catch (IllegalStateException e) {
            getLogger().warning("BedrockGUI is not loaded; actions are not registered.");
            return null;
        }
    }
}
```

The order matters:

1. **Config first**, so every later step reads the owner's settings.
2. **Detect the wrapped plugin with `isPluginEnabled`**, not `getPlugin(...) != null`. A plugin can be installed and still fail to enable (BedWars2023 does without TAB or on an unsupported Paper version). `getPlugin` still returns it, and every call into it then fails.
3. **Pick a provider per feature.** With several supported plugins, check them in order and keep the first that is enabled (Essentials: EssentialsX, CMI, HuskHomes; Bedwars: BedWars2023, BedWars1058, ScreamingBedWars). An owner can force one in config.
4. **Build the services, even without a provider.** A service with no provider answers "currently unavailable" instead of the command failing.
5. **Register listeners only when `integrated-gui` is on.**
6. **Register actions when `integrated-gui` or `register-actions` is on**, because the built-in forms' buttons run those same actions.

When a newer version of the wrapped plugin adds an event or method, check that it exists before registering against it, so older versions still load:

```java
private void registerIfPresent(String eventClass, Listener listener) {
    try {
        Class.forName(eventClass);
        getServer().getPluginManager().registerEvents(listener, this);
    } catch (ClassNotFoundException e) {
        getLogger().warning("Interception off: " + eventClass + " is not in this version.");
    }
}
```

### 5. Providers never block

A provider method is called from a form callback, which runs on the server thread. If the wrapped plugin answers asynchronously, take a callback instead of waiting:

```java
public interface HomesProvider {
    void listHomes(Player player, Consumer<List<String>> callback);
    void teleport(Player player, String home, Consumer<Boolean> callback);
}
```

HuskHomes completes its futures on the server thread, so a provider that called `.join()` there would wait forever. Use the plugin's typed API rather than reflection: the CMI providers once called methods by reflection that later CMI versions no longer had, and warps, kits and TPA silently stopped working. A typed call fails at compile time, or shows up in a binary check, instead.

When the plugin enforces its own rules (costs, cooldowns, limits, conditions), go through those rules instead of reimplementing them. The Essentials Addon claims CMI kits by running CMI's own `kit` command for the player, so CMI applies its cost, cooldown and messages, then reads CMI's data to see whether the claim happened.

### 6. Services build the forms

A service owns one group of screens. Every `open…` method follows the same steps:

```java
public final class BedrockShopService {
    private final MyAddonConfiguration config;
    private final ShopProvider provider;
    private final BedrockPlayerDetector detector;

    public boolean shouldHandle(Player player) {
        return player != null && detector.isBedrockPlayer(player);
    }

    public void openMain(Player player) {
        BedrockGUIApi api;
        try {
            api = BedrockGUIApi.getInstance();
        } catch (IllegalStateException e) {
            AddonText.send(player, config.shopUnavailable());
            return;
        }
        if (provider == null) {
            AddonText.send(player, config.shopUnavailable());
            return;
        }
        if (!provider.isInGame(player)) {
            AddonText.send(player, config.shopNotInGame());
            return;
        }

        BedrockGUIApi.SimpleFormBuilder form = api.createSimpleForm(config.shopTitle())
                .content(config.shopContent());
        for (ShopCategory category : provider.categories(player)) {
            String action = "my_shop_category:" + ActionPayloads.encode(category.id());
            form.button(category.name(), category.icon(),
                    fp -> api.executeActionString(fp, action, context("shop-main")));
        }
        form.button(config.closeButton(), fp -> { });
        form.send(new PaperPlayer(player));
    }

    private ActionSystem.ActionContext context(String menu) {
        return ActionSystem.ActionContext.builder().menuName(menu).formType("my-shop").build();
    }
}
```

* **Check state before building the form.** If the player is somewhere the screen makes no sense, say so in chat. The Bedwars shop once opened outside a match and threw a `NullPointerException`; its upgrades form once showed only a Close button with no explanation.
* **Buttons run action strings, not code.** A button that runs `my_shop_category:<id>` goes through the same handler a server owner can call from YAML, so built-in and hand-written menus behave identically.
* **Encode values in action strings.** Names can contain spaces, colons or colour codes. The Bedwars Addon encodes arena names and shop ids as URL-safe Base64 and decodes them in the handler.
* **Send every message through `AddonText.send`**, so `&` and hex colours and placeholders work the same as in BedrockGUI's own messages.
* **Wrap a `Player` with `new PaperPlayer(player)`** to send a form; turn a `FormPlayer` back into a Bukkit `Player` with `FormPlayerResolver.resolve`.

#### Reading typed input

Answers in a custom form are keyed by a name derived from each component's label: colour codes and punctuation are stripped, and `"Player Name"` becomes `player_name`. Read answers through the same rule core uses, never your own copy of it:

```java
api.createCustomForm(config.inviteTitle())
        .input(label, config.invitePlaceholder(), "")
        .onSubmit(results -> {
            Object value = results.get(FormComponentNames.derive(label));
            String name = value == null ? "" : value.toString().trim();
            if (name.isBlank()) {
                AddonText.send(player, config.inviteInvalid());
                return;
            }
            provider.invite(player, name);
        })
        .send(new PaperPlayer(player));
```

`FormComponentNames` is in `it.pintux.life.common.utils`. Or set the key yourself with `namedInput(name, label, placeholder, default)`. Homestead and PhoenixDuels once kept their own copy of the naming rule; when core changed it, every text box in both addons read as empty.

### 7. Actions

Name every action type with a short prefix for your addon (`bw_`, `hs_`, `essentials_`), since action types are global across the server. The official addons use two styles:

**One class per action** (Bedwars), when actions differ a lot:

```java
public final class OpenShopAction implements ActionSystem.ActionHandler {
    private final BedrockShopService service;

    public OpenShopAction(BedrockShopService service) {
        this.service = service;
    }

    @Override public String getActionType() { return "my_shop_main"; }

    @Override
    public ActionSystem.ActionResult execute(FormPlayer player, String value, ActionSystem.ActionContext context) {
        Player bukkit = FormPlayerResolver.resolve(player);
        if (bukkit == null) {
            return ActionSystem.ActionResult.failure("Player is not online");
        }
        service.openMain(bukkit);
        return ActionSystem.ActionResult.success();
    }

    @Override public boolean isValidAction(String value) { return true; }
    @Override public String getDescription() { return "Opens the shop form"; }
    @Override public String[] getUsageExamples() { return new String[]{"my_shop_main:"}; }
}
```

**One reusable handler and a routing table** (Homestead, PhoenixDuels), when there are dozens of navigation actions:

```java
register(api, "hs_regions", "Open the region list",
        (player, value) -> regionService.openRegionList(player, page(value)));
register(api, "hs_region_menu", "Open a region",
        (player, value) -> regionService.openRegionMenu(player, Payloads.regionId(value)));
```

Close and Back buttons that do nothing still need a handler (the Bedwars Addon registers a no-op `bw_shop_close`), otherwise validation reports an unknown action.

Owners use your actions in their own menus like any built-in action:

```yaml
buttons:
  shop:
    text: "&aShop"
    onClick: "my_shop_main:"
```

### 8. Intercepting for Bedrock players

There are three ways to know a Bedrock player wants one of the wrapped plugin's screens. Every one of them checks `shouldHandle(player)` first, so Java players are never touched.

**Commands.** Owners list the commands to take over in `config.yml`. Match them with `CommandAliases`, which ignores the leading `/`, `plugin:` prefixes, case and CMI's `/cmi` aliases. Only take over the bare command, so `/bw join arena1` still reaches the plugin:

```java
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
    String root = CommandAliases.rootOf(event.getMessage());
    if (root == null || CommandAliases.argsOf(event.getMessage()).length > 0) return;
    if (!shopCommands.matches(root) || !shopService.shouldHandle(event.getPlayer())) return;

    event.setCancelled(true);
    Player player = event.getPlayer();
    plugin.getServer().getScheduler().runTask(plugin, () -> shopService.openMain(player));
}
```

`shopCommands` comes from `CommandAliases.of(config.getStringList("commands.shop"))`. Ship the list empty when command names differ between setups, as the Bedwars Addon does.

**The plugin's own events.** If the plugin fires an event before it opens its GUI (BedWars2023's `ShopOpenEvent`, Homestead's `MenuOpenEvent`), cancel it and open the form. Register such listeners with the class check from step 4.

**The open inventory.** With no event, catch `InventoryOpenEvent` and identify which menu is opening from the inventory itself, not from its title, since titles are translated and coloured. The PhoenixDuels Addon maps each menu's layout object back to its registry key, rebuilds that map when PhoenixDuels reloads, and logs how many keys resolved at startup.

Leave some screens alone: drag-and-drop inventories, hotbar layouts, and generic pickers whose meaning depends on the screen that opened them cannot work as forms.

### 9. Config

All four addons share this shape:

```yaml
config-version: 1

integrated-gui: true
register-actions: true

commands:
  shop: []

modules:
  shop: true
```

* `integrated-gui: false` turns off the built-in forms and interception but keeps the actions, so an owner can design every menu themselves.
* Module switches let an owner use only part of the addon.
* Every player-facing text and button label is a config key, with colour codes.

Load the file through `ConfigMigrator`, so owners get new keys without losing their edits:

```java
File file = ConfigMigrator
        .of(plugin.getDataFolder(), "config.yml", () -> plugin.getResource("config.yml"),
                plugin.getLogger()::info, plugin.getLogger()::warning)
        .migrate()
        .getFile();
YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
```

`ConfigMigrator` only merges new keys when the owner's `config-version` differs from your bundled one. **Bump `config-version` whenever you add a key**, or existing servers never receive it.

### 10. Reload

`/myaddon reload` tears everything down and runs setup again:

```java
public void reload() {
    HandlerList.unregisterAll(this);
    try {
        BedrockGUIApi.getInstance().getActionRegistry().unregisterHandlersFrom(getClass().getClassLoader());
    } catch (IllegalStateException ignored) {
    }
    config = MyAddonConfiguration.load(this);
    setup();
}
```

Unregister before registering again, so no listener or handler keeps a service built from the old config. When your plugin is disabled, BedrockGUI removes its action handlers by itself.

### 11. Testing

* **Test as a Bedrock player.** Run a Paper server with Geyser and Floodgate and join from a Bedrock client. Forms behave differently from chest GUIs, and a Java client never sees them.
* **Click every path**: each button, Back, Close, closing the form with X, empty and invalid text input, and a second player for anything with invites or requests.
* **Test without the wrapped plugin, and with it installed but disabled.** Both must answer "unavailable", not throw.
* **Test each supported version of the wrapped plugin.** A method that changed signature compiles against one version and fails at runtime on another. Homestead's `deleteRegion` changed between an alpha and the release, and Delete Region silently did nothing on the alpha.
* **Watch the console** while testing; a single stack trace usually points straight at the bug.

### Checklist

* [ ] `depend: BedrockGUI`, wrapped plugin as `softdepend`, everything `compileOnly`.
* [ ] Wrapped plugin detected with `isPluginEnabled`; the addon still loads without it.
* [ ] Only the provider classes touch the wrapped plugin's API; typed calls, no reflection.
* [ ] Providers never block the server thread.
* [ ] Every interception checks for a Bedrock player first.
* [ ] Buttons run your registered actions; action types share one prefix.
* [ ] Typed input read with `FormComponentNames.derive` or `namedInput`.
* [ ] Messages sent with `AddonText`; every text is a config key.
* [ ] `ConfigMigrator` with `config-version`, bumped on every new key.
* [ ] `reload` unregisters listeners and handlers before setting up again.
* [ ] Tested from a real Bedrock client, with and without the wrapped plugin.
