Minecraft Anti cheat ( java: cannot find symbol ) [duplicate] - java

This question already has an answer here:
Cannot resolve method 'getTitle' in 'Inventory' when click event
(1 answer)
Closed 6 days ago.
Im trying to make a minecraft anti cheat with bukkit. my server version is 1.18.
but i seem to get this error;
java: cannot find symbol symbol: method getTitle() location: variable inventory of type org.bukkit.inventory.Inventory
here is the segment of code that error is referring about;
if (inventory.getTitle().equals("Flagged Players")) {
full segment of code (Not entire file of code):
package anticheat.anticheat;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.event.player.PlayerMoveEvent;
public class Anticheat implements Listener {
private Map<Player, Boolean> flaggedPlayers = new HashMap<>();
private Map<Player, Inventory> flaggedPlayersInventory = new HashMap<>();
#EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
if (isUsingFlyHack(player)) {
// Flag the player and kick them from the server
flagPlayer(player);
player.kickPlayer("Using fly hacks is not allowed on this server");
}
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
Inventory inventory = event.getInventory();
if (inventory.getType() == InventoryType.CHEST) {
if (inventory.getTitle().equals("Flagged Players")) {
ItemStack item = event.getCurrentItem();
SkullMeta meta = (SkullMeta) item.getItemMeta();
Player flaggedPlayer = Bukkit.getPlayer(meta.getOwningPlayer().getName());
// Check if the clicked item is a player head
if (item.getType() == Material.PLAYER_HEAD && flaggedPlayers.get(flaggedPlayer) != null) {
}
event.setCancelled(true);
}
}
}
I have tried to replace .getTitle with .getName using the code bellow
if (inventory.getTitle().equals("Flagged Players")) {
But that didn't fix it and gave me the same error.
**I have also tried **
if (inventory.getType() == InventoryType.CHEST && inventory.getTitle().equals("Flagged Players")) {
But also gave me the same output.

The method getTitle was removed from Inventory.
You can access that value in your code using:
event.getView().getTitle()

Related

Minecraft 1.19.3 modding fabric .createExplosion with user as entity and explosion deals player still damage

I am currently learning how to program minecraft mods using fabric. I want to create an Item, which, when used on a creeper, let the player explode, which will also be shown in the deathmessage, that the player was the cause of the death(like when you kill yourself with TNT).
package net.lurchfresser.tutorialmod.item.custom;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.ZombieEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import org.w3c.dom.Text;
public class ConsumerItem extends Item {
public ConsumerItem(Settings settings){
super(settings);
}
#Override
public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
double x = user.getX();
double y = user.getY();
double z = user.getZ();
if(!user.world.isClient) {
if (entity instanceof ZombieEntity) {
entity.kill();
user.addStatusEffect(new StatusEffectInstance(StatusEffect.byRawId(19), 100));
} else if (entity instanceof CreeperEntity) {
entity.kill();
user.world.createExplosion(user, null,null, x + 0.5D, y + 0.5d, z + 0.5d,3F,false,World.ExplosionSourceType.MOB);
}
}
return super.useOnEntity(stack, user, entity, hand);
}
}
If I put the creeper in the first param of the createExplosion method. The Creeper will be the cause of the death. Also trying pass user.getName.toString in the second param(damageSource) didn't work out.

How to use a string from another method

I am trying to make a plugin where when a certain block in the GUI is clicked, a command is run. The problem is, I have to transfer a string from one method to another. I don't have very much java knowledge, so if someone could teach me how to do this, I would very much appreciate it.
P.S. The string I am trying to use is called custompermscommand.
Code:
package me.eliminiquated.yugengrant;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
public class Grant implements CommandExecutor, Listener {
#Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (command.getName().equals("grant")){
if (sender instanceof Player){
Player player = (Player) sender;
if (player.hasPermission("yugen.grant")){
if (args.length == 1){
player.sendMessage("Incorrect Usage! </grant (username)>");
}else if (args.length == 2){
Inventory gui = Bukkit.createInventory(player, 27, ChatColor.DARK_GREEN+"Grant Menu");
ItemStack custom = new ItemStack(Material.ORANGE_GLAZED_TERRACOTTA);
ItemStack playerranks = new ItemStack(Material.LAPIS_BLOCK);
ItemStack staffpositions = new ItemStack(Material.REDSTONE_BLOCK);
ItemMeta custommeta = custom.getItemMeta();
ItemMeta playerranksmeta = playerranks.getItemMeta();
ItemMeta staffpositionsmeta = staffpositions.getItemMeta();
custommeta.setDisplayName(ChatColor.GOLD+"Custom");
ArrayList<String> custom_lore = new ArrayList<>();
custom_lore.add(ChatColor.GRAY+""+ChatColor.ITALIC+"Coming soon");
custommeta.setLore(custom_lore);
custom.setItemMeta(custommeta);
playerranksmeta.setDisplayName(ChatColor.AQUA+"Player Ranks");
playerranks.setItemMeta(playerranksmeta);
staffpositionsmeta.setDisplayName(ChatColor.RED+"Staff Positions");
staffpositions.setItemMeta(staffpositionsmeta);
gui.setItem(10, custom);
gui.setItem(12, playerranks);
gui.setItem(14, staffpositions);
player.openInventory(gui);
String custompermscommand = "grantcustomperms "+args[0]+"";
}else{
player.sendMessage("Incorrect Usage! </grant (username)>");
}
}else{
player.sendMessage(ChatColor.RED+"You do not have permission to execute this command!");
}
}
}else{
System.out.println("You must be a player to execute this command");
}
return false;
}
#EventHandler
public void onInventoryClick(InventoryClickEvent event){
Player player = (Player) event.getWhoClicked();
if (event.getClickedInventory().getTitle().equalsIgnoreCase(ChatColor.DARK_GREEN+"Grant Menu")){
if (event.getCurrentItem().getType() == Material.ORANGE_GLAZED_TERRACOTTA){
Bukkit.dispatchCommand(player, custompermscommand);
}
}
}
}
For anyone that wants to do this themselves, this is the answer:
First, declare the variable as public outside of the methods:
Example:
public String command;
Next, edit the string inside of the method that you want to grab the string from:
Example:
command = args[0];
Finally, you are able to call this string in whatever method you want:
Example:
Bukkit.dispatchCommand(player, command);

Adding Potion Effect when Item is in hand Minecraft Forge 1.16.5

So Basically I have been searching the internet for a way to add potion effects while an item is being held. I have found many results but none really seem to be working. My main issue is that when I get to the adding potion effect it throws errors because I am trying to use a non-static to access an abstract. I tried the #Overide several times but it never seems to work. I still need to register in forge as that is how it updates but adding PlayerEntity does not work when I use #SubscribeEvent
package blitz.weapon.weaponmod;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.client.MainWindow;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerAbilities;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityDispatcher;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.event.world.NoteBlockEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.RegistryObject;
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;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.stream.Collectors;
// The value here should match an entry in the META-INF/mods.toml file
#Mod("weaponmod")
public class Weaponmod {
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, "weaponmod");
public static final RegistryObject<Item> RAINBOW_SWORD = ITEMS.register("rainbow_sword", () ->
new Item(new Item.Properties()
.group(ItemGroup.COMBAT)
.maxStackSize(1)
.maxDamage(13)
));
public Weaponmod() {
// 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);
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
}
#SubscribeEvent
public void onPlayerTick(TickEvent.PlayerTickEvent event) {
if (event.side.isServer() && event.phase == TickEvent.Phase.START) {
ItemStack stack = event.player.getHeldItemMainhand();
if (stack != null && stack.getItem() !=null) {
if (stack.getItem().equals("1 rainbow_sword")) {
return;
}
}
}
}
private void setup(final FMLCommonSetupEvent event) {
// some preinit code
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("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("weaponmod", "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");
}
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
#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");
}
}
}
That is my code for basically my whole mod, can anyone give me any pointers? (Sorry for any mistakes this is my first post)

Why does my config.yml file keep on outputting only zero? bukkit plugin

I have made a plugin that is supposed to track the amount of diamonds you have mined in Minecraft and save it to a config.yml file. But my code doesn't seem to be working and I cant figure out why?
I've already tried +1 in the setConfig args and now I've switched over to this and it still doesn't seem to be working. I also have diamonds predefined in my config.yml file.
package com.raidoxe.BlockPlugin;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin {
#Override
public void onEnable() {
getLogger().info("Sartu has been enabled :)");
PluginManager pm = getServer().getPluginManager();
SartuListener listener = new SartuListener(this);
pm.registerEvents(listener, this);
this.getConfig().options().copyDefaults(true);
this.saveConfig();
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (sender instanceof Player) {
String lowerCmd = cmd.getName().toLowerCase();
switch (lowerCmd) {
case "mydiamonds":
int a = this.getConfig().getInt("diamonds."+player.getUniqueId());
player.sendMessage(ChatColor.DARK_PURPLE+"You have mined "+ChatColor.RED+a+ChatColor.AQUA+" Diamonds");
return true;
}
}
return true;
}
------------Listener File-----------
package com.raidoxe.BlockPlugin;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.Plugin;
public class SartuListener implements Listener {
private Plugin plugin = Main.getPlugin(Main.class);
public SartuListener(Main plugin) {
}
#EventHandler
public void blockBreak(BlockBreakEvent event) {
Player player = (Player) event.getPlayer();
Block block = event.getBlock();
Material blockMaterial = block.getType();
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), a++);
plugin.saveConfig();
}
}
when the player does the command /mydiamonds it should print out, "you have mined (a) diamonds". But it always prints out zero, no matter how many diamonds you have mined.
Your code seems to be looking fine except one minor mistake. You say that you've tried +1 in the setConfig, so if this solution does not work for you it's probably a version thing
If a config getInt() returns 0 it can mean two things:
value does not exist (default is returned)
value is actually 0 in the config
Upon testing the value does exist in the config (due to saveConfig(), but is set to 0. So this lead me to the setting method.
The issue is the adding part. You do a++ inside the method, this will increment the number after the method, we want before, switch to ++a. See this post.
if(blockMaterial.equals(Material.DIAMOND_ORE)) {
Bukkit.broadcastMessage(ChatColor.WHITE+player.getDisplayName()+" found a "+ ChatColor.AQUA + ChatColor.BOLD+"Diamond!!!");
int a = plugin.getConfig().getInt("diamonds."+player.getUniqueId());
plugin.getConfig().set("diamonds."+player.getUniqueId(), ++a);
plugin.saveConfig();
}

How to fix error null spam on console? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I has an error if players use ShopGUI+ Plugin to buy or sell, it will error in consoler! Plugin ShopGUI+:
https://www.spigotmc.org/resources/shopgui.6515/ Error console: http://pastebin.com/Q1Hjssfm Please help me. Thanks!
class: package com.andrewyunt.townygui.listeners;
import com.andrewyunt.townygui.Menu;
import com.andrewyunt.townygui.TownyGUI;
import com.andrewyunt.townygui.utilities.CommandBuilder;
import com.gmail.filoghost.hiddenstring.HiddenStringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
import java.util.Set;
public class InventoryListener implements Listener {
#EventHandler
public void onInventoryClick(InventoryClickEvent sukien) {
ItemStack item = sukien.getCurrentItem();
Player player = (Player) sukien.getWhoClicked();
if(!(sukien.getInventory().getHolder() == null))
return;
if(item == null || !item.hasItemMeta())
return;
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if(!HiddenStringUtils.hasHiddenString(lore.get(0)))
return;
String action = HiddenStringUtils.extractHiddenString(lore.get(0));
boolean command;
command = action.startsWith("/");
if(!command)
new Menu(player, action);
else {
player.closeInventory();
Set<String> arguments;
try {
arguments = TownyGUI.plugin.commandConfig.getConfig().getConfigurationSection("commands."+ action + ".arguments").getKeys(false);
} catch(NullPointerException e) {
action = action.replace("/", "");
TownyGUI.plugin.server.dispatchCommand(player, action);
sukien.setCancelled(true);
return;
}
new CommandBuilder(arguments, action).beginConversation((CommandSender) player);
}
sukien.setCancelled(true);
} }
As far as the NullPointerException you provided goes, this is the line that causes the error:
String action = HiddenStringUtils.extractHiddenString(lore.get(0));
You should be able to check why it results in a NullPointerException.
I guess the event-error you get will be resolved as soon as you fix your code.
Also the first link you provided does not work without being logged in.

Categories

Resources