Jump to content

[Solved]Send message to player sending json [1.16.5]


Recommended Posts

This is the first mod I've worked on in a few years now, last time I made a mod the current version of MC was 1.12.

I've been trying to get this send message to all players to work for about 2 days now, I've looked at sources for inspiration on why my message sends json instead of formatted text, to no avail.


package com.github.joelgodofwar.sps.server.events;

import java.util.Random;

import org.apache.logging.log4j.Logger;

import com.github.joelgodofwar.sps.SinglePlayerSleepMod;
import com.github.joelgodofwar.sps.common.WorldFunctions;
import com.mojang.brigadier.exceptions.CommandSyntaxException;

import net.minecraft.block.BedBlock;
import net.minecraft.client.renderer.entity.layers.EnergyLayer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.Util;
import net.minecraft.util.text.ChatType;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TextComponent;
import net.minecraft.util.text.TextComponentUtils;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraftforge.event.TickEvent.ServerTickEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.eventbus.api.Event.Result;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;

public class InteractEventHandler {
	public long daTimer = -1;
	public PlayerEntity sleepingPlayer;
	public World sleepingWorld;
	public String sleepMsg = "<player> went to sleep. Sweet dreams!";//"{\"text\":\"<player> went to sleep. Sweet dreams!\",\"color\":\"gold\"}";//"[\"\",{\"text\":\"<player> went to sleep. Sweet dreams!\"}]";//"<player> went to sleep. Sweet dreams!";
	Logger log;
	@SubscribeEvent(priority = EventPriority.HIGHEST)
    public void stopBedUse(PlayerInteractEvent.RightClickBlock event){
    	log = SinglePlayerSleepMod.LOGGER;
    	Result result = event.getResult();
    	boolean canceled = event.isCanceled();
        if(!event.getWorld().isClientSide) {
        	ServerPlayerEntity splayer = (ServerPlayerEntity) event.getPlayer();
        	splayer.setRespawnPosition(null, null, 0, false, false);
        	PlayerEntity player = event.getPlayer();
			World world = event.getWorld();
            if (world.getBlockState(event.getPos()).getBlock() instanceof BedBlock) {
                if (world.isDay()) {
                //splayer.setRespawnPosition(null, null, daTimer, canceled, canceled);
                if( result != Result.DENY && !canceled ) {
	                if(sleepingPlayer == null) {
	                	sleepingPlayer = player;
	                if(sleepingWorld == null) {
	                	sleepingWorld = world;
	                daTimer = 100; // 200 = 10 seconds
                log.info("world.getDayTime=" + world.getDayTime());
                log.info("world.getGameTime=" + world.getGameTime());
                log.info("world.getTimeOfDay=" + world.getTimeOfDay(0));
                //WorldFunctions.setWorldTime((ServerWorld)world, 12540);
	public void servertick(ServerTickEvent event){
    	if(daTimer == 0){
			daTimer = -1;
			broadcast(sleepingWorld, sleepMsg.replace("<player>", sleepingPlayer.getDisplayName().toString()));
			setDatime(sleepingPlayer, sleepingWorld);
			sleepingPlayer = null;
			sleepingWorld = null;
    	}else if(daTimer > 0){
    public void setDatime(PlayerEntity player, World world){
		//World world = server.worlds[0];
        int i = (300 + (new Random()).nextInt(600)) * 20;
		long Relative_Time = 24000 - world.getDayTime();
		ServerWorld serverworld = (ServerWorld) world;
        serverworld.setDayTime(world.getDayTime() + Relative_Time);
		// TODO Add debug log here
	public void broadcast(World world, String string){
		MinecraftServer mcserver = world.getServer();
		//mcserver.getPlayerList().broadcastMessage(new StringTextComponent(string), ChatType.SYSTEM, null);
		//ITextComponent textComponent = ITextComponent.Serializer.jsonToComponent(string);
		StringTextComponent msg = new StringTextComponent(string);
        for (ServerPlayerEntity player : mcserver.getPlayerList().getPlayers()) {
        	//writeChatMessage(player, "sps.sleep.msg", TextFormatting.GOLD);
			player.sendMessage(msg, ChatType.SYSTEM, Util.NIL_UUID);
        //mcserver.getPlayerList().broadcastMessage(new StringTextComponent(string), ChatType.SYSTEM, Util.NIL_UUID);
	public static void writeChatMessage(PlayerEntity player, String translationKey, TextFormatting color) {
		TranslationTextComponent component = new TranslationTextComponent(translationKey);
		player.sendMessage(component.plainCopy(), Util.NIL_UUID);

As you can see in my source, the message to be sent is simple, "<player> went to sleep. Sweet dreams!", replacing <player> with their displayname.

The attached picture is how the text shows up in chat. I did try using TranslationTextComponent, but was not able to replace any of the text, so abandoned that idea quickly.

I'll probably be back here later to ask how to make sure this works both serverSide and singleplayer.



Link to comment
Share on other sites

11 hours ago, diesieben07 said:

You cannot use toString on an ITextComponent, it will just give you a representation of its data (not JSON, by the way).

Instead of trying to replace in a string you should simply use text interpolation, which translation components support by defaut:

// in your language file:
"mymod.chatmessage": "%1$s went to bed. Sweet dreams!"

// in your code:
message = new TranslationTextComponent("mymod.chatmessage", player.getDisplayName());


Thank you for that.

Is it this part that is causing the representation, because I don't see any other spot where I use toString? "sleepingPlayer.getDisplayName().toString()"

Link to comment
Share on other sites

  • joelstoner changed the title to [Solved]Send message to player sending json [1.16.5]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

By using this site, you agree to our Terms of Use.