Jump to content
Search In
  • More options...
Find results that contain...
Find results in...

[1.16.5] Help with ServerSided Configuration [SOLVED]


Recommended Posts

4 minutes ago, diesieben07 said:

Show what you tried.

Under FMLServerStoppingEvent I've also tried "Config.SERVER_SPEC.save();"

Bottom of the file, called on FMLServerStartedEvent

Spoiler

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


import java.awt.Color;
import java.io.File;
import java.nio.file.Path;
import java.util.Random;

import org.apache.logging.log4j.Logger;

import com.github.joelgodofwar.sps.SinglePlayerSleepMod;
import com.github.joelgodofwar.sps.common.config.Config;
import com.github.joelgodofwar.sps.common.config.ConfigHelper;
import com.github.joelgodofwar.sps.common.config.ConfigHolder;
import com.github.joelgodofwar.sps.common.config.SinglePlayerSleepModConfig;
import com.github.joelgodofwar.sps.server.config.SPSConfig;
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;
import net.minecraftforge.fml.config.ConfigTracker;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.fml.loading.FMLPaths;

@SuppressWarnings("unused")
public class InteractEventHandler {
	public long daTimer = -1;
	public PlayerEntity sleepingPlayer;
	public World sleepingWorld;
	Logger log;
	private static long mobSpawningStartTime = 12541;//12600;
	private static long mobSpawningStopTime = 23600;
	
	public static String sleepMsg;
	public static boolean enabled;
	public static int delayLen;
	
    @SuppressWarnings("resource")
	@SubscribeEvent(priority = EventPriority.HIGHEST)
    public void playerSleep(PlayerInteractEvent.RightClickBlock event){
    	log = SinglePlayerSleepMod.LOGGER;
    	Result result = event.getResult();
    	boolean canceled = event.isCanceled();
    	
        if(!event.getWorld().isRemote) {
        	log.info("event.getWorld().isRemote=" + event.getWorld().isRemote);
        	final String modId = "singleplayersleepmod";
            final ModConfig.Type type = ModConfig.Type.SERVER;
            final String configFileName = ConfigTracker.INSTANCE.getConfigFileName(modId, type);
            if (configFileName != null) {
            	File f = new File(configFileName);
            	log.info("config file=" + f.getAbsolutePath());
            }else {
            	log.warn("Config file not found! - Warning");
            }
            final Path defaultConfigPath = FMLPaths.GAMEDIR.get().resolve(FMLConfig.defaultConfigPath());
            log.info("defaultConfigPath=" + defaultConfigPath);
            log.info("configFileName=" + configFileName);
            log.info("sleepMsg=" + Config.SERVER.str_singleplayersleep_SleepMessage.get());
            log.info("sleepLength=" + Config.SERVER.int_singleplayersleep_SleepLength.get());
            log.info("enabled=" + Config.SERVER.bool_singleplayersleep_Enabled.get());
            Config.SERVER.str_singleplayersleep_SleepMessage.save();
            //ConfigHelper.setValueAndSave(ConfigHelper.commonConfig, ConfigHelper.SleepLengthPath, 100);
        	//log.info("event.getWorld().isRemote=" + event.getWorld().isRemote);
        	
        	PlayerEntity player = event.getPlayer();
			World world = event.getWorld();
        	
            if (world.getBlockState(event.getPos()).getBlock() instanceof BedBlock) {
            	log.info("IsNight(world)=" + IsNight(world));
            	log.info("world.isThundering()=" + world.isThundering());
                if (!IsNight(world)&&!world.isThundering()) {
                    return;
                }
                if( result != Result.DENY && !canceled ) {
	                if(sleepingPlayer == null) {
	                	sleepingPlayer = player;
	                	log.info("sleepingPlayer SET");
	                }
	                if(sleepingWorld == null) {
	                	sleepingWorld = world;
	                	log.info("sleepingWorld SET");
	                }
	                daTimer = 200; // 200 = 10 seconds
                }
                
                //log.info("world.getDayTime=" + world.getDayTime());
                //log.info("world.getGameTime=" + world.getGameTime());
                //log.info("world.getTimeOfDay=" + world.getTimeOfDay(0));
            }
        }
    }
    
    @SubscribeEvent
	public void servertick(ServerTickEvent event){
    	if(daTimer == 0){
    		log.info("STE - timer finished");
			daTimer = -1;
			broadcast(sleepingWorld, "%1$s went to bed. Sweet dreams!");//"singleplayersleepmod.sleepmsg");
			log.info("STE - broadcast sent");
			setDatime(sleepingPlayer, sleepingWorld);
			log.info("STE - setTime run");
			sleepingPlayer = null;
			sleepingWorld = null;
			log.info("STE - variables reset");
    	}else if(daTimer > 0){
			daTimer--;
		}
    }
    
    public void setDatime(PlayerEntity player, World world){
        //int i = (300 + (new Random()).nextInt(600)) * 20;
        ServerWorld serverworld = (ServerWorld) world;
		if( world.isRaining() || world.isThundering()){
			serverworld.setWeather(60000, 0, false, false);
		}
		long Relative_Time = 24000 - world.getDayTime();
        serverworld.setDayTime(world.getDayTime() + Relative_Time);
		// TODO Add debug log here
	}
	
	public void broadcast(World world, String string){
		//MinecraftServer mcserver = world.getServer();
		StringTextComponent msg = new StringTextComponent(string);
    	msg.getStyle().applyFormatting(TextFormatting.GOLD);
    	
    	TranslationTextComponent component = new TranslationTextComponent(string, sleepingPlayer.getDisplayName());
		component.mergeStyle(TextFormatting.GOLD);
		log.info("B - String parsed");
		//MinecraftServer server = world.getServer().getPlayerList().sendMessageToTeamOrAllPlayers(sleepingPlayer, component);;
        /**for (ServerPlayerEntity player : world.getServer().getPlayerList().getPlayers()) {
    		player.sendMessage(component, Util.DUMMY_UUID);
    		log.info("B - Player " + player.getName() + " messaged");
    		//
        }//*/
        world.getServer().getPlayerList().func_232641_a_(component, ChatType.SYSTEM, sleepingPlayer.getUniqueID());//.sendMessageToTeamOrAllPlayers(sleepingPlayer, component);
        //mcserver.getPlayerList().broadcastMessage(component, ChatType.SYSTEM, Util.NIL_UUID);
        log.info("B - sleepMsg=" + sleepMsg);
        log.info("B - sleepLen=" + delayLen);
        log.info("B - enabled=" + enabled);
	}
	
	public static void writeChatMessage(PlayerEntity player, String translationKey, TextFormatting color) {
		TranslationTextComponent component = new TranslationTextComponent(translationKey);
		component.getStyle().applyFormatting(color);
		player.sendMessage(component, Util.DUMMY_UUID);
	}
	
	public static boolean IsNight(World world){
		long time = (world.getDayTime()) % 24000;
		return time >= mobSpawningStartTime && time < mobSpawningStopTime;
	}
	
	@SubscribeEvent
	public static void onModConfigEvent(final ModConfig.ModConfigEvent event) {
		final ModConfig config = event.getConfig();
		// Rebake the configs when they change
		if (config.getSpec() == ConfigHolder.CLIENT_SPEC) {
			ConfigHelper.bakeClient(config);
		}else if (config.getSpec() == ConfigHolder.SERVER_SPEC) {
			ConfigHelper.bakeServer(config);
		}else if (config.getSpec() == ConfigHolder.COMMON_SPEC) {
			ConfigHelper.bakeCommon(config);
		}
		
	}
	
	public void loadConfig() {
		sleepMsg = SinglePlayerSleepModConfig.str_singleplayersleep_SleepMessage;
		enabled = SinglePlayerSleepModConfig.bool_singleplayersleep_Enabled;
		delayLen = SinglePlayerSleepModConfig.int_singleplayersleep_SleepLength;
	}
	
	public void saveConfig() {
		Config.SERVER.str_singleplayersleep_SleepMessage.set(sleepMsg);
		Config.SERVER.int_singleplayersleep_SleepLength.set(delayLen);
		Config.SERVER.bool_singleplayersleep_Enabled.set(enabled);
		Config.SERVER.str_singleplayersleep_SleepMessage.save();
		Config.SERVER.int_singleplayersleep_SleepLength.save();
		Config.SERVER.bool_singleplayersleep_Enabled.save();
	}
}

 

 

Spoiler

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

import org.apache.commons.lang3.tuple.Pair;

import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.BooleanValue;
import net.minecraftforge.common.ForgeConfigSpec.IntValue;

public class SPSConfig {
	
	/**
     * General configuration that doesn't need to be synchronized but needs to be available before server startup
     */
    public static class Common {
        public final ForgeConfigSpec.ConfigValue<String> str_singleplayersleep_SleepMessage;//public final ForgeConfigSpec.ConfigValue<? extends String> str_singleplayersleep_SleepMessage;
        public final BooleanValue bool_singleplayersleep_Enabled;
        public final IntValue int_singleplayersleep_SleepLength;

        Common(ForgeConfigSpec.Builder builder)
        {
            builder.comment("General configuration settings")
                    .push("general");

            str_singleplayersleep_SleepMessage = builder
                    .comment("Defines the sleep message to be displayed when a player sleeps.",
                             "%1$s is a placeholder for the sleeping player's name.")
                    .translation("singleplayersleep.config.sleepmsg")
                    .define("str_singleplayersleep_SleepMessage", "%1$s went to bed. Sweet dreams!");

            bool_singleplayersleep_Enabled = builder
                    .comment("Enable or Disable this mod")
                    .translation("singleplayersleep.config.enabled")
                    .define("bool_singleplayersleep_Enabled", true);

            int_singleplayersleep_SleepLength = builder
                    .comment("Define the length of time to delay in ticks before changing the time.",
                    		"200(10 seconds) is default, as it is just over the vanilla length for single player.")
                    .translation("singleplayersleep.config.delay")
                    .defineInRange("int_singleplayersleep_SleepLength", 200, 0, Integer.MAX_VALUE);

            builder.pop();
        }

    }
    
    public static final ForgeConfigSpec commonSpec;
    public static final Common COMMON;
    static {
        final Pair<Common, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(Common::new);
        commonSpec = specPair.getRight();
        COMMON = specPair.getLeft();
    }
    
}

 

This is where I grabbed the values into variables.

Spoiler

package com.github.joelgodofwar.sps.common.config;

public class SinglePlayerSleepModConfig {

/** // Client	
public static boolean clientBoolean;
public static List<String> clientStringList;
public static EnumDyeColor clientEnumDyeColor;

// Server	
public static boolean serverBoolean;
public static List<String> serverStringList;
public static EnumDyeColor serverEnumDyeColor;*/
	
//Common	
public static String str_singleplayersleep_SleepMessage;//public final ForgeConfigSpec.ConfigValue<? extends String> str_singleplayersleep_SleepMessage;
public static Boolean bool_singleplayersleep_Enabled;
public static Integer int_singleplayersleep_SleepLength;

	
}

 

I think that's it, if not the repo has all of the files.

Link to post
Share on other sites

I would honestly delete that entire repo and recreate it correctly, that privacy issue is still there for anyone that wants to find it.

Just trying to help keep ya safe buddy!

Link to post
Share on other sites
13 hours ago, Ugdhar said:

I would honestly delete that entire repo and recreate it correctly, that privacy issue is still there for anyone that wants to find it.

Just trying to help keep ya safe buddy!

While I still don't see my login info in those files, I have deleted the repo and republished it using github Desktop. Thank you.

Link to post
Share on other sites

For those interested this is the solution for me, instead of using server config, I setup common config.

This is the Config class.

Spoiler

 


package com.github.joelgodofwar.sps.common.config;

import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.common.ForgeConfigSpec.BooleanValue;
import net.minecraftforge.common.ForgeConfigSpec.IntValue;

import org.apache.commons.lang3.tuple.Pair;

public class Config {
    //public static final ServerConfig SERVER;
    //public static final ForgeConfigSpec SERVER_SPEC;
    public static final CommonConfig COMMON;
    public static final ForgeConfigSpec COMMON_SPEC;

    static {
        final Pair<CommonConfig, ForgeConfigSpec> specPair = new ForgeConfigSpec.Builder().configure(CommonConfig::new);
        COMMON_SPEC = specPair.getRight();
        COMMON = specPair.getLeft();
    }
    
    public static String str_SleepMessage;
    public static Boolean bool_Enabled;
    public static Integer int_SleepLength;
    public static Boolean bool_CancelOnExit;
    public static Boolean bool_Debug;
    
    public static void load() {
    	str_SleepMessage = COMMON.str_SleepMessage.get();
    	bool_Enabled = COMMON.bool_Enabled.get();
    	int_SleepLength = COMMON.int_SleepLength.get();
    	bool_CancelOnExit = COMMON.bool_CancelOnExit.get();
    	bool_Debug = COMMON.bool_Debug.get();
    }
    
    public static class CommonConfig {
    	public final ForgeConfigSpec.ConfigValue<String> str_SleepMessage;
        public final BooleanValue bool_Enabled;
        public final IntValue int_SleepLength;
        public final BooleanValue bool_CancelOnExit;
        public final BooleanValue bool_Debug;
    		

    		
        CommonConfig(final ForgeConfigSpec.Builder builder) {
            builder.comment("Single Player Sleep Mod settings")
            .push("settings");

    		str_SleepMessage = builder
    		        .comment(" Defines the sleep message to be displayed when a player sleeps.",
    		                 " %1$s is a placeholder for the sleeping player's name.")
    		        .translation("singleplayersleep.config.sleepmsg")
    		        .define("str_SleepMessage", "%1$s went to bed. Sweet dreams!");
    		
    		bool_Enabled = builder
    		        .comment(" Enable or Disable this mod")
    		        .translation("singleplayersleep.config.enabled")
    		        .define("bool_Enabled", true);
    		
    		int_SleepLength = builder
    		        .comment(" Define the length of time to delay in ticks before changing the time.",
    		        		" 300(15 seconds) is default, as it is just over the vanilla length for single player.")
    		        .translation("singleplayersleep.config.delay")
    		        .defineInRange("int_SleepLength", 300, 20, Integer.MAX_VALUE);
    		
    		bool_CancelOnExit =  builder
    		        .comment(" Should SPS cancel sleep if the player exits the bed?")
    		        .translation("singleplayersleep.config.cancel_on_exit")
    		        .define("bool_CancelOnExit", true);
    		
    		bool_Debug =  builder
    		        .comment(" Should SPS log debug information in the console/log?")
    		        .translation("singleplayersleep.config.debug")
    		        .define("bool_Devug", false);
    		
    		builder.pop();
    		
    	}
    }
}

 

You register it like this, in the main class of your mod.

Spoiler

package com.github.joelgodofwar.sps;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.github.joelgodofwar.sps.common.config.Config;
import com.github.joelgodofwar.sps.server.events.InteractEventHandler;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fml.event.server.FMLServerStartedEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.event.server.FMLServerStoppingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

@Mod("singleplayersleepmod")
public class SinglePlayerSleepMod {
	
	// Directly reference a log4j logger.
    public static final Logger LOGGER = LogManager.getLogger();
    public static final String MOD_ID = "singleplayersleepmod";
    InteractEventHandler IEventHandler = new InteractEventHandler();

    public SinglePlayerSleepMod() {
        // Register the setup method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
        // Register the enqueueIMC method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
        // Register the processIMC method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
        // Register the doClientStuff method for modloading
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::doClientStuff);
        ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.COMMON_SPEC, "singleplayersleepmod-common.toml");
        
        // Register ourselves for server and other game events we are interested in
        MinecraftForge.EVENT_BUS.register(this);
    }
    

    private void setup(final FMLCommonSetupEvent event){ // some preinit code
        LOGGER.info("SinglePlayerSleep Loading...");
        
        //Config config = new Configuration(new File(event.getModConfigurationDirectory().getAbsolutePath() + "additional/path/to/your/config.cfg"));
    }

    private void enqueueIMC(final InterModEnqueueEvent event){ // Send InterModComms
        // some example code to dispatch IMC to another mod
        //InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";});
    }

    private void processIMC(final InterModProcessEvent event){ // Receive InterModComms
        // some example code to receive and process InterModComms from other mods
        //LOGGER.info("Got IMC {}", event.getIMCStream().
        //        map(m->m.getMessageSupplier().get()).
        //        collect(Collectors.toList()));
    }

    @SuppressWarnings("resource")
	private void doClientStuff(final FMLClientSetupEvent event) { // Client side stuff
        // do something that can only be done on the client
        //LOGGER.info("Got game settings {}", event.getMinecraftSupplier().get().options);
        
    }

    // You can use SubscribeEvent and let the Event Bus discover methods to call
    @SubscribeEvent
    public void onServerStarting(FMLServerStartingEvent event) {
        // do something when the server starts
        //LOGGER.info("HELLO from server starting");
    }
    @SubscribeEvent
    public void doServerStuff(final FMLServerStartedEvent  event) {
    	LOGGER.info("Registering Events...");
    	MinecraftForge.EVENT_BUS.register(new InteractEventHandler());
    	//IEventHandler.loadConfig();
    	LOGGER.info("Loading Complete.");
    }
    @SubscribeEvent
    public void doServerStuff(final FMLServerStoppingEvent  event) {
    	LOGGER.info("Saving configs...");
    	Config.COMMON_SPEC.save();
    }
}

 

and you use the values like this.

Spoiler

if(Config.COMMON.bool_Debug.get()){log.info("sleepingWorld SET");}

 

 

Link to post
Share on other sites
  • joelstoner changed the title to [1.16.5] Help with ServerSided Configuration [SOLVED]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
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 Privacy Policy.