Skip to content

Instantly share code, notes, and snippets.

@DrBrad
Created September 30, 2024 21:56
Show Gist options
  • Save DrBrad/9ec03b6a5e484045f3ea46dc8daec7ab to your computer and use it in GitHub Desktop.
Save DrBrad/9ec03b6a5e484045f3ea46dc8daec7ab to your computer and use it in GitHub Desktop.
Spigot 1.21.1 NMS (net.minecraft.server) packet listener

Obviously getting the NMS is a pain and the way that I have obtained it is by opening the bootstrap spigot (the one you use to run your spigot server) as a zip. Once opened go to META-INF/libraries and extract the spigot-api-..-R.-SNAPSHOT.jar, and the spigot-..-R*.*-SNAPSHOT.jar. Also extract all of the netty libraries from the same path. Use these extracted jars as libraries in your plugin.

With all of that you should be able to listen for incoming packets with spigot.

public class MyEventHandler implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) throws NoSuchFieldException, IllegalAccessException {
Player player = event.getPlayer();
//Craft Player (NMS varient of player)
EntityPlayer nmsPlayer = ((CraftPlayer) player).getHandle();
//Get connection
ServerCommonPacketListenerImpl connection = nmsPlayer.c;
//Get Network Manager field (Protected)
Field f = ServerCommonPacketListenerImpl.class.getDeclaredField("e");
f.setAccessible(true);
NetworkManager networkManager = (NetworkManager) f.get(connection);
//Get Netty Channel field (Private)
f = networkManager.getClass().getDeclaredField("n");
f.setAccessible(true);
Channel channel = (Channel) f.get(networkManager);
//Add listener
ChannelDuplexHandler duplexHandler = new ChannelDuplexHandler(){
@Override
public void channelRead(ChannelHandlerContext context, Object object)throws Exception {
if(object instanceof PacketPlayInUseEntity){
PacketPlayInUseEntity packet = (PacketPlayInUseEntity) object;
Field f = packet.getClass().getDeclaredField("b");
f.setAccessible(true);
int z = (int) f.get(packet);
System.out.println("INTERACT-Z: "+z);
}
super.channelRead(context, object);
}
};
channel.pipeline().addBefore("packet_handler", player.getName(), duplexHandler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment