Creating Your First Listener

Here's how you can create a simple Packet Listener.

We utilize packet listeners to process information transmitted between the client and the server. The PacketReceiveEvent resembles incoming packets (from the server's perspective), whilst the PacketSendEvent is called for outgoing packets.

We'll demonstrate how you can make your own listener in this basic example. Your listener will wait for any client to send a "Chat Message" packet. Whenever we detect such a packet, we then proceed by reading its content. Only if the client sends us a "ping" message, we'll respond with a "pong" message.

import com.github.retrooper.packetevents.event.PacketListenerAbstract;
import com.github.retrooper.packetevents.event.PacketListenerPriority;
import com.github.retrooper.packetevents.event.PacketReceiveEvent;
import com.github.retrooper.packetevents.protocol.packettype.PacketType;
import com.github.retrooper.packetevents.protocol.player.User;
import com.github.retrooper.packetevents.wrapper.play.client.WrapperPlayClientChatMessage;

public class PacketEventsPacketListener implements PacketListener {
    @Override
    public void onPacketReceive(PacketReceiveEvent event) {
        // The user represents the player.
        User user = event.getUser();
        // Identify what kind of packet it is.
        if (event.getPacketType() != PacketType.Play.Client.CHAT_MESSAGE)
            return;
        // Use the correct wrapper to process this packet.
        WrapperPlayClientChatMessage chatMessage = new WrapperPlayClientChatMessage(event);
        // Access the data within the wrapper using its "getters"
        String message = chatMessage.getMessage();
        // Check if the message is "ping"
        if (message.equalsIgnoreCase("ping")) {
            //Respond with a "pong" message to the client.
            user.sendMessage("pong");
        }
    }
}

The user represents the player (or client).

Since PacketEvents supports multiple platforms, we offer functionality that is capable of running on all those platforms within our User instance.

You don't have to use our user instance, you could replace it with the Bukkit player:

Player player = event.getPlayer();

The wrapper used to process the packet must match with the packet type, hence you should always check the type of a packet before you process it.

Please note that Bukkit imposes limitations on asynchronous access, potentially hindering accessibility to certain functionalities within your PacketEvents listener. You'll typically encounter issues with features within Bukkit pertaining to the Minecraft World.

Last updated