ProtocolLib

3M Downloads

Chat server packet not working (only in 1.19.4)

Ibramsou opened this issue · 5 comments

commented
  • This issue is not solved in a development build

Hi, I found that in 1.19.4 outbound chat packet aren't recognized by ProtocolLib

package ua.realalpha.itsmyconfig;

import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.events.ListenerPriority;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketContainer;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.utility.MinecraftVersion;
import com.comphenix.protocol.wrappers.WrappedChatComponent;
import me.clip.placeholderapi.PlaceholderAPI;
import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import ua.realalpha.itsmyconfig.model.ModelType;
import ua.realalpha.itsmyconfig.xml.Tag;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class PacketChatListener extends PacketAdapter {

    private final ModelRepository modelRepository;
    private ItsMyConfig itsMyConfig;
    private final Pattern filtreColorSection = Pattern.compile("[§&][a-zA-Z0-9]");

    public PacketChatListener(ItsMyConfig itsMyConfig, ModelRepository modelRepository) {
        super(itsMyConfig, ListenerPriority.NORMAL,  PacketType.Play.Server.SYSTEM_CHAT);
        this.itsMyConfig = itsMyConfig;
        this.modelRepository = modelRepository;
    }

    @Override
    public void onPacketSending(PacketEvent event) {
        System.out.println("MESSAGE SENT !");
        PacketContainer packetContainer = event.getPacket();
        Player player = event.getPlayer();
        BaseComponent[] baseComponents;
        if (!MinecraftVersion.CAVES_CLIFFS_2.isAtLeast(MinecraftVersion.getCurrentVersion())) {
            String s = packetContainer.getStrings().readSafely(0);
            if (s == null) return;
            baseComponents = ComponentSerializer.parse(s);
        }else {
            WrappedChatComponent wrappedChatComponent = packetContainer.getChatComponents().readSafely(0);
            if (wrappedChatComponent == null || (packetContainer.getChatComponentArrays().readSafely(0) != null && packetContainer.getChatComponentArrays().readSafely(0).length != 0)) return;

            baseComponents = ComponentSerializer.parse(wrappedChatComponent.getJson());
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (BaseComponent baseComponent : baseComponents) {
            stringBuilder.append(baseComponent.toLegacyText());
        }
        String message = stringBuilder.toString();
        message = PlaceholderAPI.setPlaceholders(player, message);
        message = PlaceholderAPI.setBracketPlaceholders(player, message);
        String plainTextWithOutColor = message.replaceAll(filtreColorSection.pattern(), "");

        if (plainTextWithOutColor.startsWith(itsMyConfig.getSymbolPrefix())) {
            String plainTextWithOutSymbolPrefix = message.substring(message.indexOf(itsMyConfig.getSymbolPrefix()) + 1).replaceAll("§", "&");

            if (!plainTextWithOutSymbolPrefix.isEmpty()) {
                List<String> tags = Tag.getTags(plainTextWithOutSymbolPrefix);
                if (!tags.isEmpty()) {
                    List<String> texts = Tag.textsWithoutTags(plainTextWithOutSymbolPrefix);
                    if (!texts.isEmpty()) {
                        Audience audience = itsMyConfig.adventure().player(player);
                        MiniMessage miniMessage = MiniMessage.miniMessage();
                        texts.forEach(text -> {
                            Component parsed = miniMessage.deserialize(text);
                            ItsMyConfig.applyingChatColor(parsed);
                            audience.sendMessage(parsed);
                        });
                    }

                }
                List<ModelType> modelTypes = tags.stream().map(ModelType::getModelType).filter(modelRepository::hasModel).collect(Collectors.toList());
                for (ModelType modelType : modelTypes) {
                    modelRepository.getModel(modelType).apply(player, Tag.getContent(modelType.getTagName(), plainTextWithOutSymbolPrefix), tags);
                }

                if (modelTypes.isEmpty()) {
                    Audience audience = itsMyConfig.adventure().player(player);
                    MiniMessage miniMessage = MiniMessage.miniMessage();
                    Component parsed = miniMessage.deserialize(plainTextWithOutSymbolPrefix);
                    ItsMyConfig.applyingChatColor(parsed);
                    audience.sendMessage(parsed);
                }


            }

            event.setCancelled(true);
        }
    }

}

Nothing in the console when the packet is sent to the player:
image

The code works except in 1.19.4

Thanks for the support

commented

I guess you are using Paper. Paper added two more fields to the NMS packet, namely one for the Bungee Chat Component and one for the Adventure Chat component. So we have 3 fields that can contain the chat message The problem is, that

a) If one of the fields is set, the other ones are null
b) If you change one of these fields, the others need to be set to null. Otherwise, the changes will be ignored

commented

No you don't understand, don't look at the entire code, just note that the message "MESSAGE SENT" should appears in the console, but it don't because the packet event is not recognized, I also tried with "CHAT" packet instead of "SYSTEM_CHAT", but same results.

commented

Oh, okay. I'm sorry, I confused it with the "Message send" by the "message" command. Could you please share the output of /protocol dump?

commented

Hi, no problem :)
Here is the results of /protocol dump

ProtocolLib Dump
Timestamp: 05/29/23 20:29:39

ProtocolLib Version: ProtocolLib v5.1.0-SNAPSHOT-645
Bukkit Version: 1.19.4-R0.1-SNAPSHOT
Server Version: git-Purpur-1976 (MC: 1.19.4)
Java Version: 17.0.6

ProtocolLib: com.comphenix.protocol.ProtocolLib@97460ba[
  statistics=com.comphenix.protocol.metrics.Statistics@39c65ee2
  packetTask=2
  tickCounter=4330
  configExpectedMod=1
  updater=com.comphenix.protocol.updater.SpigotUpdater@55f87a76
  redirectHandler=com.comphenix.protocol.ProtocolLib$2@2ee1364e
  commandProtocol=com.comphenix.protocol.CommandProtocol@43ae298
  commandPacket=com.comphenix.protocol.CommandPacket@f809db3
  commandFilter=com.comphenix.protocol.CommandFilter@19bd6dff
  packetLogging=com.comphenix.protocol.PacketLogging@3e496bc0
  skipDisable=false
  isEnabled=true
  loader=io.papermc.paper.plugin.manager.DummyBukkitPluginLoader@6db460b3
  server=CraftServer{serverName=Purpur,serverVersion=git-Purpur-1976,minecraftVersion=1.19.4}
  file=plugins/ProtocolLib.jar
  description=org.bukkit.plugin.PluginDescriptionFile@14f25e13
  pluginMeta=org.bukkit.plugin.PluginDescriptionFile@14f25e13
  dataFolder=plugins/ProtocolLib
  classLoader=PluginClassLoader{plugin=ProtocolLib v5.1.0-SNAPSHOT-645, pluginEnabled=true, url=plugins/ProtocolLib.jar}
  naggable=true
  newConfig=YamlConfiguration[path='', root='YamlConfiguration']
  configFile=plugins/ProtocolLib/config.yml
  logger=com.destroystokyo.paper.utils.PaperPluginLogger@2f6f655f
]
Manager: com.comphenix.protocol.injector.PacketFilterManager@5966128c[
  plugin=ProtocolLib v5.1.0-SNAPSHOT-645
  server=CraftServer{serverName=Purpur,serverVersion=git-Purpur-1976,minecraftVersion=1.19.4}
  reporter=com.comphenix.protocol.ProtocolLib$1@5fe2cd75
  minecraftVersion=(MC: 1.19.4)
  asyncFilterManager=com.comphenix.protocol.async.AsyncFilterManager@3f9347bf
  pluginVerifier=com.comphenix.protocol.injector.PluginVerifier@6b82888f
  inboundListeners=com.comphenix.protocol.injector.SortedPacketListenerList@2991501
  outboundListeners=com.comphenix.protocol.injector.SortedPacketListenerList@4b59f942
  registeredListeners=[PacketAdapter[plugin=ItsMyConfig, sending=ListeningWhitelist[priority=NORMAL, packets=[SYSTEM_CHAT[class=ClientboundSystemChatPacket, id=100]], gamephase=PLAYING, options=[]], receiving=EMPTY_WHITELIST]]
  packetInjector=com.comphenix.protocol.injector.netty.manager.NetworkManagerPacketInjector@6ed2e129
  playerInjectionHandler=com.comphenix.protocol.injector.netty.manager.NetworkManagerPlayerInjector@11ebda8c
  networkManagerInjector=com.comphenix.protocol.injector.netty.manager.NetworkManagerInjector@5b10e4ad
  debug=false
  closed=false
  injected=true
]

Listeners:
ua.realalpha.itsmyconfig.PacketChatListener@58ffbb9f[
  modelRepository=ua.realalpha.itsmyconfig.ModelRepository@5f079564
  itsMyConfig=ItsMyConfig v1.1.3
  filtreColorSection=[§&][a-zA-Z0-9]
  plugin=ItsMyConfig v1.1.3
  connectionSide=SERVER_SIDE
  receivingWhitelist=EMPTY_WHITELIST
  sendingWhitelist=ListeningWhitelist[priority=NORMAL, packets=[SYSTEM_CHAT[class=ClientboundSystemChatPacket, id=100]], gamephase=PLAYING, options=[]]
]

Plugins Using ProtocolLib:
ItsMyConfig by [RealAlphaUA]
commented

Try listening for PacketType.Play.Server.CHAT in addition and check if this packet is sent instead of the SYSTEM_CHAT one. Maybe the message commands sends the message as a player message.