Server plugins
Writing a plugin
A plugin is a .NET class library the server loads from its plugins/ folder. It adds commands and events, and players
join with a vanilla client. The API still changes between versions, so expect to update a plugin with the server.
Coming from Spigot or Paper?
| Spigot / Paper | Obsidian |
|---|---|
JavaPlugin |
PluginBase |
plugin.yml |
obsidian.mod.json, written from the project file |
onEnable / onDisable |
OnLoadedAsync / OnUnloadingAsync |
CommandExecutor |
a CommandModuleBase class with [Command] methods |
Listener and @EventHandler |
a MinecraftEventHandler class with [EventPriority] methods |
Player#sendMessage |
IPlayer.SendMessageAsync |
BukkitScheduler |
ILevel.AddTicker, for code that runs every tick |
Set up a project
Start from the plugin template. It's a working server-side plugin (a command, a join greeting, a dimension and a portal to it) that vanilla clients can join. Its project file references two packages:
Obsidian.API, the plugin API, referenced withExcludeAssets="runtime": the server provides it at runtime, so the plugin only compiles against it.Obsidian.MSBuild, which packs the build into an.obbyarchive and writes the archive's metadata.
The metadata comes from the project file's properties:
<PropertyGroup>
<PluginId>myplugin</PluginId>
<Version>1.0.0</Version>
<Title>My Plugin</Title>
<Authors>You</Authors>
<Description>What the plugin does.</Description>
<ProjectUrl>https://github.com/you/myplugin</ProjectUrl>
<!-- Runs on the server only. -->
<PluginSide>server</PluginSide>
</PropertyGroup>
PluginId is the plugin's namespace too: identifiers it registers, like myplugin:visits, use it.
Plugin archives describes the archive and every metadata field, including dependencies on
other plugins.
The plugin class
Each plugin has one class that derives from PluginBase. The server calls its methods in this order:
ConfigureServices(IServiceCollection): add the plugin's own services.ConfigureRegistry(IPluginRegistry): register commands, events and content.OnLoadedAsync(IServer): the plugin is loaded.OnServerReadyAsync(IServer): the server has started, or straight after loading when it already had.OnUnloadingAsync(), thenDisposeAsync(), when the plugin unloads.
Properties marked [Inject] are filled from the server's services, such as a logger:
public sealed class MyPlugin : PluginBase
{
[Inject]
public ILogger<MyPlugin> Logger { get; set; } = null!;
public override void ConfigureRegistry(IPluginRegistry registry)
{
// Finds the plugin's CommandModuleBase and MinecraftEventHandler classes.
registry.MapCommands();
registry.MapEvents();
}
public override ValueTask OnLoadedAsync(IServer server)
{
this.Logger.LogInformation("{Name} loaded", this.Info.Name);
return ValueTask.CompletedTask;
}
}
Command and event handler classes get services the same way, through [Inject] properties or their constructor.
Besides the server's services, a plugin can ask for IServer, ILevelFactory,
IOptionsMonitor<ServerConfiguration> and the services exported by plugins it depends on.
Install, update and remove
- Install: put the
.obbyfile in the server'splugins/folder (subfolders work too). The server loads every plugin there as it starts. - Update: replace the file while the server runs. The server notices and reloads the plugin, and the plugins that depend on it reload with it.
- Remove: delete the file. The plugin unloads, and the plugins that depend on it unload too until it's back.
Unloading undoes what the plugin registered: its commands, event handlers, recipes, scoreboards, boss bars, dialogs
and entities (see the mod system for the details). /plugins (or /pl)
lists the loaded plugins. There's no command to reload or disable one; change the file instead.
Commands
A command is a method marked [Command] on a class that derives from CommandModuleBase. The server creates the
class for each run, and its parameters become the command's arguments:
public sealed class TeleportCommands : CommandModuleBase
{
[Command("tpto")]
[CommandInfo("Teleports you to another player.", "/tpto <player>")]
[IssuerScope(CommandIssuers.Client)]
[RequirePermission(op: true, permissions: "myplugin.tpto")]
public async Task TeleportToAsync(IPlayer target)
{
if (this.Player is not IPlayer player)
return;
await player.TeleportAsync(target);
await player.SendMessageAsync($"Teleported to {target.Username}.");
}
}
- Who ran it:
this.Playeris the player, or null from the console;this.Senderis whoever ran it, andthis.Serverthe server.[IssuerScope]limits who can:Client,Console,RemoteConsole,PluginorAny(the default). - Arguments:
bool, numbers,string,Guid,IPlayerandIPlayer[](names and selectors like@a),IEntityandIEntity[],VectorD(a position),Vector(a block position),Item,BlockStateArgument,EntityType,ResourceLocation,MinecraftTime,PotionEffect,EnchantmentDefinition,ParticleType, and any enum.[Remaining]on a finalstringtakes the rest of the line. For another type, derive fromBaseArgumentParser<T>and callregistry.RegisterCommandArgumentHandler. - Optional arguments: add an overload with
[CommandOverload], as/givedoes for its count. - Permissions:
[RequirePermission]lets the console through, and operators whenopis true, and otherwise checks the player's permissions. For your own rule, derive fromBaseExecutionCheckAttribute; checks also decide what a player sees in help and suggestions, so keep them free of side effects. - Suggestions:
[Suggestions("day", "night")]on a parameter suggests fixed values; derive fromBaseSuggestionProviderAttributeto compute them. - Help:
[CommandInfo(description, usage)]is what/helpshows. - Results: a command can return
Task,ValueTask, or anint(or a task of one) as its result.
Subcommands are a class marked [CommandGroup]. Its [GroupCommand] method runs for the bare name, and nested
classes make deeper groups:
[CommandGroup("motd")]
public sealed class MotdCommands : CommandModuleBase
{
public static string Text { get; set; } = "Welcome!";
[GroupCommand]
public Task ShowAsync() => this.Sender.SendMessageAsync(Text);
[Command("set")]
[RequirePermission(op: true, permissions: "myplugin.motd.set")]
public Task SetAsync([Remaining] string text)
{
Text = text;
return this.Sender.SendMessageAsync("Message of the day set.");
}
}
registry.MapCommand(name, delegate) registers a single command without a class: the delegate's first parameter is
the CommandContext, and the others are its arguments.
Events
An event handler is a method on a class that derives from MinecraftEventHandler, marked [EventPriority] and
taking the event's arguments. registry.MapEvents() finds the class:
public sealed class JoinGreeter : MinecraftEventHandler
{
[EventPriority(Priority = Priority.Normal)]
public async ValueTask OnPlayerJoinAsync(PlayerJoinEventArgs args)
{
await args.Player.SendMessageAsync($"Welcome, {args.Player.Username}!");
}
// Only players with the permission can break blocks.
[EventPriority(Priority = Priority.High)]
public ValueTask OnBlockBreakAsync(BlockBreakEventArgs args)
{
if (!args.Player.HasPermission("myplugin.build"))
args.Cancel();
return ValueTask.CompletedTask;
}
}
registry.MapEvent registers one handler without a class:
registry.MapEvent<IncomingChatMessageEventArgs>(args =>
{
if (args.Message.Contains("spoiler", StringComparison.OrdinalIgnoreCase))
args.Cancel();
return ValueTask.CompletedTask;
});
Handlers run from Low to Critical priority, and the server's own handling comes last, so Cancel() in any of
them stops what the event would do: the block isn't broken, the message isn't sent. A delegate's priority is Low
unless you pass another.
The events a plugin can handle:
| Event | Raised when | Cancellable |
|---|---|---|
PlayerJoinEventArgs |
a player joins | no |
PlayerLeaveEventArgs |
a player leaves | no |
IncomingChatMessageEventArgs |
a player chats; Message can be changed |
yes |
BlockBreakEventArgs |
a player breaks a block | yes |
BlockPlaceEventArgs |
a player places a block | yes |
PlayerInteractEventArgs |
a player uses an item or a block | yes |
EntityInteractEventArgs |
a player uses an entity | yes |
PlayerAttackEntityEventArgs |
a player attacks an entity | yes |
PlayerTeleportEventArgs |
a player teleports | no |
ContainerClickEventArgs |
a player clicks in a container (see click handlers) | yes |
ContainerClosedEventArgs |
a player closes a container | yes |
DialogActionEventArgs |
a player submits a dialog | no |
PermissionGrantedEventArgs, PermissionRevokedEventArgs |
a player's permissions change | no |
PacketReceivedEventArgs |
a packet arrives, with its id and bytes | yes |
ServerStatusRequestEventArgs |
a client pings the server list | no |
There are no events yet for deaths, damage in general, movement, respawning, dropping or picking up items, or commands before they run.
Players and messages
Players are IPlayers: from an event's arguments, a command's this.Player, or the server
(server.OnlinePlayers, server.GetPlayer(name)).
- Chat:
SendMessageAsync(message); to everyone,server.BroadcastMessage(message). - Titles and the action bar:
SendTitleAsync(title, subtitle, fadeIn, stay, fadeOut)andSendActionBarAsync(text). - Teleporting:
TeleportAsyncto a position, another entity, a level or a world, andTeleportToDimensionAsync("minecraft:the_nether"). - Inventories:
InventoryandEnderInventory, andOpenInventoryAsyncto show a container. - Game mode:
SetGamemodeAsync(GameMode.Creative). - Leaving:
KickAsync(reason). - Operators:
server.Operators(IsOperator,AddOperator,RemoveOperator), saved inconfig/ops.json.
Messages are ChatMessages. A string converts to one, SimpleLegacy reads & colour codes, and the builder
methods add colour, click and hover actions:
var message = ChatMessage.Simple("Welcome back, ", ChatColor.Gold)
.AppendText(player.Username, ChatColor.White);
await player.SendMessageAsync(message);
await player.SendMessageAsync(ChatMessage.SimpleLegacy("&aSaved."));
Permissions
A permission is a dot-separated name, like myplugin.motd.set, matched without case. A player holding myplugin.*
has every permission under myplugin. Grant and check them through the player:
await player.GrantPermissionAsync("myplugin.build");
await player.RevokePermissionAsync("myplugin.build");
var canBuild = player.HasPermission("myplugin.build");
They're saved per player in permissions/<uuid>.json. There are no groups or defaults, and no command to grant them
yet; a permissions plugin can add both on top of this API.
Worlds, blocks and entities
- Worlds and levels: a world is a save with its dimensions, which are levels.
server.DefaultWorldis the main world,server.WorldManager.TryGetWorld(name, out var world)finds another,world.GetLevel(identifier)one of its dimensions, andplayer.Levelis where the player is. - Blocks:
level.GetBlockAsync(position)andlevel.SetBlockAsync(position, block)read and change blocks;DestroyBlockbreaks one as a player would, with its drops. Gameplay and the world explains the update flags. - Entities:
level.SpawnEntity(position, EntityType.Zombie)spawns a vanilla mob, andGetEntitiesInRangeandGetPlayersInRangefind what's nearby. An entity hasDamageAsync,KillAsyncandRemoveAsync. - Items:
ItemsRegistry.Get("minecraft:diamond")is an item, andnew ItemStack(item, count)a stack of it.
// A bat at the player's feet.
var bat = player.Level.SpawnEntity(player.Position, EntityType.Bat);
Scoreboards and boss bars
var scoreboard = server.ScoreboardManager.CreateScoreboard("kills");
scoreboard.CreateOrUpdateObjective("Kills");
scoreboard.CreateOrUpdateScore(player.Username, player.Username, 0);
await player.DisplayScoreboardAsync(scoreboard, DisplaySlot.Sidebar);
var bar = server.CreateBossBar("Event ends soon", 1, BossBarColor.Red, BossBarDivisionType.None, BossBarFlags.None);
bar.AddPlayer(player.EntityId);
bar.UpdateHealth(0.5f);
Scoreboards also have teams (CreateTeam), with prefixes, suffixes, colours and name tag rules. Both go away when
the plugin unloads.
Running code every tick
There's no scheduler like Bukkit's. level.AddTicker runs a callback once every tick of that level, which covers
timers and repeating work; dispose the result to stop it, and the server removes it when the plugin unloads:
var ticks = 0;
var ticker = level.AddTicker(() =>
{
if (++ticks % 1200 == 0)
server.BroadcastMessage("Another minute has passed.");
return ValueTask.CompletedTask;
});
Event handlers for a player's actions run on that player's connection, not on the level's tick, so two players' events can run at once. Guard state a plugin shares between handlers, with a lock for example.
Saving data
Plugins save data in the world, as NBT: values for the whole server or a world, and attachments on players, entities and chunks. The template counts each player's trips with an attachment:
PlayerVisits = registry.RegisterAttachment("obsidianplugin:dusk_visits",
new ComponentCodec<int>(visits => new NbtTag<int>("", visits), tag => ((NbtTag<int>)tag).Value),
copyOnDeath: true);
var visits = player.GetAttachment(PlayerVisits) + 1;
player.SetAttachment(PlayerVisits, visits);
Saved data and attachments covers both.
Configuration
Obsidian doesn't give plugins a config file or data folder yet. A plugin can read files packed in its archive
with this.Container.GetFileData(name), and the server's settings through IOptionsMonitor<ServerConfiguration>.
Keeping vanilla clients
A plugin keeps vanilla clients able to join as long as it doesn't add content their game has built in. Registering a block, block entity type, item, entity type, menu, particle type, custom statistic or a data component type that's sent to clients makes the server refuse vanilla clients, and those belong to mods. Commands, events, recipes of vanilla items, loot tables, advancements, saved data, dimensions, biomes and the rest of world generation don't. Sounds a plugin registers play for vanilla clients that have its resource pack.
Next
Gameplay and the world, recipes and tags, world generation and dialogs go further.