Events and handler options
Choose priority, blocking, ignore-cancelled and a failure verdict for each handler, and read what each event carries.
Two ways to register
register_event_handler::<E, _>(handler, EventPriority, blocking): the short form. A blocking handler registered this way gets the failure verdict deny.register_event_handler_with_options::<E, _>(handler, HandlerOptions): Paper's full set of options.
HandlerOptions has four fields:
priority:Lowest,Low,Normal,High,HighestorMonitor. Handlers of one event run fromLowesttoMonitor, and in registration order within one priority, whichever function registered them.Monitorruns last, to observe the outcome; it should not change the event.blocking:truemeans the event waits for the handler and the data it returns replaces the event (Paper's behaviour).falsemeans the handler only observes: what it returns is ignored and the event does not wait for it.ignore_cancelled:truemeans the handler is not called while the event is cancelled (Paper'signoreCancelled).on_failure: what the event gets when a blocking handler fails instead of answering.Denycancels the event;Allowlets it go on unchanged. See below.
Remove a handler
Every registration returns the handler's id. Context::unregister_event_handler(id) removes that handler from every event it was registered for and answers whether it was still registered (Paper's HandlerList.unregister). It works for extension event handlers too.
Use it for a state that lasts a short while, such as a teleport warmup, a countdown or a combat tag: register the handler when the state starts and remove it when the state ends, so your script is called for these events only while it needs them. It is safe inside the handler itself: the event under way still reaches it, the next one does not. Another script's handlers are never touched.
Register a decision and an observer
// A protection decision: blocking, early, and refused if the plugin fails.
context.register_event_handler_with_options::<BlockBreakEvent, _>(
SkyProtection,
HandlerOptions {
priority: HandlerPriority::Lowest,
blocking: true,
ignore_cancelled: false,
on_failure: FailureVerdict::Deny,
},
)?;
// An observer: runs last, skips cancelled joins, never holds the join up.
context.register_event_handler_with_options::<PlayerJoinEvent, _>(
JoinLog,
HandlerOptions {
priority: HandlerPriority::Monitor,
blocking: false,
ignore_cancelled: true,
on_failure: FailureVerdict::Allow,
},
)?;/// Nobody breaks blocks at y = 100 or above in the overworld.
struct SkyProtection;
impl EventHandler<BlockBreakEvent> for SkyProtection {
fn handle(&self, _server: Server, mut event: BlockBreakEventData) -> BlockBreakEventData {
let in_overworld = event_world().is_some_and(|world| world.get_dimension() == "minecraft:overworld");
if in_overworld && event.block_pos.y >= 100 {
event.cancelled = true;
if let Some(player) = &event.player {
player.send_system_message(TextComponent::text("This area is protected."), false);
}
}
event
}
}Blocking or observing
A blocking handler decides: the player's action waits for it, so keep it short. An observing (non-blocking) handler gets its own copy of each event and never holds the game up. It gets every event, in the order they were fired.
- When 2,048 calls are waiting, the console says that your script is behind, at most once every 10 seconds.
- At 65,536 waiting calls the script is stopped as failed and restarted.
Keep handlers of events that come for every chunk, block or tick cheap. A handler that has to refuse or change something registers as blocking.
When a handler fails
A blocking handler fails when your script faults or its own code runs past the call deadline. The event then gets the handler's failure verdict:
FailureVerdict::Deny(the default): the event is cancelled as if the handler had cancelled it. An event that cannot be cancelled goes on unchanged. Use it for protection, permissions and logins: a broken protection script keeps protecting.FailureVerdict::Allow: the event goes on unchanged. Use it for handlers that only decorate an event, such as a join message or a chat format.
About the event being handled
During a handler, these functions answer for the event that handler is handling:
events::event_world(): the event's world, when it has one.events::explosion_blocks()andevents::set_explosion_blocks(list): the blocks an explosion will destroy. A blocking handler's list is what the explosion destroys.events::damage_projectile_shooter(): for a damage-by-entity event caused by a projectile, the entity id of the shooter.events::event_teleport_cause(): in a player teleport event, why the player is moved (Paper'sgetCause).events::piston_blocks(): in a piston extend or retract event, the positions of the blocks the piston moves and breaks (Paper'sgetBlocks()).events::death_drops()andevents::set_death_drops(list),events::set_death_cancelled(true),events::death_revive_health()andevents::set_death_revive_health(health): in an entity death event, what drops and whether the entity dies.BlockIgniteEvent::cause(),igniting_block(),igniting_entity()andplayer(): in a block ignite event, why the block catches fire and what set it.
The sections below describe these and more, for clicks, equipment, deaths, drops, furnaces, signs and books.
Clicks on entities
An attack or an interaction with an entity reaches scripts only when vanilla would accept it: the player is not a spectator, the entity is inside the world border and within the player's reach (with a weapon, the weapon's attack range). Clicks that fail these checks are ignored before any event, so PlayerInteractEntityEvent and the damage events never see an out-of-reach click.
A click on an entity id the server does not know, for example an entity your script only showed to the client with packets, fires PlayerInteractUnknownEntityEvent (Paper's PlayerUseUnknownEntityEvent) with the entity id and whether it was an attack or an interaction, and does nothing else.
What a click carried
To cancel a click or to split a right click into its two uses, see Events and commands. In a PlayerInteractEvent, BlockPlaceEvent or BlockBreakEvent handler:
events::event_block_face(): the face of the block the player clicked (for a place, the face of the block placed against). None for a click in the air.events::event_click_point(): aClickPointon that face, each ofx,yandzfrom 0 to 1 inside the block. None for a left click and a click in the air. The server does not trust the client's point: one that is not a finite number gives none, and the point is held inside the block.events::event_hand_item(): a copy of the item in the hand used: the interaction's hand, the hand the block is placed from, or the main hand (the tool) when breaking. Changing the copy changes nothing in the hand.events::event_replaced_state(): the block state a placed block replaces, such as air or water.events::event_hand()also tells the hand a block is placed from.
The event types have the same calls under Paper's names: PlayerInteractEvent::block_face(), clicked_position() and item(); BlockPlaceEvent::block_face(), clicked_position(), hand(), item_in_hand() and replaced_state(); BlockBreakEvent::tool().
In a PlayerInteractEntityEvent, PlayerInteractAtEntityEvent, EntityDamageByEntityEvent, EntityMountEvent or EntityDismountEvent handler:
events::event_entity(): the entity the event is about (the clicked one, the damaged one, or the rider), so you need no search by its id (Paper'sgetRightClicked(),getEntity()).events::event_vehicle(): the vehicle of a mount or dismount (Paper'sgetMount(),getDismounted()).events::event_dismount_cause(): why the rider left, aDismountCause:PlayerInput(the player sneaked),VehicleRemoved,RiderDied,Teleport,Plugin,GameorUnknown.events::event_hand()andevents::event_click_point()also answer entity clicks; the point is on the entity's box, relative to the entity's position.- For a Bedrock player the hand is always the main hand and there is no click point.
The event types have them too: PlayerInteractEntityEvent::entity(), hand() and clicked_position() (the same on PlayerInteractAtEntityEvent), EntityDamageByEntityEvent::entity(), EntityMountEvent::rider() and vehicle(), EntityDismountEvent::rider(), vehicle() and cause().
Each of these returns none outside the events it names.
Teleports
PlayerTeleportEventfires as on Paper: not when the player is placed at join or at respawn, and not for a move to where the player already is. A move into another world fires it once, before the move, with the position the player leaves; the world change event follows, and a cancelled teleport keeps the player in their world.events::event_teleport_cause()gives aTeleportCause:Command(/tp,/teleport,/spreadplayers,/rotate),Plugin(a script's teleport, or a move event whose destination a script changed),EnderPearl,ConsumableEffect(chorus fruit),NetherPortal,EndPortal,EndGateway,Spectate(a spectator's camera going to an entity or a player),Dismount,ExitBedandUnknownfor any other move by the server. It returns none for other events.- A blocking teleport handler that changes
to_positionsends the player there, as Paper'ssetTodoes, in the world they were being moved to. The player keeps the look they would have had (change it withevents::set_move_to_look) and keeps no motion. A destination that is not a finite number keeps the player where they are, as a cancel does; a destination beyond 30 million blocks on x or z (20 million on y) is held there. The destination's world cannot be changed. - A player who gets off a vehicle (a boat, a minecart, a horse) fires
PlayerTeleportEventwith the causeDismount, from where they sat to the place beside the vehicle. Cancel it and the player is still off the vehicle but stays where they sat; changeto_positionand they are put there instead. It does not fire when the player is already at that place, and a mob that gets off a vehicle fires no teleport event. - A script that teleports the player inside their move event keeps that teleport; the move itself is then not taken, as on Paper.
Joining
PlayerResourcePackStatusEventalso fires for the answers a player gives while joining, for the server's resource pack and packs sent during the join. These events come right after the join event, in the order the player answered (Accepted,Downloaded, then the final one such asDownloadSuccessorDeclined), with the pack's id. A script that draws with a pack's fonts or images only for players who loaded it can wait forDownloadSuccess. A player kicked for declining a required pack never joins, so no event fires for them.- Whatever your script sends to a joining player (a message, a team, a title, a teleport from
PlayerSpawnLocationEvent) reaches the player right after their client has the world, in the order it was sent, so nothing has to wait a tick. Do not wait in that handler for an answer from the player: the client answers only after the join has gone on. A player who is kicked during the join gets only the kick message.
Dismounts
EntityDismountEventalso fires for/ride ... dismount, a chorus fruit's teleport, a minecart on a powered activator rail and a player leaving the server. The dismount of a player who leaves cannot be cancelled.- It also fires when a mount or a rider is killed or despawns. The riders of such a vehicle get the cause
VehicleRemoved, and a killed rider getsRiderDied. A cancel does not keep a rider on a vehicle that is gone. - A chunk unload and a change of dimension fire no dismount event.
Picking up and throwing
PICK_ITEM("pick-item", an extension event) is Paper'sPlayerPickItemEventwith its block and entity forms. It fires when a player picks an item with the middle click, after the server found the item and where it goes.event.pick_item()gives the block position (or the entity id), the item, whether the player asked for the data (Ctrl with the middle click), the inventory slot the item comes from (-1 when a creative pick makes a new one) and the hotbar slot it goes to. Cancel it and the inventory and the selected slot stay as they are.event.set_pick_slots(source, target)takes the item from another slot or puts it into another hotbar slot; a source outside -1 to 35 or a hotbar slot outside 0 to 8 is ignored.PICKUP_EXPERIENCE("pickup-experience", an extension event) is Paper'sPlayerPickupExperienceEvent. It fires when a player touches an experience orb and is about to take one orb of it.event.pickup_experience()gives the orb's entity id, the experience of the one orb and how many orbs of that value it holds (merged orbs are taken one by one). Cancel it and the orb stays and the player can try again on the next touch. Not cancelled, Mending repairs first, as in vanilla, and the rest firesPlayerExpChangeEvent; the amount a blocking handler sets there is what the player gets.PLAYER_LAUNCH_PROJECTILE("player-launch-projectile", an extension event) is Paper'sPlayerLaunchProjectileEvent. It fires when a player throws a snowball, egg, ender pearl, potion, bottle o' enchanting, wind charge or trident, or uses a firework rocket on a block, before the projectile enters the world.event.launch_projectile()is the projectile andevent.launch_item()a copy of the stack in the hand. Cancel it and nothing is thrown and the item stays;event.set_launch_should_consume(false)keeps the item of a throw that goes on. Bows and crossbows do not fire it.
Equipment
ENTITY_EQUIPMENT_CHANGE("entity-equipment-change", an extension event) is Paper'sEntityEquipmentChangedEvent, andPlayerArmorChangeEventfor a player's armour. It fires when what a living entity wears changes: its helmet, chestplate, leggings, boots, or a mob's body armour. Held items and saddles are not included.event.equipment_entity()gives the entity andevent.player()the player when it is one.event.equipment_changes()lists every slot that changes at that moment as anEquipmentChangewithslot,old_itemandnew_item(none for an empty slot).- A slot that ends up as it was is not listed; losing durability counts as a change. The event also fires when armour breaks, when a mob drops its armour as it dies, for
/clearand/item replace, and when a script changes equipment. Loading a player or a mob does not fire it: read the equipment in the join event. - It is an observer: it cannot be cancelled and the server does not wait for it. A handler gets the changes in the order they happened. To stop a change, cancel the action that caused it.
Blocks and fluids
TNTPrimeEventfires before the TNT block is touched: cancelled, the TNT stays as it was and nothing around it is updated. Itsprime_reasonsays what lit it:REDSTONE,PLAYER(flint and steel or a fire charge),PROJECTILE(a burning arrow or other burning projectile),DISPENSER,FIRE,BLOCK_BREAK(unstable TNT broken by a player not in creative) orEXPLOSION. Cancelling it for an explosion keeps that TNT a block, so a script can stop a chain of TNT. A TNT whose prime by fire is cancelled does not burn away.BlockIgniteEventfires when fire spreads, when lava sets fire to a block, when lightning sets fire, when a fireball lands, when a dispenser's flint and steel places fire and for each fire an explosion sets.BlockIgniteEvent::cause()gives theIgniteCause:Lava,FlintAndSteel(a player's or a dispenser's),Spread,Lightning,Fireball(a fire charge used on a block, or a fireball),ExplosionorArrow.igniting_block()is the block that set the fire (the lava, the burning fire, the dispenser),igniting_entity()the entity (the player, the lightning bolt, the fireball, the entity that exploded, or whoever shot a burning projectile) andplayer()the player, when a player set it. The event's position is the block that catches fire. Cancel it and nothing catches fire; as on Paper, a refused flint and steel still wears and a refused fire charge is still used up. So a protection script can allow a player's flint and steel and refuse lava and spreading fire:
if BlockIgniteEvent::cause() != Some(IgniteCause::FlintAndSteel)
|| BlockIgniteEvent::player().is_none()
{
data.cancelled = true;
}BlockPistonExtendEventandBlockPistonRetractEventfire once the piston knows what it moves;events::piston_blocks()lists the blocks it moves and breaks. Cancelling leaves the piston and every block as they were. The direction of a retract event that moves blocks is the direction they move (towards the piston), as on Paper. A sticky piston that retracts without pulling a block fires the retract event with an empty list.BlockFromToEventnames the block the fluid flows from, and is also asked before lava turns the water it flows into into stone.BlockFormEventfires before lava and water make cobblestone, obsidian, stone or basalt,BlockIgniteEvent(causeLava) before lava sets fire to a block,FluidLevelChangeEventbefore flowing water or lava changes its level or dries up, andEntityChangeBlockEventbefore sand, gravel and other falling blocks start to fall and before they land. A cancel keeps the world as it was; a falling block that may not land disappears without placing or dropping anything.PlayerBucketFillEventandPlayerBucketEmptyEventfire before anything changes: cancelled, the water, lava or powder snow stays where it was and the player keeps the bucket they held. A water bucket used in the Nether firesPlayerBucketEmptyEventtoo; cancelling it keeps the water bucket.BlockShearEntityEventfires before a dispenser shears a sheep, mooshroom, snow golem, bogged or copper golem; cancelled, that mob stays as it is and the dispenser goes on to the next mob in front.BlockDispenseArmorEventfires before a dispenser puts armor, an elytra, a head, a saddle, horse or wolf armor, a carpet or a chest on a mob, an armor stand or a player; cancelled, nothing is put on.BlockBreakEvent'sexpis the experience the block will drop (Paper'sgetExpToDrop), and a blocking handler can change it, up to 32767.BlockDropItemEventfires for every break by a player while a script listens, also when the block drops nothing (creative, the wrong tool): its list is then empty and a handler may add items (Paper's rule). Breaks without a player (explosions, fluids, pistons) do not fire it, except for custom blocks.events::event_broken_block()(BlockDropItemEvent::broken_block()) names the broken block as it was, andevents::drop_experience()andevents::set_drop_experience(exp)(BlockDropItemEvent::experience()andset_experience(exp)) read and change the experience the break drops, so a drop rule can add experience to the items it adds. The experience drops even when the event is cancelled, as on Paper.
Signs and books
- In a
SignChangeEventhandler,events::sign_line_components()reads the sign's lines as text components andevents::set_sign_line_component(index, line)sets line 0 to 3 as styled text (colours, fonts, translations);events::sign_edit_front()says whether the front side is edited. The event type has them asSignChangeEvent::line_components(),set_line_component()andis_front()(Paper'slines(),line(int, Component),getSide()). - In a
PlayerEditBookEventhandler for a book being signed,events::book_page_components()andevents::set_book_page_component(index, page)read and set its pages as styled text (PlayerEditBookEvent::page_components()andset_page_component()); the title stays plain. - A component set this way wins over the plain line or page in the event data. A component over vanilla's limits (128 levels deep, 32,767 bytes) writes nothing, as if the event were cancelled. Signs saved with styled text keep it after a restart. A line a player types on a sign is always plain text and can never run a command when clicked. Bedrock players see the colours on such signs.
PlayerEditBookEventfires for Bedrock players too, with the whole book: about once a second while they type, and at once when they sign. A Java player's fires once, when they close the book. Cancelling and changing the pages work the same.
Combat, projectiles and deaths
EntityDamageEventand its by-entity and by-block forms fire only for a hit that lands.events::damage_final(damage)answers the health the hit takes after armour, enchantments, resistance and absorption. A thrown trident's damage event names the trident and its thrower.- An attack on an entity fires no
PlayerInteractEntityEvent, on Java and Bedrock. ProjectileLaunchEventandProjectileHitEventfire for every projectile (snowballs, eggs, pearls, potions, fireballs, tridents, fishing bobbers and more). A cancelled launch keeps the projectile out of the world; a cancelled launch of a thrown trident leaves it whole in the hand. A cancelled hit on an entity does not happen and the projectile flies on; a cancelled hit on a block still stops the projectile but skips the block's reaction.EntityPickupItemEventfires before the item is taken, with the item and the amount that fits; cancelled, the item stays on the ground. A trident on the ground firesPlayerPickupArrowEvent.EntityDeathEventdecides a death.events::death_drops()andevents::set_death_drops(list)read and replace what drops, anddropped_expis the experience, which a handler can change. The drops hold the mob's own items too: the block an enderman carries, a horse's or llama's inventory and chest, the item an allay holds; a handler that removes them makes them not fall.events::set_death_cancelled(true)keeps the entity alive withevents::death_revive_health(), its maximum health unlessevents::set_death_revive_health(health)sets another; a cancelled death keeps the mob's items on it.- In an
EntityDeathEventhandler,events::death_details()(EntityDeathEvent::details()) gives anEntityDeathDetails: theentitythat dies (still in its world, where it died), thekiller(the shooter of an arrow, not the arrow), thekiller_playercredited with the kill, thedamage_typeand thelooting_levelthe loot uses (Paper'sgetEntity(),getDamageSource()andgetEntity().getKiller()).EntityDeathEvent::spawn_reason()tells how the entity came into the world. It returns none for the player death event.events::event_world()also answers in an entity death handler. EntityResurrectEventfires, as on Paper, whenever a living entity would die from damage a Totem of Undying can stop. It comes cancelled when the entity holds no totem. Cancel it to let the entity die; un-cancel it to save the entity without a totem: it gets the totem's effects and no item is taken.EntityAirChangeEventfires for mobs too, not only for players.- Cancel
EntityTargetEventto stop a mob from taking a target,EntityTameEventto stop an animal from being tamed,EntityEnterLoveModeEventto stop it from falling in love andEntityBreedEventto stop it from breeding.
Crafting, enchanting, furnaces and brewing
- A cancelled
PrepareItemCraftEventshows no result, whatever a handler set as the result. PrepareItemEnchantEventfires right after the click that changed the enchanting table, andEnchantItemEventbefore an enchant button is carried out. Both run with the window free, so a handler may close, open or change the player's window. Until the prepare event has answered, the table's buttons offer nothing.- In a furnace smelt, start smelt, burn or extract event, or a brew or brewing stand fuel event,
events::event_source_item()gives a copy of the stack the block works on, with its components, so a custom item tells itself apart from its base item. The event types have it under Paper's names:FurnaceSmeltEvent::source(),FurnaceStartSmeltEvent::source(),FurnaceBurnEvent::fuel(),FurnaceExtractEvent::item_stack(),BrewEvent::ingredient()andBrewingStandFuelEvent::fuel(). Changing the copy changes nothing in the block. ServerLoadEventof the reload kind fires once after a data reload (/reload,/datapack, a script's data pack), with the recipes, tags and advancements back. The reload drops every script recipe, so register yours again there.
Change an event safely
Return the event data. Check cancelled before side effects and keep another script's cancellation unless your feature owns that decision. Not every event can be cancelled; use its data type. Cancellation does not make a multi-step change (an item for money) atomic: check the state again before you apply it.
The event reference lists every event and its data.