#help-development

1 messages · Page 838 of 1

ivory sleet
#

It should be fine, altho… if its from config

#

Maybe go with getList() instead of get()

silent slate
#

im trying getList right now

#

now its this

Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.toArray(java.util.function.IntFunction)" because the return value of "org.bukkit.configuration.file.YamlConfiguration.getList(String)" is null
at mondlw.laserserver.laserservermanager.util

#

its returning null because buildinventory was never saved

ivory sleet
#

Yeah

#

Prob nothing wrong with the type part, just that the value at said path is null lol

silent slate
#

but thats also what im checking for

#

if(buildInventory == null) {
player.getInventory().clear();
} else {
player.getInventory().setContents(buildInventory);
}

#

so i dont know why its erroring this. I already check if its null

glossy venture
#

?mappings

undone axleBOT
silent slate
#

for me?

ivory sleet
#

Na its not

silent slate
#

ok

ivory sleet
silent slate
#

should i sent you code from the whole file

#

and its setBuildMode im currently having the issue with

quiet ice
#

Sorry - internet went out (amateur sysadmin thought it was a good idea to touch the router):
Strange, in that case you could use new ItemStack[0] instead of ItemStack[]::new

silent slate
#

"Expression expected"

#

and it wants to create a Object[][] Itemstack;

quiet ice
#

Hm, is this some IJ analysis stuff?

silent slate
#

yes

quiet ice
#

I do mean to keep your .toArray() the same, just write new ItemStack[0] instead of ItemStack[]::new

silent slate
#

yes

#

ive done that

#
ItemStack[] buildInventory = (ItemStack[]) ((List) storage.getList(uuid + "." + world + "." + "buildinventory")).toArray(ItemStack[0]);

quiet ice
#

You forgot the new part

silent slate
#

im dump

#

im sorry

quiet ice
#

And in that case you can do ItemStack[] buildInventory = ((List) storage.getList(uuid + "." + world + "." + "buildinventory")).toArray(new ItemStack[0]);

silent slate
#

but dont i need to cast it to a ItemStack[]?

quiet ice
#

Although ordinarily even the code that I gave initially should work without a cast

quiet ice
silent slate
#

so its optional?

quiet ice
#

more useless than optional

silent slate
#

ok

#

so build set on works, but build set off returns this mess:

    at mondlw.laserserver.laserservermanager.utils.BuildUtils.setBuildM```
minor junco
#

it ain't mess, it just means your list is null (not contained) within the configuration at your given path

silent slate
#

and why is that bad?

minor junco
#

erm because it causes an exception, you cannot use / access object members when the object you're trying to access is null

silent slate
#

okay, so i need to initialize it with a empty inventory or what?

minor junco
#

you need to check against whether your list is null or not, before you call .toArray(...), and if it is null, you return an empty ItemStack for example

silent slate
#

so ```java
if(ItemStack[] buildInventory = (ItemStack[]) ((List) storage.getList(uuid + "." + world + "." + "buildinventory")) != null) {

ItemStack[] buildInventory = (ItemStack[]) ((List) storage.getList(uuid + "." + world + "." + "buildinventory")).toArray(new ItemStack[0]);
}```

minor junco
#

this code isn't valid

#

you cannot create locals (or variables in general) within if clauses

#

but in theory, yes

silent slate
#

yeah ik

#

im already doing this though=

if(buildInventory == null) {
player.getInventory().clear();
} else {
player.getInventory().setContents(buildInventory);
}

If the player doesnt have anything in the build/normal inventory it should just clear his current inventory

minor junco
#

I'd recommend reading through java basics, since this is quite a basic issue you have right now, not to be judgmental.

You first get your list: storage.getList(...)
then you call toArray on the list (which is a class member of that list).
But what happens when your list is null, as in not contained in the configuration?
A nullpointer is thrown (since you tried to operate upon a null object)

You need to check for null before invoking any members of the object (in this case the list)

#

so I'll write it down for you in your example:

#
List<?> inventory = storage.getList(...);
if (inventory != null && !inventory.isEmpty()) {
  player.getInventory().setContents(inventory.toArray(new ItemStack[0]));
} else {
  player.getInventory().clear();
}

^ I'd recommend cleaning up this code a bit, depending on what your surroundings are (this if-else clause isn't very cleanly implemented, but totally valid [... I hope so lmao])

silent slate
#

bool is wheater or not to enable or disable build mode

if(bool) {
            storage.set(uuid + "." + world + "." + "normalinventory", player.getInventory().getContents());

            List<?> buildList = storage.getList(uuid + "." + world + "." + "buildinventory");

            if(buildList != null && !buildList.isEmpty()) {

                player.getInventory().setContents(buildList.toArray(new ItemStack[0]));

            } else {
                player.getInventory().clear();
            }

            storage.set(uuid + "." + world + "." + "buildmode", true);
            
        } else {```
#

schnitzel?

scenic onyx
#

why is always false?

umbral ridge
silent slate
#

yes

hazy parrot
silent slate
#

buildmode is a boolean

minor junco
umbral ridge
silent slate
#

currently

tender shard
silent slate
#

a error i had earlier

scenic onyx
minor junco
#
Arena.arenas.stream()
  .filter((x) -> x.containsPlayer(player))
  .findFirst()
  .ifPresent((arena) -> {
    // TODO your code
  });
#

@scenic onyx

scenic onyx
#

tnx

tender shard
umbral ridge
minor junco
#

nws

silent slate
umbral ridge
undone axleBOT
silent slate
umbral ridge
#

I need to go @tender shard @hazy parrot will probably help uwu

molten cloak
#

is their any other plugins I need for decent holograms / holographic displays to work? I just come back for having a long break. and I didint remember and they arent working.

scenic onyx
#

is good code?

scenic onyx
glad prawn
#

fst snd

remote swallow
#

well the fact you access the colletion elsewhere its not really the best

minor junco
#

fst and snd are interesting choices for attribute names

#

@scenic onyx

quaint mantle
scenic onyx
quaint mantle
#

yeah you're not supposed to expose lists like that

scenic onyx
molten cloak
#

is their any other plugins I need for decent holograms / holographic displays to work? I just come back for having a long break. and I didint remember and they arent working.

proud badge
#

Why is it saying it might be null, im literally checking beforehand if its null?

proud badge
#

And no, I dont use any other plugins

kind hatch
#

The reviews for DecentHolograms all say they are waiting for 1.20.4 support. Sooooo

proud badge
#

@molten cloak iirc holographicdisplays doesnt work on anything above 1.20.1

molten cloak
molten cloak
kind hatch
#

You could try FancyHolograms, although it's on Hangar.

proud badge
#

No clue, my server's on 1.20.1

#

I dont update to minor versions, too much effort and plugins break

rotund ravine
proud badge
#

why

young knoll
#

Decent holograms is updated on GitHub

#

But I don’t think any pre built releases are out

molten cloak
silent slate
#

I'm still a bit clueless why its only working half the time

#

If i enable build mode it clears my inventory, but doesnt save it

silent slate
#

this should save it

#

storage.set(uuid + "." + world + "." + "buildinventory", player.getInventory().getContents());

#

but its not

#

wait

#

oh it makes sense

#

was 2nd guessing myself there for a second

molten cloak
#

okey

silent slate
#

mhh

proud badge
#

Should I use Lava or Lava_Bucket for bucketemptyevent>

#

?

rotund ravine
#

Both can be used depending on what ur doing

proud badge
#

emptying a bucket

#

event.getBlock();

#

specifically

young knoll
#

Well a bucket isn’t a block

rotund ravine
#

Block is probably also blockClicked

#

And not the lava

vocal cloud
#

The docs will tell you what's what lol

silent slate
#

So, ive implemented some error finding and ive got these results:

Server restart:

  • Have something in inventory
    -> Build on
    BOOL TRUE, NOT EMPTY BUILDLIST
  • Nothing in inventory
    -> Build off
    BOOL FALSE, EMPTY BUILDLIST
  • Nothing in inventory
    -> Build on
    BOOL TRUE, EMPTY BUILDLIST

After this i still dont have anything in my inventory, the items i had from the beginning werent saved..

Again these are the links to my code and my command

Code: https://paste.md-5.net/kixipeguve.cs
Command: https://paste.md-5.net/utaxubavon.sql

young knoll
#

I don’t see you save storage anywhere

vocal cloud
#

Oh my Lord. For starters please make a method to set/get so you don't have to copy paste your "key".

#

Or at least extract it into a variable

quaint mantle
#

when ur overlapping methods whats the order it goes

#

most complex to least complex or other way

vocal cloud
#

This code could probably be reduced and made easier to read.

vocal cloud
silent slate
# young knoll I don’t see you save `storage` anywhere

public static YamlConfiguration storage = YamlConfiguration.loadConfiguration(new File(plugin.getDataFolder(), "buildData.yml"));


    public static void saveBuildMode() throws IOException {
        storage.save(new File(plugin.getDataFolder(), "buildData.yml"));
    }```
silent slate
# silent slate ```java public static YamlConfiguration storage = YamlConfiguration.loadConfigu...

its not like nothing is saved, its just a empty inventory thats being saved..

  lobby:
    normalinventory:
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    buildinventory:
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    - null
    buildmode: false```
vocal cloud
#

Remember the good old days when databases existed sad

#

I think you might find your solution if you clean up the code first. The first step would be extract commonality. This includes the key you're using to save as it looks fairly static between sections.

#

Make a string call it key and then replace all instances of the uuid+. Stuff.

wet breach
minor junco
slender elbow
#

grtPlayerExact 😭

minor junco
#

easy fix, easy go

wet breach
#

yep

#

there is an isEmpty() method on inventory

#

probably wise it should be used 🙂

river oracle
quaint mantle
#

yo guys

#

anyone like my test

half arrow
#

whats the max characters for chest inventory name?

#

wanted to spread, {Inventory name} {Page} for example

young knoll
#

Don’t think there is a practical one

#

You will eventually go off the screen though

half arrow
#

Ok, will try fudge it

river oracle
#

I've exceeded it once, but you need to be excessive

young knoll
#

Hence the word practical smh

ivory sleet
#

You should learn JUnit a bit better

#

Like for instance to use @BeforeEach and @BeforeAll

#

And then the test also is… well… lets say I wouldve written it differently

quaint mantle
#

lmao

echo basalt
#

too much

#

blud goes through all that and still can't give variables more than 1 letter

minor junco
#

@ivory sleet what do you think

#

and ofc all perks that were available before and more are still accessible, also the layer system and stuff all works with ease

ivory sleet
#

I like the idea

#

But I hate the execution, the nested callback intention just asks for trouble almost lol

minor junco
#

it's just one way of doing it

ivory sleet
#

Callback hell is generally an anti pattern u wna avoid

#

Because of… well… I’m sure I dont need to even explain the reasons lol

minor junco
#

yeah I know (from react lol), but I don't think it's that awful in the example above, and as said you can totally go a different way of building the inventory, you don't have to use callbacks if you don't want them

#

the only reason i implemented them was to make it "easier" to create inventories yk

#

like in one go with chained method calls on the builder

ivory sleet
#

Yeah, I mean I’d advocate to have some more framework stuff around the population

#

Like InventoryPopulator.create().material(…).drawOutline(…);

Or sth yk

#

So I don’t have to reference storage 3 times in a single callback

#

I mean the way you do it is good on a base level because it allows expressiveness

#

But when you want to do basic things, it looks like your framework lacks the simplicity and straightforwardness regarding that

#

As the aforementioned example

minor junco
#

mhn yeah I agree

#

it's quite complex since there's a lot to it

#

so it's great for complex inventories, but for really basic ones it's still a lot of effort

minor junco
#

thanks for feedback, as always :3

ivory sleet
ivory sleet
sterile sapphire
#

Yesterday (a few hours ago) I was working on my plugin, everything looked perfect, no errors. The command I made did indeed exist. But when I did it, it wouldn’t load the inventory up like it was meant to

#

No error message

#

Looked fine, just wouldn’t do it

#

Do any of u know what might of happend?

minor junco
#

?nocode

undone axleBOT
#

It’s hard to answer a programming question without code
Oh no! You ran into a problem. But no worries, people are willing to help, but first they need to see your code. This is because otherwise, they would be providing help based on guesses instead of concrete knowledge. Whether it be a compile error, runtime error, or an unexpected output, I'm sure that if you were to provide code, you'd receive a quick solution.

sterile sapphire
#

Ahh I don’t currently have the code so I shall update you in the morning if that’s alright. Sorry for this!

#

Well, I have some of it but not all of it

#

( This is the bit I do have )


package me.tom.test.Listeners;

import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;

public class MenuListener implements Listener {

    @EventHandler
    public void onMenuClick(InventoryClickEvent e) {
        if (e.getView().getTitle().equalsIgnoreCase(ChatColor.GRAY + "Land Shop")) {
            // Check if the clicked slot is empty
            if (e.getCurrentItem() == null || e.getCurrentItem().getType().isAir()) {
                return;
            }

            // Cancel the event to prevent item movement
            e.setCancelled(true);
        }
    }
}

minor junco
ivory sleet
#

Yeah exactly

#

:)

minor junco
#

perfecto

#

you give me good ideas i like it

minor junco
ivory sleet
sterile sapphire
#

I got the right name and color

ivory sleet
#

I’ve failed so many times… god knows how many just

minor junco
minor junco
#

thing is sometimes, especially when you build like bigger libraries, you have such a focus on providing the ability to create something with ease on a large scale (the final solution to the problem), but you completely forget about other applications

sterile sapphire
#

It did work untill the // cannsle event to prevent item movement was unreachable. So I fixed it and it broke

minor junco
#

in this instance it was smaller inventories haha

ivory sleet
#

yea lol

young knoll
#

Failure? What do you mean, all my code works first time

minor junco
#

haha

sterile sapphire
#

U think I’ve just forgot to do somthing?

#

Maybe, I’ll check tmrw again

echo basalt
#

I overengineer stuff so much that writing a simple feature from scratch is faster than copying all the libs, initializing managers and hooking into it

young knoll
#

It’s not my code that’s wrong

sterile sapphire
young knoll
#

It’s the jvm that’s wrong

drifting bear
#

I'm trying to code a simple plugin for my 1.20.2 factions server but it's giving me this error

The package org.bukkit is not accessible

these are all the lines which have org.bukkit

import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.entity.FallingBlock;
import org.bukkit.plugin.java.JavaPlugin;

not really sure if this is the right place to ask but figured I might aswell

echo basalt
#

You're not importing the jar correctly

drifting bear
#

I'm using eclipse*

echo basalt
#

most likely

#

?bootstrap

undone axleBOT
#

Bootstrap Jar
The main spigot-1.18.jar is now a bootstrap jar which contains all libraries. You cannot directly depend on this jar. You should depend on Spigot/Spigot-API/target/spigot-api-1.18-R0.1-SNAPSHOT-shaded.jar, or the entire contents of the bundler directory from your server, or use a dependency manager such as Maven or Gradle to handle this automatically.

Please read the release notes for further information: https://www.spigotmc.org/threads/9-years-of-spigotmc-spigot-bungeecord-1-18-1-18-1-release.534760/#post-4305163

drifting bear
#

I'll check that, ty

drifting bear
echo basalt
#

Use maven or gradle

river oracle
#

you can use the java system, but its just harder imho. Just go with maven

#

its in my opinion, by far easier than gradle and gets the job done especially if you're not doing anything crazy

drifting bear
#

im new to this and dont have much of an idea what im supposed to do so I think that would be the best option

river oracle
sterile sapphire
echo basalt
#

I wouldn't say one's better than the other

#

both work

sterile sapphire
#

Alr 👍

sterile sapphire
#

And the rest of the code (I’ll send later today when I’m on me pc) has 0 errors but a few orange warning

quaint mantle
#

Guys is it OK to throw exception

#

like fetchStatistics(UUID) throws Exception;

#

something like that

tender shard
#

declare a specific exception

wet breach
# sterile sapphire Am I right in understanding maven is better?

maven is easier to work with and on top of being easy to work with its very versatile. Gradle can be versatile too but it requires more work and can be more difficult to work with. Gradle's biggest advantage is faster compiling and this is because it is by default designed to use all resources available but you will only see this with super huge projects which 99% of all plugins will not come anywhere close to be considering a super large project. Maven by default is designed to be conservative with resources and is the primary reason most see it being slow, however you can just give it more resources to help speed it up.

#

so in all, its really down to preference for most things

brazen pebble
#

How do other servers develop scoreboard sidebar with player information?

tender shard
brazen pebble
#

ex) player's money , Online Player..

#

I've tried to make it, but I keep getting errors

#

-- test scoredboard --
Money:0 2
Money:1000 2
Online Player:2 1
Online Player:1 1

#

like this

tender shard
quaint mantle
tender shard
#

I can only see them throwing Exceptions in internal stuff

#

I'd always declare what it really throws though, fetchStatistic e.g. might throw IOException and NoSuchElementException for example

quaint mantle
#

Yeah well

#

I currently do both rn lol

#

NoSuch... and IOExc

#

I'm just p sure gson has a unique exception for everything

#

should I just wrap it with an IOException

#

like

try {
...
} catch (Exception e) {throw new IOEx(e)}

astral pilot
#

does BukkitRunnable#runTaskLater blocks the thread?

astral pilot
#

wait if it doesn't block the thread

#

why do we have Bukkit#runTaskLaterAsynchronously then

#

and wat i mean by thread is the plugin thread

#

cuz i wanna know if my code will make different tasks or will it wait for the task to run before creating one

public class EntitySpawnerUtils {
    public void startSpawnerLogic() {
        for (CustomEntity mob : getLoadedMobs().values()) {
            if (mob.getSpawnLocation().getProperty().isEnabled()) {
                long interval1 = mob.getSpawnLocation().getProperty().getMinInterval();
                long interval2 = mob.getSpawnLocation().getProperty().getMaxInterval();
                long higherInterval = Math.max(interval1, interval2);
                long lowerInterval = Math.min(interval1, interval2);

                long randomInterval = randomizer(higherInterval, lowerInterval);

                EntitySpawnerTask mobSpawnerTask = new EntitySpawnerTask(mob);
                // Not sure if this will block the thread and prevent the for loop from running correctly
                mobSpawnerTask.runTaskLater(getPlugin(), randomInterval);
            }
        }
    }
}
quaint mantle
#

What plugin thread

astral pilot
#

my plugin thread

quaint mantle
#

What

astral pilot
#

each plugin has its own thread provided right?

quaint mantle
#

No

astral pilot
#

huh

#

so if 1 plugin suffers a deadlock

#

the server gets deadlocked?

quaint mantle
#

Whole server dies

#

Normal runnables work with ticks, so that no thread is used

astral pilot
#

cuz i wanna spawn multiple bukkit runnables

quaint mantle
#

No

#

It wont block

astral pilot
#

ok i see

#

so im good

#

thanks

distant wave
#

would this be a good approach to spawn a magma cube instead of an arrow with same velocity?

faint aspen
#

did you test it?

waxen plinth
#

it might not be a good idea to schedule that many tasks, you might be better off sorting it into buckets for each random amount and then schedule one task for each bucket, processing all items at once in each tick

#

but probably not a major performance concern at small scale

distant wave
astral pilot
#

as each mob has its own spawner

faint aspen
distant wave
faint aspen
#

does it die bc of damage? or just despawns?

distant wave
#

doesnt do any animation

#

seems like it just spawns for like 0.1 sec

quaint mantle
#

Velocity might be too high

#

Also check yo difficulty

distant wave
#

oh my gooood

faint aspen
#

xD

quaint mantle
distant wave
#

testing

#

one sec

#

it did!

#

thanks

quaint mantle
#

Breh

drifting bear
#

i just spent like a entire hour trying to get maven done

#

no worky

#

what am i supposed to do

faint aspen
#

whats not working ? any error message. maybe send us your .pom

drifting bear
#

i think I might want to just uninstall it and try again

distant wave
drifting bear
#

alright I deleted it and I'll just try again

faint aspen
#

nah I think you have to use a schedueler which checks if two entities are too close to each other

drifting bear
#

is there a good guide on how to properly install maven?

distant wave
drifting bear
faint aspen
#

intellij or eclipse

#

yeah

distant wave
#

💀

faint aspen
#

in maven this would be a cake walk xD

#

intellij*

distant wave
#

indeed

drifting bear
#

oh bruh ill just install that instead

#

im a beginner

distant wave
#

why you do mc plugins if you dont know java

faint aspen
#

yeah thats fine, trust me no one, NO ONE, have I every seen anyone use eclipse at work for java ^^

drifting bear
#

trying to figure out what the hell im doing

distant wave
#

wait

#

you want to create plugins right?

drifting bear
#

mhm

#

I want one that can add sand stacking for factions

#

i dont wanna pay like 20 bucks for a cannon jar

astral pilot
#

when does LivingEntity#getAttribute return null

faint aspen
#

I think when a given attribute does not exists for the entity

#

e.g. animal and attack damage attribute

drifting bear
#

.java and .bin?

#

ah no image perms

astral pilot
faint aspen
astral pilot
#

of mobs that doesn't have those

faint aspen
drifting bear
distant wave
#

does anyone know what exactly EntityChangeBlockEvent do

drifting bear
#

I'm installing intellji and it has "update path variable" and "create associations"

#

should i do a .java association and add a bin folder to the path

#

@faint aspen

distant wave
#

You can ig

drifting bear
#

any reason to?

distant wave
#

Not realyl important tho

drifting bear
#

ah alright

faint aspen
#

do either

drifting bear
#

I'm installing it, what do I do to install maven now

distant wave
#

Nothing

#

Just create a maven project

drifting bear
#

perfect

quaint mantle
#

For beginners, I would recommend the "Minecraft Development" plugin in intellij

drifting bear
#

ty

#

intellji looks so much better compared to eclipse

ocean hollow
#

what's the best way to send an action bar to the player every tick?

#

create one scheduler for everyone and execute code for everyone? or does everyone have their own?

#

Or maybe it’s possible without them?

bleak stream
#

I have a (probably very simple) question.
I'm learning how to use inheritance properly, and I'm trying to make some repeatable code for a custom YAML file.
I have to have 4 default methods that need to be implemented when I extend this class with the super class. How would I go about doing that?

ocean hollow
#

well it turns out like this

eternal oxide
#

I can't see how there is anything you would need to update in the action bar every tick

#

unless it's some colour animation of text or something

sterile sapphire
#
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class Menu extends CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;
        Inventory inventory = Bukkit.createInventory(player, 9, ChatColor.GRAY + "Land Shop");
        ItemStack item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        inventory.addItem(item);

        ItemStack Nothing = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        ItemMeta NothingMeta = Nothing.getItemMeta();
        NothingMeta.setDisplayName(" ");

        NothingMeta.addEnchant(Enchantment.DURABILITY, 1, true);

        Nothing.setItemMeta(NothingMeta);

// rest of the slots
        inventory.setItem(1, Nothing);
        inventory.setItem(2, Nothing);
        inventory.setItem(3, Nothing);
        inventory.setItem(4, Nothing);
        inventory.setItem(5, Nothing);
        inventory.setItem(6, Nothing);
        inventory.setItem(7, Nothing);
        inventory.setItem(8, Nothing);
        return false;
    }
} ```
#
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;

public class MenuListener implements Listener {

    @EventHandler
    public void onMenuClick(InventoryClickEvent e) {
        if (e.getView().getTitle().equalsIgnoreCase(ChatColor.GRAY + "Land Shop")) {
            // Check if the clicked slot is empty
            if (e.getCurrentItem() == null || e.getCurrentItem().getType().isAir()) {
                return;
            }

            // Cancel the event to prevent item movement
            e.setCancelled(true);
        }
    }
} ```
#

this is my plugin i made, there is no error message in IntelliJ or for the Minecraft server console and the rest of the plugins runs fine but it doesn't work.

#

( the 2 spaces before the first imput on both of those peaces of code doeant atualy have a space infront of it, idk y it did that when i copy and pasted it

sterile sapphire
#

The menu

faint aspen
#

Did you register your listener

#

did you register the command

sterile sapphire
#

I registered the command

faint aspen
#

return true instead of false in the end of the command

sterile sapphire
faint aspen
#

If it does not work provide the code which shows how you registered your cmd and maybe your plugin.yml

hazy parrot
#

Am I blind or you never actually open the inventory

valid basin
#

is this good antiafk detection?

        Player player = Bukkit.getPlayer(profile.getUuid());


        boolean moving = player.getVelocity().lengthSquared() > 0.0001; // Adjust the threshold as needed


        if (!moving) {
            Location currentLocation = player.getLocation();
            Location lastLocation = playerLocations.get(player.getUniqueId());


            return lastLocation != null && !hasSignificantlyMoved(lastLocation, currentLocation);
        }

        return false;
    }

    private boolean hasSignificantlyMoved(Location loc1, Location loc2) {

        return !loc1.getWorld().equals(loc2.getWorld()) || loc1.distanceSquared(loc2) > 0.25;
    }```
#

ik it's probably flawed, it's basic integration

wet breach
#

you could just use the move event

valid basin
#

because tbh idk how to exactly make it work so it detects if player moves without moving his mouse (cursor)

wet breach
#

also it doesn't account for someone using an inventory

valid basin
#

without using packets or something

wet breach
#

probably best that you do it based on time

valid basin
wet breach
#

explain?

valid basin
#

i mean it's very bad to be used often, it can cause high cpu usage in my experience

hazy parrot
wet breach
valid basin
#

yk afk bots

wet breach
#

you could do it based on time, and not sure why an afk bot is an issue

#

if the main issue is because of monster spawning then you should just detect someone near a spawner for long period of time and just stop spawning mobs

sterile sapphire
# hazy parrot <@984915836957499452>
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class Menu extends CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;
        Inventory inventory = Bukkit.createInventory(player, 9, ChatColor.GRAY + "Land Shop");
        ItemStack item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        inventory.addItem(item);

        ItemStack Nothing = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        ItemMeta NothingMeta = Nothing.getItemMeta();
        NothingMeta.setDisplayName(" ");

        NothingMeta.addEnchant(Enchantment.DURABILITY, 1, true);

        Nothing.setItemMeta(NothingMeta);

// rest of the slots
        inventory.setItem(1, Nothing);
        inventory.setItem(2, Nothing);
        inventory.setItem(3, Nothing);
        inventory.setItem(4, Nothing);
        inventory.setItem(5, Nothing);
        inventory.setItem(6, Nothing);
        inventory.setItem(7, Nothing);
        inventory.setItem(8, Nothing);
        
        player.openInventory(inventory);
        
        return true;
    }
}```
wet breach
#

the more people connected to your server the more likely people are to join it, but if you are just going to combat them seems you don't want players

sterile sapphire
#

there we go

wet breach
#

I never had an issue with afk'ing players though, even with mob farms if they were allowed to begin with

#

because it doesn't matter if they are there or not since anyone can leave their client open and connected, don't even need a bot for it

proud badge
#

Should I use .equals or just == to compare strings? (player usernames)

wet breach
#

also, not all bots are used for the purpose of afking at a farm, some of them are for just so they could chat

#

which I see harmless unless they are spamming, which is easy to deal with itself

wet breach
proud badge
#

ok epic thx

sterile sapphire
#

how do u put someones head in a inv, so no matter who opens it, it will always show your head

proud badge
#

Get the item meta from the item, then get the skull meta from the itemmeta, and set the owner
LIke this

SkullMeta skullMeta = (SkullMeta) bum.getItemMeta();
skullMeta.setOwningPlayer(**insert offline player object here, probably of the command executor**);
bum.setItemMeta(skullMeta);```
#

online player object might work too, just I dont use it

shadow night
#

OfflinePlayer extends Player soo

#

Or opposite

#

Way

#

Yeah I think it was P extends OP

sterile sapphire
#

If there offline I don’t need it

#

Because the inventory is gonna be diffrent for everyone

proud badge
#

well replace with online player then

wet breach
#

player extends offlineplayer

shadow night
#

Yeah, I said so

#

A bit below

wet breach
#

they should use offlineplayer object though

#

to avoid any errors

shadow night
wet breach
#

from offlineplayer they can check if they are online

shadow night
#

Makes sense

wet breach
#

if they are not online they can stop

orchid trout
#

aaaaaaa

#

help clearn urp

lost matrix
orchid trout
#

yeah

#

what aoobout it

lost matrix
orchid trout
#

yeah

#

thats why i have the remove cooldown logic async and not async

candid galleon
#

what's tempProfile?

orchid trout
#

idk

#

ok so i rename

#

asyncProfile

lost matrix
orchid trout
#

yeah i forgot to change it

#

in the async logic

steel swan
#

?paste

undone axleBOT
lost matrix
orchid trout
steel swan
orchid trout
#

but like is this the best way to go on about it

lost matrix
orchid trout
#

ok thanks

lost matrix
scenic onyx
steel swan
lost matrix
steel swan
lost matrix
steel swan
#

the map is just a big plain biome with a few volcanos for the moment

half arrow
#

I had a similar issue, how olds your map?

#

What’s version was it built on

steel swan
#

new

#

1.20.2

half arrow
#

Oh

lost matrix
#

Was it built with mods?

steel swan
#

made using World Painter tho

lost matrix
lost matrix
steel swan
umbral ridge
#

hey

#

why is inventoryclickevent cancelled even though I dont cancel it anywhere

#

i tried setting it to false but regardless its still cancelled

#

i only have 1 plugin installed

lost matrix
# umbral ridge

Another listener can still cancel the event after yours.
Did you debug your code and made sure your if condition is going through?

umbral ridge
#

another listener?

lost matrix
umbral ridge
#

I do return; if item material names arent the same

#

which they're not

#

event shouldnt be cancelled

#

I dont cancel it

#

I just return

#

return should exit out of function right?

lost matrix
#

Well, then another listener method cancels it

#

Add a monitor listener to make sure

umbral ridge
#

I see it now yeah I'll change it

#

I basically have a blocks gui and homes gui, for each i have a separate click listener

wet breach
# umbral ridge

why do you bother setting it uncancelled if you never bother to check if it was cancelled to begin with?

half arrow
#

attempting to debug by the looks of it

wet breach
#

also you could just set in the annotation to ignore cancelled as well

umbral ridge
lost matrix
umbral ridge
#

as well as items, contents blaaablabla

half arrow
#

Just do it under one listener?

#

Having a ton in one plugin is messy

umbral ridge
half arrow
#

lol

lost matrix
umbral ridge
#

where inventories are somewhat the same, I do one listener, but in this case I do a separate listener just for the sake of understanding

wet breach
#

this is where abstraction helps

umbral ridge
lost matrix
#

Here is the Listener for the GUI guide i wrote.
Its one listener that works with an infinite amount of inventories.

umbral ridge
#

i'm talking about an actual InventoryClickEvent I needed for each gui

lost matrix
lost matrix
umbral ridge
#

interesting

#

what do handleClick and other handle methods do

lost matrix
scenic onyx
#

the correct?

umbral ridge
#

thanks for the help though

lost matrix
umbral ridge
#

I'll consider using abstraction in the future

scenic onyx
lost matrix
silent slate
wet breach
#

inventory has an isEmpty() method

#

check if its empty, if it is don't save it

silent slate
#

yeah ik, but couldnt i just put null in the file like this:

inventory: null
Instead of
Inventory:

  • null
  • null
    ...
lost matrix
#

Myeah, and make sure that you save a single null value to erase the previous inventory.

wet breach
lost matrix
#

^ Which is nice 🙂

silent slate
#

so im doing everything rihgt?

#
if(player.getInventory().isEmpty()) {
                storage.set(uuid + "." + world + "." + "buildinventory", null);
            } else {
                storage.set(uuid + "." + world + "." + "buildinventory", player.getInventory().getContents());
            }```

So every time when i check wheater there is an entry or when i change an entry im putting this
agile hollow
#

Entity damager = (Entity) p.getLastDamageCause().getEntity();
why it gave null?

lost matrix
agile hollow
lost matrix
#

A bit more information would be nice 🙂

silent slate
#

if its null then there is no damager, cant there be other damage like fall damage etc..

agile hollow
#

i want to check when a player get hitted by another player do something

#
    public boolean ruba(EntityDamageEvent e) {
        Entity p = e.getEntity();
        Entity damager = (Entity) p.().getEntity();
        if (damager instanceof Player) {
            Player whod = (Player) damager;
            if (whod.getItemInHand().getType() == Material.DIAMOND_SWORD) {
                if (p instanceof Player) {
                    Player player = (Player) p;
                    Inventory inventory = player.getInventory();
                    Material material = Material.BOOK;
                    if (inventory.contains(material)) {
                        p.sendMessage("TI hanno fottuto il portafoglio!");
                        damager.sendMessage("Ti sei Fottuto un portafoglio!");
                    }
                }
            }
        }
            return false;
    }
}```
lost matrix
silent slate
#

When triggering this

if(player.getInventory().isEmpty()) {
                storage.set(uuid + "." + world + "." + "normalinventory", null);
                Bukkit.broadcastMessage("bool true, set norm inv to null");
            } else {
                storage.set(uuid + "." + world + "." + "normalinventory", player.getInventory().getContents());
                Bukkit.broadcastMessage("bool true, set norm inv to playerinv");
            }```

It says set buildinv to playerinv so it should save it, when looking into the file i can confirm: It saved the items. But this:

```java
List<?> normalList = storage.getList(uuid + "." + world + "." + "normalinventory");```

doesnt get these items it says the normalList is null. Why the frick is that
late sonnet
silent slate
#

should i print the normalinventory after saving it?

late sonnet
silent slate
#

well i tried this:

storage.set(uuid + "." + world + "." + "buildinventory", player.getInventory().getContents());
                Bukkit.getServer().getLogger().info(storage.getList(uuid + "." + world + "." + "buildinventory").toString());
                Bukkit.broadcastMessage("bool true, set build inv to playerinv");```

But now its getting an error when executing the command

```java

Caused by: java.lang.NullPointerException: Cannot invoke "java.util.List.toString()" because the return value of "org.bukkit.configuration.file.YamlConfiguration.getList(String)" is null
    at mondlw.laserserver.laserservermanager.utils.BuildUtils.setBuildMode(Bu```

So i see its not being saved correctly
#

because its returning null

lost matrix
# silent slate because its returning null

Yeah because its not saved at all. Meaning the inventory was empty, resulting in the config entry being removed and the config returning null when asked for that value.

silent slate
lost matrix
silent slate
#

and its actually being saved right here

- ==: org.bukkit.inventory.ItemStack
  v: 3105
  type: BIRCH_STAIRS
  amount: 64
#

well there isnt much to debug

#

its this

if(!storage.contains(uuid + "." + world)) {
Checking wheather there is an entry

if(player.getInventory().isEmpty()) {
Checking if the inventory is null and deciding wheather to put inventory or null in file

if(buildList != null && !buildList.isEmpty()) {

checking weather its null or empty in file

tropic saddle
#

?mappings

undone axleBOT
clever lantern
#

how to add effects to everyone in certain radius from a player

#

ok i found getNearbyEntitiesByType

half arrow
#

anyone here use mainly a sql or mongo db but have a failsafe that goes flatfile if connections fail?

chrome beacon
#

You can use SQLite as failsafe

half arrow
#

True

#

then periodically check if the main connections back up and import sqlite data?

#

or do you just close the pl down and save to sqlite?

ivory sleet
#

You can prob save the data async as its being mutated and changed

#

That way u dont need to buffer a synchronization of the data

half arrow
#

Ok thank you, will take a look

quaint mantle
#

I made a damagetag by boarding TextDisplay on the entity, but when I tested it on mythic mob,TextDisplay was dismounted.

#

Cancelling EntityDismountEvent set to EventPriority=MONITOR does not work as desired.

#

how can i resolve this?

brisk estuary
#

Is there any way I can get the default suspicious stews that are already in minecraft or do I have to create them myself using SuspiciousStewMeta?

shadow night
#

what is the spigot alternative for the forge Start/Stop Tracking event?

tender shard
eternal night
#

nah

tender shard
#

what is the forge start stop tracking event?

eternal night
#

paper events iirc

tender shard
#

I mean, what does it do?

eternal night
#

Actually no i lied

#

no events under that name

#

there is track and untrack events

#

called when the server starts the player on tracking an entity in the world (e.g. initial packet sync and then updates via packets)

tender shard
#

ah

eternal night
#

More or less useful given you cannot do much without internals

#

so meh

agile hollow
#

how can i use / check a public string in a Listener?

#
        String dir = "";
        float y = playerSelf.getLocation().getYaw();
        if( y < 0 ){y += 360;}
        y %= 360;
        int i = (int)((y+8) / 22.5);
        if(i == 0){dir = "west";}
        else if(i == 1){dir = "north";}
        else if(i == 2){dir = "east";}
        else if(i == 3){dir = "south";}
        else {dir = "west";}
        return dir;
    }``` 
i make that Public String for get the direction of where the player is looking and i want apply it on a `BlockPlaceEvent` Event how can i do that?
rotund ravine
#

?learnjava

undone axleBOT
steel swan
#

Just a question, how do i return the item in the offhand of a player?

silent slate
#

player.getInventory().getOffHand or something like that

#

player.getInventory().getItemInOffHand()

steel swan
#

ooog thx

#

i tried doing e.getPlayer().getInventory().getItemInOffHand().setType(Material.BUCKET); but it doesnt seem to work

remote swallow
#

it probably returns a mutable copy

#

set the slot

#

player.getInventory().setItem(45, new ItemStack(Material.BUCKET))

steel swan
#

or simply e.getPlayer().getInventory().setItemInOffHand(new ItemStack(Material.BUCKET));?

#

can it work?

ivory sleet
#

Yeah

#

That works assumably

steel swan
#

Yep i works !

#

thank you !

sterile sapphire
sterile sapphire
lost matrix
#

Yes, it would set the ItemStack in that slot to a bucket

young knoll
#

Probaby better to use the fixed setItemInOffhand

lost matrix
#

Def

young knoll
#

In case the slot number changes one day :p

ivory sleet
#

Ye magic values evil

clever lantern
#

can i cancel chorus fruit teleport if it has specified pdc tag?

eternal night
#

PlayerItemConsumeEvent should do the trick

quaint mantle
scenic onyx
#

But if the player is in another world, does it leave them in the "world" or does it leave them in the world the player is in?

#

??

lost matrix
scenic onyx
#

i dont use it

#

i only want understand if it drop them in the "world" or does it drop them in the world the player is in?

lost matrix
scenic onyx
lost matrix
#

It will drop the item in the "world" at the x, y, z of the location.

lost matrix
scenic onyx
halcyon hemlock
#

who wanna make a server framework in rust

lost matrix
#

Isnt there already one with a Bevy backbone?

quaint mantle
#

is it okay to catch (Exception) ?

lost matrix
quaint mantle
#

im working with a database that's abstracted

#

and I want every exception to be informed for the api users

#

I was thinking abt just making a bunch of custom exceptions

#

like

#

DatabaseException
DatabaseArgumentException stuff like that

#

or IO

lost matrix
#

Exceptions will be passed through the call stack. Idk why you would want to catch them early.

quaint mantle
#

well i dont want to catch them later as of now

lost matrix
#

Hm?

quaint mantle
#

like

#

this forexample

#
    @Override
    public void update(@NotNull Class<? extends T> configClass) throws IOException {
        Preconditions.checkState(this.configMap.containsKey(configClass), "configClass is not registered.");

        Path pathToConfig = this.configFolderPath.resolve(this.getConfigClassName(configClass) + ".json");
        T updatedConfig = this.gson.fromJson(Files.readString(pathToConfig), configClass);
        this.configMap.put(configClass, updatedConfig);
    }
#

there's a ton of exceptions that can be thrown and they dont all fall under IOException\

lost matrix
#

Which of your methods here throws an IOException?

#

Ah Files.readString

quaint mantle
#

InvalidPathException
JsonParseException

#

wtf

#

what's an Error lol

#

never seen that before

dry hazel
#

an Error is usually an unrecoverable error that shouldn't be caught

shadow night
#

I catch out of mem errors all of the time

#

Annoying crap to deal with

lost matrix
#

I mean you basically pass through every exception that you want the caller to handle.
But letting him handle a very generalized exception is very discouraged.

lost matrix
quaint mantle
#

uh

#

so what if

#

hm

#

what if I make my custom exceptions

#

instead

#

then in the docs for the interface, I just justify what exceptions the method can only throw

shadow night
slender elbow
shadow night
slender elbow
#

not all OOMEs are the same tho

shadow night
#

Hmm, true

dry hazel
#

no more metaspace

lost matrix
quaint mantle
#

so should I make my own exceptions that wrap all the impl exceptions in my case

lost matrix
dry hazel
mellow edge
#

is it possible to achieve custom ender dragon movement via EnderDragon#setPassanger (to avoid NMS)

quaint mantle
#

like log it?

lost matrix
# quaint mantle what does that mean

Every exception that needs to be handled on compile time is simply appended to the method

public void someMethod() throws ExceptionA, ExceptionB {

}

Exceptions that dont need to be handled are just left alone.

sterile sapphire
#

Or am I just confused

young knoll
#

You don't need to be holding it

sterile sapphire
young knoll
#

It knows what slot the offhand is

#

Internally

sterile sapphire
quaint mantle
#

i am confused because of the confusion

wet breach
#

main hand and off hand refer to inventory slots since they don't disappear when equipped

#

the api just makes it easier to refer to common slots that are used

sterile sapphire
#

What I’m confused about it if you use of hand to change the bucket won’t it change what in the hand not the inv and if it did change the inv you don’t tell it what slot to use

wet breach
#

items in offhand don't disappear out of the inventory when equipped

#

same goes with main hand

sterile sapphire
#

Yea

#

But I mean not your inv but a custom inv like In a chest

wet breach
#

since they are in the inventory, that means if you change it in the inventory, which off hand and main hand refer to, it will change

quaint mantle
#

PlayerInventory and Inventory is different

Chest Inventory does not have the function "setItemInOffhand" etc

quaint mantle
#

these are the function that are added in PlayerInventory

#

the methods not included in the list are from "Inventory"

sterile sapphire
#

Alr 👍

#

Also this would still work right? Coz I removed a bit but not at my pc to see

#
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class Menu extends CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;
        Inventory inventory = Bukkit.createInventory(player, 9, ChatColor.GRAY + "Land Shop");

        ItemStack Nothing = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        ItemMeta NothingMeta = Nothing.getItemMeta();
        NothingMeta.setDisplayName(" ");

        NothingMeta.addEnchant(Enchantment.DURABILITY, 1, true);

        Nothing.setItemMeta(NothingMeta);

// rest of the slots
        inventory.setItem(1, Nothing);
        inventory.setItem(2, Nothing);
        inventory.setItem(3, Nothing);
        inventory.setItem(4, Nothing);
        inventory.setItem(5, Nothing);
        inventory.setItem(6, Nothing);
        inventory.setItem(7, Nothing);
        inventory.setItem(8, Nothing);
        
        player.openInventory(inventory);
        
        return true;
    }
}```
quaint mantle
#

why are you filling only 8 slots and not all 9

#

also you didnt check if the sender is a playedr

#

it could be console

sterile sapphire
#

Ig

sterile sapphire
#
        ItemStack item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE, 1);
        inventory.addItem(item);

        ```
lost matrix
sterile sapphire
#

Still learning and getting my head around some things

quaint mantle
lost matrix
quaint mantle
#

its still spoonfeeding

sterile sapphire
#

I won’t use it anyway. I don’t understand it

#

It’s Alr

quaint mantle
#

...?

#

?learnjava

undone axleBOT
sterile sapphire
#

Ik I am learning

quaint mantle
#

how will you learn if you dont take on a challenge?

sterile sapphire
#

But trying to also not over do myself, I’m only just learning

#

When I get used to it I’ll do harder stuff

lost matrix
# quaint mantle its still spoonfeeding

Showing a concept without implementation is not spoon feeding.
If i explain someone what strong encapsulation is, im introducing abstract information.
Same goes for extracting functionality from a codeblock into a method body. Its an abstract concept.
There is no actual logic being fed.

Or in shot: I disagree

sterile sapphire
#

I respect the help 😅

wet breach
split dagger
#

Hi,
I want to write two independent plugins.
The first plugin will handle player login and registration, while the
second plugin will record player statistics.

Both plugins will use JDBC to save data to a MySQL database.
Should each plugin contain its own JDBC dependency and database logic, or should I create a separate database plugin to be used by both plugins?
Can someone explain the best practice and how to do it?

wet breach
#

why not make it just one plugin?

minor junco
#

Or you just put everything into one plugin

teal pumice
wet breach
#

given the context anyways

minor junco
split dagger
teal pumice
lost matrix
minor junco
#

If you are okay with multiple connections, use a monorepo type style (basically what @lost matrix described)

wet breach
split dagger
minor junco
#

(or just use an ORM lol)

wet breach
#

you would make the api in such a way you can just fetch what you are wanting, the db plugin then takes that and creates the necessary query

#

you can make some methods where its some default queries, but if you intend to query multiple DB's, then it could get a bit more complex

umbral ridge
#

hey, countdown() still gets called even if its not 0 right? if statement is ran regardless of the result?

minor junco
#

If your target audience for your Plugins is a large server network, I'd recommend using an ORM instead of raw SQL queries

wet breach
#

because you have to switch between DB's and in the context of existing connections the DB switch persists until you switch it again

minor junco
#

we need to know the conditions of the countdown call

split dagger
floral kindle
#

Is this function still working? Bukkit.getUnsafe().loadAdvancement();

spare prism
#

?paste

undone axleBOT
spare prism
quaint mantle
#

Hi , how to close permission for /plugins on my plugin ? i just need a name of this permission

spare prism
#

it doesnt provide any downloads, discord bugged

#

i can send the exception tho

faint aspen
#

ahh I see yeah

#

you trying to cast to a different Logger

spare prism
#

at least my IDE says that

spare prism
#

and it does pretty much the same thing that i do

#

i saw that

#

even this doesn't help:
org.apache.logging.log4j.core.Logger log = (org.apache.logging.log4j.core.Logger) LogManager.getRootLogger();

#

same exception

tender shard
#

you have shaded Log4J or something and relocated it

tender shard
#

in that case you also have to cast it to the shaded version

#

cast it to shaded.org.apache.logging.log4j.core.Logger

sterile sapphire
#

Why when ever I package my plugin it makes a shadow . Jar file?

spare prism
#

i cant

#

compilation error

tender shard
#

why do you shade log4j in the first place?

spare prism
#

cause otherwise my plugin conflicts with other plugins that are using log4j

#

ClassNotFoundException

tender shard
#

because you're relocating it

#

just set the scope to provided and use the logger provided by spigot

spare prism
#

it will not find a class

tender shard
#
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.19.0</version> <!-- This is the version Spigot 1.20.1 uses -->
  <scope>provided</scope>
</dependency>
spare prism
#

because of another plugin

#

that is using log4j

#

idk why

tender shard
shadow night
#

I asked here before but I forgot to check and lost it now, is there some alternative to the StartTrackingEvent from forge in spigot?

remote swallow
#

probably not

spare prism
tender shard
#

which conflict? there shouldn't be any if you just use the version provided by spigot

spare prism
#

and send it

shadow night
eternal night
#

Well yes, the add entity packet

shadow night
#

Hmm

spare prism
#

ty

hazy parrot
#

There shouldnt be any conflict, spigot should be the only one which shades log4j

elfin atlas
#

Is it possible to cancel the sign editing when pressing on a sign so that it will not open?

inner mulch
#

can someone explain what this does when is type code in a class? I dont know what to google, i dont know what it is.

    //code
}```
tall dragon
#

itll run the code in there when the class gets loaded iirc

tender shard
# inner mulch can someone explain what this does when is type code in a class? I dont know wha...

Java allows you to use the so called “init blocks”. You can declare static and instance init blocks. The static init blocks will run exactly once, when the ClassLoader loads the class that declares it, and the instance init blocks run everytime you construct a new object, after the actual constructor ran. The general order...

inner mulch
tall dragon
#

no

tall dragon
sterile flicker
#

import com.sumeru.party.SumeruParty;
import com.sumeru.party.economy.Vault;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.Statistic;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.*;

public class PartyScoreboard {
    static Scoreboard board;
    public static void setupScoreboard() {
        ScoreboardManager manager = Bukkit.getScoreboardManager();

        for (String pl : SumeruParty.players) {
            Player p = Bukkit.getPlayerExact(pl);
            board = manager.getNewScoreboard();
            Objective objective = board.registerNewObjective("Party", "dummy");
            objective.setDisplaySlot(DisplaySlot.SIDEBAR);
            updateScoreboard();

            p.setScoreboard(board);
        }
    }

    public static void updateScoreboard() {
        for (String pl : SumeruParty.players) {
            Player p = Bukkit.getPlayerExact(pl);

            String kills = "§bKills§8: §7" + p.getStatistic(Statistic.PLAYER_KILLS);
            String deaths = "§bDeaths§8: §7" + p.getStatistic(Statistic.DEATHS);
            String spacer = "§7§m-------------------";
            Objective objective = board.getObjective("Party");
            ............
        }
    }
}

please help it throws a nullpointeexception in this line Objective objective = board.getObjective("Party"); and new BukkitRunnable() { public void run() { PartyScoreboard.updateScoreboard(); } }.runTaskTimer(plugin, 0L, 20L);

tender shard
#

board is null

sterile flicker
#

please help me identify the problem

tall dragon
#

he already identified your problem

sterile flicker
#

but why board == null

tender shard
#

you probably call updateScoreboard() before you call setupScoreboard

tall dragon
#

other than that this is an interesting piece of work

#

you set the global value for every player

#

then when updating you use that global variable?

#

this makes very little sense

sterile flicker
sterile flicker
tall dragon
minor junco
sterile flicker
# tall dragon

and? so what's the problem with replacing with
Objective objective = p.getScoreboard().getObjective("Party");

tall dragon
#

ah thats what u mean

#

yea

#

that should be fine

sterile flicker
#

thanks

tall dragon
#

but

#

right now for every player u setup scorebord u also update for all players

#

since thats in the for loop

sterile flicker
inner mulch
#

until plugin is disabled?

sterile flicker
#

now objective.getScore(spacer).setScore(15); throws NPE

tall dragon
inner mulch
tender shard
tall dragon
#

when the jvm e.g. ur server shuts down or when its defining class loader is reclaimed by the garbage collector

inner mulch
tender shard
#

more or less, yeah

tall dragon
#

spigot even does so

#

here

tender shard
#

yo my boyfriend joined the chat

ionic terrace
#

Is there a better way of adding textures onto player heads instead of using skullmeta?

tender shard
#

no

ionic terrace
#

Oh

river oracle
#

NMS ig

tender shard
#

how's that better though

river oracle
#

but whats with the API hate though

#

just use SkullMeta

#

I get ItemMeta needs a rewrite but thats internal not API :P

eternal night
#

all the cool kids love cloning /s

tender shard
#

this is the proper way on 1.18.1+ to use base64 / url skins https://blog.jeff-media.com/creating-custom-heads-in-spigot-1-18-1/

Spigot 1.18.1 added the new PlayerProfiles class, which finally allows us to use custom heads without needing any reflection! You can obtain them as normal items, or actually place them down into the world. I’ll show you how both works: Creating a new PlayerProfile First, we gotta create a new PlayerProfile object. To do so,...

river oracle
tender shard
#

lynx is a trap confirmed

eternal night
#

Is that a promise shy

tender shard
#

uwu

eternal night
river oracle
#

😨

ionic terrace
tender shard
#

correct

ionic terrace
#

Great, thanks

quaint mantle
lost matrix
quaint mantle
#

Cause it sounds like an input exception

ivory sleet
#

But you can consider to fallback to some default values/ try to load it again, or just report that the data failed to load

quaint mantle
#

Should that be my service's job or the api user's job to report

ivory sleet
#

As a service you should try to tell the api consumer when the service cannot deliver as expected

lost matrix
steel swan
#

is there a way to return the player that clicked in the inventory?

tender shard
#

getWhoClicked() then if it's instanceof Player, cast it to Player

river oracle
#

?jd-s

undone axleBOT
river oracle
#

HumanEntity can be cast to player without worries

#

unless you want to enable the ability for NPC's to interact with your inventory

steel swan
#

Ok thx !

tender shard
steel swan
#

ok i will

#

Oh and btw, is there a listener for when a player put on/off a piece of armor?

tender shard
lost matrix
tender shard
quaint mantle
lost matrix
#

I would 100% pass the exception through. 🙂

river oracle
#
    public static ChatColor of(Color color)
    {
        return of( "#" + String.format( "%08x", color.getRGB() ).substring( 2 ) );
    }

Why MD 🥲

ivory sleet
#

Yeah propagate it is usually quite reasonable

lost matrix
ivory sleet
river oracle
# ivory sleet PR time

I ran a JMH test on it just to see invoking the constructor directly instead of doing useless string fuckery turns out to be around 7.5x faster give or take for inconsistencies

#

this is using MethodHandles ofc

ivory sleet
#

Ofc

#

Ooo

#

But anyway String format is so slow lol

river oracle
#

well remember it also runs it through this method too

#
    public static ChatColor of(String string)
    {
        Preconditions.checkArgument( string != null, "string cannot be null" );
        if ( string.startsWith( "#" ) && string.length() == 7 )
        {
            int rgb;
            try
            {
                rgb = Integer.parseInt( string.substring( 1 ), 16 );
            } catch ( NumberFormatException ex )
            {
                throw new IllegalArgumentException( "Illegal hex string " + string );
            }

            StringBuilder magic = new StringBuilder( COLOR_CHAR + "x" );
            for ( char c : string.substring( 1 ).toCharArray() )
            {
                magic.append( COLOR_CHAR ).append( c );
            }

            return new ChatColor( string, magic.toString(), rgb );
        }

        ChatColor defined = BY_NAME.get( string.toUpperCase( Locale.ROOT ) );
        if ( defined != null )
        {
            return defined;
        }

        throw new IllegalArgumentException( "Could not parse ChatColor " + string );
    }
ivory sleet
#

StringBuilder is actually rather fast

#

but yeah

lost matrix
ivory sleet
#

hahaha

#

Allman coding style

river oracle
#

my guess this is for legacy chat but its not needed when dealing with components

#

completely uneeded in my component parser so I just am doing invokeExact 💪

ivory sleet
#

Yeah method handles can be so nicee

river oracle
#

I don't like that you need to try catch them every time, but 🤷‍♂️

    static {
        CHAT_COLOR_CONSTRUCTOR = ReflectionUtils.getConstructor(ChatColor.class, new Class<?>[]{String.class, String.class, int.class});
    }

    public static ChatColor create(@NotNull final Color color) {
        String string = color.toString();
        try {
            return (ChatColor) CHAT_COLOR_CONSTRUCTOR.invokeExact(string, string, color.getRGB());
        } catch (Throwable e) {
            throw new IllegalArgumentException(e);
        }
    }```
ivory sleet
#

Oof catching throwable

river oracle
#

🤷‍♂️ idk what else to do since invoke throws Throwable

ivory sleet
#

yeah well

river oracle
#

the other option is to literally just propogate it into my parser

remote swallow
#

shruggy moment

river oracle
#

which is equally as well you have to catch Throwable

young knoll
#

Smh

#

At least catch exception

river oracle
#

otherwise you have to throw Thrwoable

ivory sleet
#

Its a bit stupid because its just if the underlying method propagates an exception @river oracle

river oracle
#

you end up going full circle

ivory sleet
#

but yeah, I just think its oof on javas end altho it’s understandable but still

ivory sleet
river oracle
#

believe me catching Throwable hurts the soul

#

my ideal world 🥲

    public static ChatColor create(@NotNull final Color color) {
        String string = color.toString();
        return (ChatColor) CHAT_COLOR_CONSTRUCTOR.invokeExact(string, string, color.getRGB());
    }```
river oracle
#

that'd be redundant

umbral ridge
#

yea

river oracle
#

my platform of choice is spigot not paper

umbral ridge
#

yea

proud badge
#

If I send particle packets to a player, I assume only that player can see those particles right?

young knoll
#

yes

#

But we also have api for that

quaint mantle
young knoll
#

Yeah, but not well

#

It has like 5 methods for bukkit

quaint mantle
#

Yeah.

junior geyser
#

Is there an event that is called when the dragon blows up?

#

I thought it would be EntityDeathEvent, but the blow up effect plays after the dragon is killed

quaint mantle
#

EntityDamagedEvent

#

Then check if damage more than health

proud badge
#
        PacketContainer packet = HeeseTroll.protocolManager.createPacket(PacketType.Play.Server.WORLD_PARTICLES);
        packet.getIntegers().write(0, particleId);
        packet.getFloat().write(0, (float) location.getX());
        packet.getFloat().write(1, (float) location.getY());
        packet.getFloat().write(2, (float) location.getZ());
        packet.getFloat().write(3, 0.3f); // offsetX
        packet.getFloat().write(4, 0.3f); // offsetY
        packet.getFloat().write(5, 0.3f); // offsetZ
        packet.getFloat().write(6, 0.1f); // speed
        packet.getIntegers().write(1, 50); // count

        try {
            HeeseTroll.protocolManager.sendServerPacket(player, packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }``` Ok I keep getting nullpointerexceptions here, anyone know where I messed up? (specifically at the protocolManager.sendServerPacket)
```sendCustomParticlePacket(target, 101, target.getLocation());```
chrome beacon
#

You don't need packets and protocol lib to send particles

proud badge
#

A particle that only the player can see

chrome beacon
#

You can use the API for that

tender shard
#

there's literalls 10 methods for that

proud badge
#

I dont see a player selection though anywhere

#

How could I send a particle to a specific player?

tender shard
#

because it's an instance method on the Player class?

tender shard
proud badge
#

oh so player.spawnParticle and only the player can see that particle?

tender shard
#

yes

proud badge
#

epic thx

tender shard
#

np

sterile flicker
#
        ScoreboardManager manager = Bukkit.getScoreboardManager();

        for (String pl : SumeruParty.players) {
            Player p = Bukkit.getPlayerExact(pl);
            Scoreboard board = manager.getNewScoreboard();
            Objective objective = board.registerNewObjective("Party", "dummy");
            objective.setDisplaySlot(DisplaySlot.SIDEBAR);

            p.setScoreboard(board);
        }
    }

    public static void updateScoreboard() {
        for (String pl : SumeruParty.players) {
            Player p = Bukkit.getPlayerExact(pl);

            String kills = "§bKills§8: §7" + p.getStatistic(Statistic.PLAYER_KILLS);
            String deaths = "§bDeaths§8: §7" + p.getStatistic(Statistic.DEATHS);
            String spacer = "§7§m-------------------";
            Objective objective = p.getScoreboard().getObjective("Party");
            objective.getScore(spacer).setScore(15);
            objective.getScore(kills).setScore(14);
            objective.getScore(deaths).setScore(13);
            objective.getScore(spacer).setScore(12);```please help ``` objective.getScore(spacer).setScore(15);``` throws NPE
chrome beacon
#

did you run setup scoreboard

sterile flicker
chrome beacon
#

any other scoreboard plugins?

#

also does it always npe

sterile flicker
sterile flicker
chrome beacon
#

and where do you run setup scoreboard

sterile flicker
#

i have condition SumeruParty.gameStarted = true; PartyScoreboard.setupScoreboard(); and ```new BukkitRunnable() {
public void run() {
if (gameStarted) {
PartyScoreboard.updateScoreboard();
}

            }
        }.runTaskTimer(plugin, 0L, 20L);```
#

i see the problem

#

i have SumeruParty.players.add(player.getName()); after setupScoreboard

chrome beacon
#

You should fix your static abuse

#

also next time send all the relevant code

sterile flicker
rapid scarab
#

Hey guys. I'm working on a plugin that uses mysql databases (2 actually). Plugin works & was tested on multiple servers with no issues but just seems to crash after a while for this one specific server I'm working with. Tried the plugin on another server running on the same machine with little amount of plugins, & everything worked fine, so it wasn't the machine stopping the plugin from connecting to the databases or anything. Plugin also runs in a big server with different plugins with no issues whatsoever.

Plugin works fine anywhere from 20 minutes to 3 hours before this one specific server completely crashes: https://pastebin.com/gHiLEpTB

Code for the methods that are mentioned in the crash log: https://pastebin.com/QP1K8AiQ & here's what I use to connect to the database:

public void connect(String databaseUrl, String username, String password) throws Exception {
        Class.forName("com.mysql.cj.jdbc.Driver");
        connection = DriverManager.getConnection(databaseUrl, username, password);
    }

I'm most likely going to use Hikari in the future but I doubt that's what's crashing the server, since it runs on other servers fine?

It's 100% a plugin incompatibility with some other plugin but I can't seem to figure out what it is, & the server I'm working with has 141 plugins, so removing plugin by plugin seems impossible. Any ideas? Thanks 💙

eternal night
#

beyond the pooint that there is 0 sense in wrapping all of this fun in a CF

#

when you just #get directly after

chrome beacon
#

Don't run database queries on the main thread 💀