Skip to content

Instantly share code, notes, and snippets.

@rainbowdashlabs
Last active August 27, 2021 17:14
Show Gist options
  • Save rainbowdashlabs/e927e30b5c56c57e39dc539215a89ca4 to your computer and use it in GitHub Desktop.
Save rainbowdashlabs/e927e30b5c56c57e39dc539215a89ca4 to your computer and use it in GitHub Desktop.
ProtocolLib cant read the components in chat packets when using adventure. This workaround allows reading of the content on servers using adventure and those who are not
// Workaround for https://github.com/aadnk/ProtocolLib/issues/191/
package de.eldoria.util;
import com.comphenix.protocol.events.PacketContainer;
import net.kyori.adventure.text.TextComponent;
import java.util.function.Function;
import java.util.logging.Level;
public class AdventureComponentAdapter {
private static Function<PacketContainer, String> adapter = AdventureComponentAdapter::adapter;
public static String rawMessage(PacketContainer packet) {
return adapter.apply(packet);
}
private static String adapter(PacketContainer packet) {
buildAdapter(packet);
return adapter.apply(packet);
}
private static void buildAdapter(PacketContainer packet) {
try {
var field = packet.getHandle().getClass().getField("adventure$message");
adapter = container -> {
try {
var component = (TextComponent) field.get(container.getHandle());
return component.content();
} catch (IllegalAccessException e) {
System.out.println("Could not read field value of adventure$message");
}
return getSafeString(container);
};
} catch (NoSuchFieldException e) {
adapter = AdventureComponentAdapter::getSafeString;
}
}
private static String getSafeString(PacketContainer container) {
if (container.getStrings().size() == 0) {
return "";
}
return container.getStrings().read(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment