Jump to content

Works in internal server but doesn't on a external server


Recommended Posts

This is my first forum post so I aplogize if I do anything wrong or assume this is markdown somewhere since I'm used to it.
I'm building a mod to detect block changes, when people start raids, ...etc to prevent griefing while you afk. 
Here is my code 

package io.github.javaarchive.logitmod;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Nullable;
import javax.imageio.ImageIO;

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

import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.client.Minecraft;
import net.minecraft.client.main.Main;
import net.minecraft.client.renderer.texture.NativeImage;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Hand;
import net.minecraft.util.ScreenShotHelper;
import net.minecraft.util.Util;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockRayTraceResult;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponent;
import net.minecraft.world.World;
import net.minecraftforge.client.event.GuiScreenEvent;
import net.minecraftforge.common.ForgeConfig.Client;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.entity.player.EntityItemPickupEvent;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import net.minecraftforge.event.world.BlockEvent;
import net.minecraftforge.event.world.BlockEvent.BreakEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.TextComponentMessageFormatHandler;
import net.minecraftforge.fml.common.Mod;
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.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

// The value here should match an entry in the META-INF/mods.toml file
@Mod("logit")
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.FORGE)
public class LogitMod
{
    // Directly reference a log4j logger.
    private static final Logger LOGGER = LogManager.getLogger();
	public boolean DONOTDOUBLEEVENT = true;
    PrintWriter pw;
    public String EVIDENCE_DIR = "evidence";
    public LogitMod() {
    	
        // 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);

        // Register ourselves for server and other game events we are interested in
        MinecraftForge.EVENT_BUS.register(this);
    	
    }
    public String getFormattedTime() {
    	SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy_HH-mm-ss");  
        Date date = new Date();  
        return formatter.format(date);
    }
    private void setup(final FMLCommonSetupEvent event) 
    {
        // some preinit code
        LOGGER.info("HELLO FROM PREINIT");
        
        try {
        	pw = new PrintWriter(new BufferedWriter(new FileWriter("log-"+this.getFormattedTime()+".txt")));
        	File evidenceDir = new File(EVIDENCE_DIR);
        	if(!evidenceDir.isDirectory()) {
        		evidenceDir.mkdir();
        	}
        }catch(IOException ex) {
        	ex.printStackTrace();
        }
        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
              pw.close();
            }
          });
        	LOGGER.info("The DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
    }

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

    private void enqueueIMC(final InterModEnqueueEvent event)
    {
        // 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)
    {
        // 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()));
    }
    // 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");
    }
    public boolean isValuable(String name) {
    	if(name.contains("diamond")) {
    		return true;
    	}
    	return false;
    }
    @SubscribeEvent
    public void ItemTossEvent(net.minecraftforge.event.entity.item.ItemTossEvent event) {
        //System.out.println("Item picked up!");
    	
    	if(isValuable(event.getEntityItem().getName().getString().toLowerCase())){
    		Minecraft mc = Minecraft.getInstance();
    		ITextComponent tc = new StringTextComponent("You have dropped a valuable item. It's name is "+event.getEntityItem().getName().getString()+" and it is waiting for you at "+Math.floor(event.getEntityItem().getPosX())+", "+Math.floor(event.getEntityItem().getPosY())+", "+Math.floor(event.getEntityItem().getPosZ()));
    		mc.player.sendMessage(tc);
    		//mc.getConnection()
    		//ScreenshotHelper.
    		/*
    		ScreenShotHelper.saveScreenshot(new File(EVIDENCE_DIR+"/"+getFormattedTime()+".jpg"), mc.currentScreen.width, mc.currentScreen.height, mc.getFramebuffer(), new Consumer<ITextComponent>() {

				@Override
				public void accept(ITextComponent arg0) {
					// TODO Auto-generated method stub
					
				}});
				*/
    		/*try {
				//screenshot.write(new File(EVIDENCE_DIR+"/"+getFormattedTime()+".jpg"));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} */
    		
    		
    		pw.println("ALERT: You dropped a "+event.getEntityItem().getName().getString());
    	
    	}
        pw.println("You dropped a "+event.getEntityItem().getName().getString()+" at "+Math.floor(event.getEntityItem().getPosX())+", "+Math.floor(event.getEntityItem().getPosY())+", "+Math.floor(event.getEntityItem().getPosZ()));
    }
    // You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
    // Event bus for receiving Registry Events)
    
    public void onBlockHarvested(World worldIn, BlockPos pos, BlockState state, PlayerEntity player) {
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	Block block = state.getBlock();
    	pw.println("The player "+player.getName().getString()+" broke(harvested) a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    
    public void onBlockPlacedBy(World worldIn, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack stack) {
    	if(placer.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	pw.println(placer.getName()+" placed a "+state.getBlock().getNameTextComponent().getString()+" block at "+" at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    
    public boolean onBlockActivated(BlockState state, World worldIn, BlockPos pos, PlayerEntity player, Hand handIn, BlockRayTraceResult hit) {
    	pw.println("Block activated by "+player.getName().getString()+" at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    	if(worldIn.isRemote) {
    		return true;
    	}else {
    		return false;
    	}
    }
    
    public void onBlockClicked(BlockState state, World worldIn, BlockPos pos, PlayerEntity player) {
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		return; // We have our own handler for this
    	}
    	Block block = state.getBlock();
    	pw.println("The player "+player.getName().getString()+" left-clicked a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    @SubscribeEvent
    public void GuiOpenEvent(GuiScreenEvent gui) {
    	//gui.getClass()
    	pw.flush();
    }
    @SubscribeEvent
    public void onBlockPlaced(BlockEvent.EntityPlaceEvent event)
    {
    	pw.println("You placed a "+event.getPlacedBlock().getBlock().getNameTextComponent().getString()+" at "+event.getPos().getX()+", "+event.getPos().getY()+", "+event.getPos().getZ());
    }
    @SubscribeEvent
    public void onBreakBlock(BreakEvent event) {
    	PlayerEntity player = event.getPlayer();
    	BlockPos pos = event.getPos();
    	Block block = event.getState().getBlock();
    	if(player.getName().getString().equals(Minecraft.getInstance().player.getName().getString()) && DONOTDOUBLEEVENT) {
    		//return; // We have our own handler for this
    	}
    	pw.println("The player "+player.getName().getString()+" left-clicked a "+block.getNameTextComponent().getString()+" block at "+pos.getX()+", "+pos.getY()+", "+pos.getZ());
    }
    @SubscribeEvent
    public void onBlockBreakEvent(BlockEvent.BreakEvent event) 
    {
    	// Check if a spawner broke
    	if(event.getState().getBlock() == Blocks.SPAWNER)
    	{
    		pw.println("ALERT: YOU BROKE A SPAWNER");
    	}
    	pw.println("Broke the block "+event.getState().getBlock().getNameTextComponent().getString()+" at "+event.getPos().getX()+", "+event.getPos().getY()+", "+event.getPos().getZ());
    }
    @Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
    public static class RegistryEvents {
        @SubscribeEvent
        public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
            // register a new block here
            LOGGER.info("HELLO from Register Block");
        }
    }
}


This works when I play in a singleplayer world however when I build it, and copy it into a standard forge minecraft 1.15.2 client and run it none of the events are triggered. The log file is created but is empty. I know it's probaly a bad idea to flush the file when the inventory opens but that's just temporary testing. 

Second question: Since I'm not able to test yet but does my code detect other players breaking/placing blocks. If so how can I make it detect those events? 

Edited by javaarchive/rpeng2007

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Link to comment
Share on other sites

19 minutes ago, javaarchive/rpeng2007 said:

if(isValuable(event.getEntityItem().getName().getString().toLowerCase())){

    Minecraft mc = Minecraft.getInstance();

You're reaching across logical sides. You can't do this.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Not sure by what you mean by that, could you elaborate a bit more. The mod is meant to be run on client side only. I only found this by accident when I was looking for where somebody was obtaining their mc variable from. If this is not the right way to do it, please tell me the correct way. I think the only thing I'm using it for is to get the current player's username. 

Edited by javaarchive/rpeng2007

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Link to comment
Share on other sites

1 hour ago, javaarchive/rpeng2007 said:

    public boolean isValuable(String name) {
        if(name.contains("diamond")) {
            return true;
        }
        return false;
    }

This code is awful. Do not compare things to strings. entity.getItem().getItem() == Items.DIAMOND.

48 minutes ago, javaarchive/rpeng2007 said:

Not sure by what you mean by that, could you elaborate a bit more. The mod is meant to be run on client side only.

1 hour ago, javaarchive/rpeng2007 said:

copy it into a standard forge minecraft 1.15.2 client and run it none of the events are triggered

 

The event is only fired on the server side.

 

When you connect to a dedicated server, that server is the logical server, but also the physical server. Because it is physically elsewhere.

However when you play single player, the physical client runs its own integrated server locally on a separate thread, this is the logical server located at the physical client.

When you do something on the logical server that accesses something on the logical client, that's known as "reaching across sides." It works only because the two threads are running in the same JVM. But because they are different process threads you'll sometimes get random and unexpected crashes.

  • Thanks 1

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Thanks for explaining this. This is my third attempt to make an minecraft mod, so I tend to not be able to find the best way to do things. Which event can I listen for on the client side, so I know when some player breaks/places a block that I can see? 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Link to comment
Share on other sites

That's annoying, any way to log when I break/place a block on the client without putting stuff on the server? 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Link to comment
Share on other sites

Thanks for that. It was very helpful. Can this event fire when other players break a block, just curious. 

Hi there, I'm an inexperienced modder currently but I'm sort of good at figuring things out. If you are helping me with anything, thank you! I try to make posts as quality as I can and try to keep the grammar good. 

Link to comment
Share on other sites

Howdy.

You can detect the effects of players breaking a block on the client side, if they're within your render distance.  That might be enough for you?

Your client-side code could check the location of all players, every tick.  And then you could look at the blocks within a reasonable radius of each player, to see if they have changed (been broken, TNT has been placed, etc).  Might be better than nothing, if you have no way to install a mod on the server.

 

-TGG

 

  • Thanks 1
Link to comment
Share on other sites

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.

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

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • If you're seeking an unparalleled solution to recover lost or stolen cryptocurrency, let me introduce you to GearHead Engineers Solutions. Their exceptional team of cybersecurity experts doesn't just restore your funds; they restore your peace of mind. With a blend of cutting-edge technology and unparalleled expertise, GearHead Engineers swiftly navigates the intricate web of the digital underworld to reclaim what's rightfully yours. In your moment of distress, they become your steadfast allies, guiding you through the intricate process of recovery with transparency, trustworthiness, and unwavering professionalism. Their team of seasoned web developers and cyber specialists possesses the acumen to dissect the most sophisticated schemes, leaving no stone unturned in their quest for justice. They don't just stop at recovering your assets; they go the extra mile to identify and track down the perpetrators, ensuring they face the consequences of their deceitful actions. What sets  GearHead Engineers apart is not just their technical prowess, but their unwavering commitment to their clients. From the moment you reach out to them, you're met with compassion, understanding, and a resolute determination to right the wrongs inflicted upon you. It's not just about reclaiming lost funds; it's about restoring faith in the digital landscape and empowering individuals to reclaim control over their financial futures. If you find yourself ensnared in the clutches of cybercrime, don't despair. Reach out to GearHead Engineers and let them weave their magic. With their expertise by your side, you can turn the tide against adversity and emerge stronger than ever before. In the realm of cybersecurity, GearHead Engineers reigns supreme. Don't just take my word for it—experience their unparalleled excellence for yourself. Your journey to recovery starts here.
    • Ok so this specific code freezes the game on world creation. This is what gets me so confused, i get that it might not be the best thing, but is it really so generation heavy?
    • Wizard web recovery has exhibited unparalleled strength in the realm of recovery. They stand out as the premier team to collaborate with if you encounter withdrawal difficulties from the platform where you’ve invested. Recently, I engaged with them to recover over a million dollars trapped in an investment platform I’d been involved with for months. I furnished their team with every detail of the investment, including accounts, names, and wallet addresses to which I sent the funds. This decision proved to be the best I’ve made, especially after realizing the company had scammed me.   Wizard web recovery ensures exemplary service delivery and ensures the perpetrators face justice. They employ advanced techniques to ensure you regain access to your funds. Understandably, many individuals who have fallen victim to investment scams may still regret engaging in online services again due to the trauma of being scammed. However, I implore you to take action. Seek assistance from Wizard Web Recovery today and witness their remarkable capabilities. I am grateful that I resisted their enticements, and despite the time it took me to discover Wizard web recovery, they ultimately fulfilled my primary objective. Without wizard web recovery intervention, I would have remained despondent and perplexed indefinitely.
    • I've tested the same code on three different envionrments (Desktop win10, desktop Linux and Laptop Linux) and it kinda blows up all the same. Gonna try this code and see if i can tune it
  • Topics

×
×
  • Create New...

Important Information

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