> For the complete documentation index, see [llms.txt](https://docs.aethercube.fr/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aethercube.fr/developers/plugins/events.md). Agents can also search and read this documentation through its [MCP server](https://docs.aethercube.fr/~gitbook/mcp).

# Events

Events are how your plugin reacts to the game, changes the outcome of something, or stops it. This page starts with a small listener, then lists every event the server fires. If you hit a case no event covers, tell me: new events are cheap to add.

## Listening

A listener is a class that implements the marker interface `Listener`. Each handler is a method with the `@EventHandler` annotation, returns `void` and takes exactly one event.

```java
import com.velyorix.game.api.event.EventHandler;
import com.velyorix.game.api.event.EventPriority;
import com.velyorix.game.api.event.Listener;
import com.velyorix.game.api.event.player.PlayerChatEvent;
import com.velyorix.game.api.event.player.PlayerJoinEvent;

public final class ChatRules implements Listener {

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onChat(PlayerChatEvent event) {
        if (event.message().contains("spoiler")) {
            event.setCancelled(true);
            event.player().sendMessage("That word is not allowed here.");
        }
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        event.player().sendMessage("Welcome, " + event.player().displayName() + ".");
    }
}
```

Register the listener in `onEnable`:

```java
registerEvents(new ChatRules());
```

| Annotation field  | Default  | Meaning                                                       |
| ----------------- | -------- | ------------------------------------------------------------- |
| `priority`        | `NORMAL` | Order of handlers.                                            |
| `ignoreCancelled` | `false`  | Skip the handler when an earlier handler cancelled the event. |

An invalid handler signature throws `IllegalArgumentException` at registration. An exception in a handler is logged, counted for the plugin, and does not stop the other handlers.

### Priorities

`LOWEST`, `LOW`, `NORMAL`, `HIGH`, `HIGHEST`, `MONITOR`, in that order of execution. `LOWEST` runs first, so later handlers have the last word. `MONITOR` runs last and only observes the final outcome. A `MONITOR` handler must not change the event: the bus restores the cancelled state if it does, so a logger can never change the game by accident.

### Cancelling

An event that implements `Cancellable` has `isCancelled()` and `setCancelled(boolean)`. The server performs the action only if the event is still not cancelled after every handler ran. What a cancel does is stated per event below.

A listener on a type also receives its subtypes. Listening to `BlockEvent` receives every block event.

All events fire on the simulation thread.

## Custom events

A plugin can define its own events and post them on the bus:

```java
public final class ShardCollectedEvent implements Event, Cancellable {
    private final Player player;
    private boolean cancelled;

    public ShardCollectedEvent(Player player) {
        this.player = player;
    }

    public Player player() {
        return player;
    }

    @Override
    public boolean isCancelled() {
        return cancelled;
    }

    @Override
    public void setCancelled(boolean cancelled) {
        this.cancelled = cancelled;
    }
}
```

```java
ShardCollectedEvent e = getServer().events().post(new ShardCollectedEvent(player));
if (!e.isCancelled()) {
    // go on
}
```

`post` returns the event after every handler ran. Post synchronous events on the simulation thread. `events().register(owner, listener)` and `unregisterAll(owner)` are the low-level forms of `registerEvents`.

## Event reference

Packages are under `com.velyorix.game.api.event`. "Cancel" says what a cancel does.

### Players (`player`)

| Event                       | Fires when                                                                                                                                 | Cancel                                                                               | Accessors                                                |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | -------------------------------------------------------- |
| `PlayerJoinEvent`           | A player entered the world: its entity exists and the join sequence was sent. The lines of `server.join_messages` are sent right after it. | No.                                                                                  | `player()`                                               |
| `PlayerQuitEvent`           | A player is leaving (disconnect, kick or a duplicate login), before its entity is removed.                                                 | No.                                                                                  | `player()`                                               |
| `PlayerChatEvent`           | A chat line passed the length, permission and rate checks.                                                                                 | Yes: the line is dropped.                                                            | `player()`, `channel()`, `message()`, `setMessage(text)` |
| `PlayerLoadingScreenEvent`  | Once per join, before the world is sent. The player has no entity yet.                                                                     | No: the packet is always sent.                                                       | `player()`, `screen()`, `setScreen(screen)`              |
| `PlayerGameModeChangeEvent` | The game mode is about to change, by `/gamemode` or `Player.setGameMode`.                                                                  | Yes: refuses the change.                                                             | `player()`, `oldMode()`, `newMode()`                     |
| `PlayerDodgeEvent`          | A dodge is starting and met every rule.                                                                                                    | Yes: the step is simulated without the dodge, with no stamina spent and no cooldown. | `player()`, `direction()`                                |

### Blocks (`block`)

`BlockEvent` is the base class of these events. The server posts them after the distance, accessibility and material checks and before the change applies. A cancel refuses the action and the client is resynchronised.

| Event                | Fires when                                                                                | Extra accessors                                             |
| -------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------- |
| `BlockBreakEvent`    | A player breaks a block. It becomes air unless cancelled.                                 | `materialId()`                                              |
| `BlockDamageEvent`   | A player starts mining a block. A cancel refuses the start.                               | `materialId()`, `breakTicks()`                              |
| `BlockPlaceEvent`    | A player places a block.                                                                  | `materialId()`, `setMaterialId(id)`, `replacedMaterialId()` |
| `BlockInteractEvent` | A player uses a block. The server has no built-in behaviour for it: plugins implement it. | `materialId()`, `hand()`                                    |

All carry `player()`, `world()` (the world name) and `position()` (a `BlockPosition` with `x`, `y` and `z`).

A handler of `BlockPlaceEvent` may change the material. The server checks the final material again: it must exist and be solid.

| Event            | Fires when                                                                         | Cancel        | Accessors                                                     |
| ---------------- | ---------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------- |
| `PickBlockEvent` | A player picks a block with the middle mouse button, before the inventory changes. | Yes: refused. | `player()`, `world()`, `position()`, `materialId()`, `item()` |

### Combat (`combat`)

| Event               | Fires when                                                                                             | Cancel                                       | Accessors                                                        |
| ------------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------- | ---------------------------------------------------------------- |
| `AttackEvent`       | An attack passed its checks and found a target.                                                        | Yes: no damage. The cooldown is still spent. | `attacker()`, `target()`                                         |
| `EntityDamageEvent` | Damage is about to be applied.                                                                         | Yes: no damage.                              | `target()`, `source()`, `critical()`, `amount()`, `setAmount(a)` |
| `EntityDeathEvent`  | An entity's health reached 0. The death already happened. Players respawn, other entities are removed. | No.                                          | `entity()`, `cause()`                                            |

### Entities (`entity`)

| Event                 | Fires when                                                                                                                                                                                               | Cancel                                                                                     | Accessors                           |
| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------- |
| `EntitySpawnEvent`    | An entity entered the world and is active.                                                                                                                                                               | No.                                                                                        | `entity()`                          |
| `EntityDespawnEvent`  | An entity is leaving the world.                                                                                                                                                                          | No.                                                                                        | `entity()`                          |
| `EntityInteractEvent` | A player interacts with a living entity, before the effect (feed, saddle, mount).                                                                                                                        | Yes: refused silently.                                                                     | `player()`, `entity()`, `held()`    |
| `TameEvent`           | A feed succeeded and a wild creature is about to become a companion. A player who already owns 5 companions, or a world that holds 200, is refused before the food is used, and the event does not fire. | Yes: the attempt fails. The food is used and the creature stays wild.                      | `player()`, `entity()`              |
| `MountEvent`          | A player is about to mount a companion, or to dismount by its own input.                                                                                                                                 | Mounting only. A dismount cannot be cancelled. Dismounts the server forces do not fire it. | `player()`, `mount()`, `mounting()` |

### Items and inventory (`item`, `inventory`)

| Event                  | Fires when                                                                                                    | Cancel                        | Accessors                                                                                                                |
| ---------------------- | ------------------------------------------------------------------------------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `ItemUseEvent`         | A player is about to use a consumable.                                                                        | Yes: nothing is consumed.     | `player()`, `item()`, `slot()`                                                                                           |
| `ItemDropEvent`        | A player drops items, before they leave the inventory.                                                        | Yes: the items stay.          | `player()`, `stack()`                                                                                                    |
| `ItemPickupEvent`      | A player is about to pick up a dropped item.                                                                  | Yes: it stays on the ground.  | `player()`, `item()`, `stack()`                                                                                          |
| `ItemCraftEvent`       | A craft request passed every check up to the room check. Fires once per request.                              | Yes: rejected.                | `player()`, `recipeId()`, `times()`                                                                                      |
| `ItemRepairEvent`      | A repair request passed every check up to the material.                                                       | Yes: rejected.                | `player()`, `slot()`, `item()`                                                                                           |
| `ItemBreakEvent`       | A durable item reached its durability, just before the slot empties.                                          | No.                           | `player()`, `slot()`, `item()`                                                                                           |
| `InventoryClickEvent`  | A player moves, drops or equips items in its inventory or an open container. Fires after the validity checks. | Yes: rejected as `CANCELLED`. | `player()`, `kind()`, `sourceSlot()`, `destinationSlot()`, `amount()`, `sourceInventoryId()`, `destinationInventoryId()` |
| `CreativeSetSlotEvent` | A creative player asked for a stack in a slot.                                                                | Yes: refused.                 | `player()`, `slot()`, `stack()`                                                                                          |

### Containers (`container`)

| Event                 | Fires when                                                                          | Cancel                                                          | Accessors                                                  |
| --------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------------- | ---------------------------------------------------------- |
| `ContainerOpenEvent`  | A player is about to open a container. For a chest it follows `BlockInteractEvent`. | Yes: refused.                                                   | `player()`, `container()`                                  |
| `ContainerCloseEvent` | A container closed for a player. It fires for every close, a disconnect included.   | No.                                                             | `player()`, `container()`, `reason()`                      |
| `LootGenerateEvent`   | A chest rolls its loot table, the first time it is opened or broken.                | No.                                                             | `world()`, `position()`, `table()`, `stacks()`, `opener()` |
| `ForgeSmeltEvent`     | An Ember Forge is about to add a smelted output.                                    | Yes: the forge keeps its progress and retries on the next tick. | `world()`, `position()`, `input()`, `output()`             |

A handler of `LootGenerateEvent` may add, remove or replace stacks in `stacks()`. Each goes into a random empty slot. Stacks beyond the free slots are discarded and an amount above the stack size is clamped.

### Effects and progression (`effect`, `progression`)

| Event                 | Fires when                                                                                                                                                                                                 | Cancel                           | Accessors                                                           |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | ------------------------------------------------------------------- |
| `EffectApplyEvent`    | A status effect is about to be applied, as a new effect or as a replacement by the stacking rule. It does not fire for an application that changes nothing, nor when a player's effects resume on joining. | Yes: the entity stays as it was. | `entity()`, `effect()`, `amplifier()`, `durationTicks()`, `cause()` |
| `EffectEndEvent`      | An effect ended. It is already removed. An effect replaced by a stronger one, or saved with a leaving player, does not end.                                                                                | No.                              | `entity()`, `effect()`, `amplifier()`, `reason()`                   |
| `ExperienceGainEvent` | A player is about to gain experience.                                                                                                                                                                      | Yes: no gain.                    | `player()`, `cause()`, `amount()`, `setAmount(n)` (0 gains nothing) |
| `LevelUpEvent`        | A player went up one or more levels, after the statistics apply and before the player is told.                                                                                                             | No.                              | `player()`, `previousLevel()`, `level()`                            |

### Abilities and bosses (`ability`, `boss`)

| Event                  | Fires when                                                                                                                                                | Cancel                                                                  | Accessors                                                                              |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `AbilityCastEvent`     | A cast passed every check, the ability's own conditions included.                                                                                         | Yes: refused with rejection 7. Nothing is spent and no cooldown starts. | `caster()`, `ability()`, `context()`                                                   |
| `BossSpawnEvent`       | A boss is about to spawn.                                                                                                                                 | Yes: an arena tries again at its next check, once a second.             | `definition()`, `world()`, `position()`, `cause()`                                     |
| `BossPhaseChangeEvent` | A boss entered a new phase, after the phase rule applied. A hit that crosses two thresholds fires it once per phase. A reset to phase 1 does not fire it. | No.                                                                     | `boss()`, `from()`, `to()`                                                             |
| `BossDefeatedEvent`    | A boss died, after its summons and its bar are removed and before the drops fall.                                                                         | No.                                                                     | `boss()`, `killerEntityId()`, `contributors()`, `drops()` (editable), `fightSeconds()` |

### NPCs, shops and quests (`npc`, `quest`)

| Event                | Fires when                                                                                       | Cancel                                                     | Accessors                                                                              |
| -------------------- | ------------------------------------------------------------------------------------------------ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `NpcInteractEvent`   | A player talks to an NPC, after the rate, target and reach checks.                               | Yes: no dialogue opens and no `TALK` objective progresses. | `player()`, `npc()`                                                                    |
| `ShopTradeEvent`     | A trade is about to be committed, after the checks on shop, offer, funds and space.              | Yes: rejected (7).                                         | `player()`, `shop()`, `kind()`, `items()`, `price()`, `setPrice(p)`                    |
| `QuestStartEvent`    | A quest is about to start: accepted in a dialogue, or started by `/quest start` or a plugin.     | Yes: the quest stays unstarted.                            | `player()`, `quest()`                                                                  |
| `QuestProgressEvent` | An objective changed its progress, before the player is told. A `COLLECT` objective can go down. | No.                                                        | `player()`, `quest()`, `objectiveIndex()`, `objective()`, `previous()`, `progress()`   |
| `QuestCompleteEvent` | A quest is being completed.                                                                      | No. Rewards are editable.                                  | `player()`, `quest()`, `experience()`/`setExperience`, `coins()`/`setCoins`, `items()` |

A changed `ShopTradeEvent` price is checked again. A buy the player can no longer pay is rejected (4). A sale whose coins no longer fit is rejected (5).

### World (`world`)

| Event                | Fires when                                                                              | Cancel                                                                                                                                                       | Accessors                                                 |
| -------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |
| `CropGrowEvent`      | A crop is about to advance one growth stage, after the growth roll and the light check. | Yes: it keeps its stage and tries again at the next growth step.                                                                                             | `world()`, `position()`, `materialId()`, `newStage()`     |
| `WeatherChangeEvent` | The weather of a world is about to change.                                              | Only a change made by the weather cycle: the current weather lasts another cycle. `isCancellable()` tells. A command or a plugin change cannot be cancelled. | `world()`, `from()`, `to()`, `durationTicks()`, `cause()` |

## A complete example

Halve critical hits, and log a defeated boss:

```java
public final class Rules implements Listener {

    private final org.slf4j.Logger log;

    public Rules(org.slf4j.Logger log) {
        this.log = log;
    }

    @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
    public void onDamage(EntityDamageEvent event) {
        if (event.critical()) {
            event.setAmount(event.amount() * 0.5f);
        }
    }

    @EventHandler(priority = EventPriority.MONITOR)
    public void onBossDefeated(BossDefeatedEvent event) {
        log.info("boss defeated in {} s by {} player(s)", event.fightSeconds(), event.contributors().size());
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.aethercube.fr/developers/plugins/events.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
