#help-development

1 messages · Page 542 of 1

eternal oxide
#

ah 🙂

quaint mantle
#
    public void moisture(MoistureChangeEvent e) {
        e.setCancelled(true);
        World world = e.getBlock().getWorld();
        if (!(world.isClearWeather())) {
            e.setCancelled(false);
        }
    }```
eternal oxide
#

you need to detect if the block is near a watering block, and only water below a certain level.

fierce salmon
#

I'm using this code to detect when a player presses a pressure plate, but it doesn't seem to be working:

} else if (event.getAction() == Action.PHYSICAL){
                if (event.getClickedBlock().getType() == Material.LIGHT_WEIGHTED_PRESSURE_PLATE){
                    if (event.getClickedBlock().getLocation().equals(new Location(Bukkit.getWorld("practice"), -74, 65, -24))){
                        player.teleport(new Location(Bukkit.getWorld("practice"), -74.5, 65, 0.5, 180, 0));
                        player.sendMessage(ChatColor.GREEN+"You have completed Bridging!");
                    }
                }
            }
#

ignore the spacing, it just copied wrong

eternal oxide
#

have you got the correct world name this time?

fierce salmon
#

yes lol it was the first thing I checked after yesterday's incident

eternal oxide
#

sysout the block location

fierce salmon
#

good idea

#

Oh i get it now

#

ty

cobalt thorn
#

Hi, something strange is happening with this code, this code runs correctly every Monday runs etc.. but sometimes happens the code runs on days that shouldn't run like today ran at 9 pm

Code: https://sourceb.in/Rwnft8usIm
Main Class:

TimeUtils.getDate();
TimeUtils.startScheduler();

I don't know what I'm doing wrong but should be everything correct for adding something
here the line save in the config "Mon May 29 00:00:00 CEST 2023"

clear galleon
#

How do I use hex codes? I want a custom scoreboard but I cannot figure out how to use hex colors as I tried ChatColor.of() but It did not appear and I got an error help is appreciated

shadow night
#

Hey, I've already posted this but I think nobody saw it (or didn't answer) due to the ongoing conversation at that time. I have this weird error about the multiplication of the velocity, I've tried changing the multiplier but it seems to be the same. I have no idea why that happens and how I can make a fast and quick enough arrow without that. (Idk if it's critical but it spams the console so it isn't good)

[19:41:42 WARN]: Excessive velocity set detected: tried to set velocity of entity #378 to (6.574896471116735,-2.4675344695432244,-3.9350362178400293).
[19:41:42 WARN]: java.lang.Exception: Stack trace
[19:41:42 WARN]:     at java.lang.Thread.dumpStack(Thread.java:1341)
[19:41:42 WARN]:     at org.bukkit.craftbukkit.v1_8_R3.entity.CraftEntity.setVelocity(CraftEntity.java:213)
[19:41:42 WARN]:     at me.andreasmelone.gunstop.GunEvents.onPlayerShoot(GunEvents.java:69)
``` (Code: <https://github.com/RaydanOMGr/GunStop/>)
#

If needed, I can send the whole log of the server

eternal oxide
#

you are setting a velocity of just under 13

eternal night
quaint mantle
#

can i check if blocks gets hit by a water ( i mean rain water ( particles ) )

clear galleon
shadow night
eternal night
eternal oxide
#

I believe 10 is the max velocity per tick

shadow night
#

I have no idea about velocity

#

Rn I'm multiplying it by 8.05
arrow.setVelocity(player.getLocation().getDirection().multiply(8.05));

eternal oxide
#

then reduce your multiplier

shadow night
#

Let me try, I will do like 7

#

Or should I do 6.25?

#

I'm gonna do 6.75

shadow night
river oracle
eternal night
#

flame mojang for not providing component support in scoreboard scores

eternal oxide
#

so try 4

#

direction is a unit vector

#

so multiply by 4 should give the max velocity

karmic mural
#

If you gotta try around just have a config or something to update the value on the fly and test?

#

Isn't the max velocity based on acceleration? Like if you accelerate too much in a single tick?

#

Unless I am completely missing the point here, please correct me if that is the case. But I believe the channel "LiveOverflow" made a video about player velocity exploits on paper (not quite spigot, I know) If you feel it's related let me know and I can link you the video privately

shadow night
pseudo hazel
#

I am afraid the answer is no, but is there a way to get a spawn egg of any color (combination) ?

#

idc what or if it spawns anything

#

should be stated that I don't want to use a resource pack..

shadow night
karmic mural
#

My immediate thought is giving the spawn egg of the type you want a custom name, and some identifier that a plugin can use to detect when that particular egg is being used, and replace the type of animal it spawns

#

(I'm not terribly experienced with this yet, so there is a high chance that there's a much better way to do it)

pseudo hazel
#

well like I said, I dont care about what it spawns

#

I just need it visually

#

for inventory

pseudo hazel
#

sad

river oracle
#

AFAIK atleast

dire marsh
eternal night
#

teams ? Confusement

pseudo hazel
#

team names do

dire marsh
#

scoreboard teams still have a preset colour set

pseudo hazel
#

just not the scoreboard easily

eternal night
#

I mean, so do prefix and suffix in teams

#

well the scores don't

#

yea

ruby mesa
#

hey guys!


            ShapelessRecipe recipe = new ShapelessRecipe(key, ItemBuilder.of(Material.BREWING_STAND)
                    .name("&3&lPotion Maker")
                    .addToLore("", "&3| &fRight click to start a",
                            "&3| &f5 second cooldown which gives you",
                            "&3| &f3 health potions",
                            "",
                            "&fObtainable through &bcrafting&f.")
                    .enchant(Enchantment.DURABILITY, 1)
                    .flag(ItemFlag.HIDE_ENCHANTS)
                    .build());

            recipe.addIngredient(Material.GLASS);
            recipe.addIngredient(Material.NETHER_WART);
            recipe.addIngredient(Material.GLOWSTONE_DUST);
            recipe.addIngredient(Material.GLISTERING_MELON_SLICE);
            recipe.addIngredient(Material.AIR);

            Bukkit.getServer().addRecipe(recipe);```

this code i provided does not seem to add the recipe. i've tried to look it up, ask chatgpt, etc but nothing worked lol. anyone know why?
#

its in the onEnable method btw

eternal night
#

AIR ?

#

why are you adding air as an ingredient 💀

ruby mesa
#

oops

#

i kinda just copied and pasted my old code and changed it a bit

#

but is that the issue?

eternal night
#

maybe ™️

ruby mesa
#

lemme test

ruby mesa
fierce salmon
#

How can I make a variable that applies to one specific player?

river oracle
#

Map

#

It

#

Data object with a Map<UUID

eternal oxide
#

a variable to do what?

river oracle
#

Stuff and things

#

A safe bet is always UUID, DataObjectHere

fierce salmon
robust pebble
#

any way I can make a timer and when it hits 0 it bans the player, and I can add and subtract time based on what theplayer does

flint coyote
#

Sure. Just use a Hashmap with either time left or bantime and adjust it whenever you need

robust pebble
#

coudnt I create a timer for every player or something

#

and save it evry second

flint coyote
#

Yeah you could but you'd still require a map

robust pebble
#

like Player --- Time

eternal oxide
#

explain what you are trying to do and we can give better advice

robust pebble
#

ok so

#

I want each player to get 10 hours

#

they kill another player to get one more hour

#

if their time is up

#

they get ban

eternal oxide
#

ok does this persist between player relog or server restarts?

robust pebble
#

yes

#

so I need to save the time

eternal oxide
#

save it on the player

robust pebble
#

good idea

eternal oxide
#

start a repeating task and every time it triggers it loops over all players and removes X amount of time

#

any players hitting <=0 get kicked/banned

#

you coudl have it run every minute or even 5

robust pebble
eternal oxide
#

adding/subtracting will be simple as you are just updating the value already on the player

#

?pdc

robust pebble
#

Thanks

robust pebble
eternal oxide
#

if they don't already have a time, yes

fierce salmon
#

How can I use a for loop to loop through the different UUID values in a hashmap?

#

nvm

eternal oxide
#

map.entrySet().forEach

fierce salmon
#

dont answer that

#

Im an idiot

obsidian plinth
#

Whats the best way to find a memory leak in a plugin

eternal oxide
#

experience

obsidian plinth
#

thats a lie lol

#

and not helpful

quaint mantle
#

how to use Tag ?

river oracle
#

if it doesn't

#

Meh probably not a memory leak

obsidian plinth
#

naw ik it has one

river oracle
#

if it does probably a memory leak

obsidian plinth
#

im saying to find what it is

river oracle
#

you're probably not emptying a map or something when people leave etc

#

look at lists and maps

#

usually they're the source

robust pebble
#

should I set a time variable at the beginning and have getter settter

halcyon temple
#

So you have a task which is runs by x tick ( you can choose whatever you want i think) the task checks if there is online player on the server? if it is then checks player's time

eternal oxide
#

that would work

#

you can add/subtract for kills

halcyon temple
#

yeah you can change it as you want

robust pebble
halcyon temple
#

because i'm not native

eternal oxide
#

I said earlier, you runTaskTimer

#

it triggers at a predetermined interval

hasty prawn
#

Could be why it doesn't exist then.

eternal oxide
#

everymineut or 5, you decide

robust pebble
#

new BukkitRunnable() {
@Override
public void run() {
//methods
cancel();
}
}.runTaskTimer(plugin, 1, 1);

#

like this im guessing

halcyon temple
#

yeahh

#

but i think incresaing the interval might be better

#

because you are checking 20 times in a second now

eternal oxide
#

yeah no point in doing every tick

#

do it every minute

#

at teh minimum

halcyon temple
#

you can do it every second i think it won't lag

#

so just determine what you need

robust pebble
#

oh rlly

robust pebble
eternal oxide
#

I'd run it every 72000 ticks

#

1 minute

robust pebble
eternal oxide
#

replace the last 1 with 72000

robust pebble
#

new BukkitRunnable() {
@Override
public void run() {
//methods
cancel();
}
}.runTaskTimer(plugin, 1, 72000);

halcyon temple
robust pebble
#

yes I see

halcyon temple
#

but when it created it immideaditly checks (the first value is the delay)

robust pebble
#

should I put this snippet in what type of class (like event class command class etc)

halcyon temple
#

You can run it JavaPlugin#onEnable

robust pebble
#

sweeet

halcyon temple
#

or you can create a extra class for this

robust pebble
#

I dont want to rlly

halcyon temple
#

if the plugin is small and the operation is not too long there is no need to do i think

#

it won't effect the readability of the code

robust pebble
#

oh nice!

#

now that I have that

#

where would I create the time and save it

#

when the player joined im guessing

halcyon temple
#

how would you store the data?

robust pebble
#

in the player

#

as elgarL said

halcyon temple
#

oh i don't know about it but

#

when the player joins

#

just check if there is a data for him? if not just create the time data for him

#

if you can keep the data in player as you said

#

just loop the online players

#

and write the conditional that's it

robust pebble
#

here I create timer

halcyon temple
#

just create the data for the player

safe leaf
#

Is there a plugin makes fake player so I can test the player damage event?

robust pebble
#

i see

halcyon temple
#

yeah

robust pebble
#

ok so now where do I decresetime

flint coyote
safe leaf
halcyon temple
#

you can get the current unix timestamp by System.currentTimeMills()

flint coyote
halcyon temple
#

and you need to add the kick time to this value

#

let me show you 1 sec

robust pebble
#

could you show that to me in code (an example)

safe leaf
# flint coyote can't you die yourself?
    @EventHandler
    void onPlayerDie(PlayerDeathEvent event) {
        Player p = event.getEntity();
        Session pSession = this.plugin.getSessionManager().getSession( p );
        pSession.addDeaths( 1 );

        EntityDamageEvent cause = p.getLastDamageCause();
        if (cause instanceof EntityDamageByEntityEvent) {
            Player killer = (Player) ((EntityDamageByEntityEvent) cause).getDamager();
            Session kSession = this.plugin.getSessionManager().getSession( killer );
            kSession.addKills( 1 );
        }
    }```
#

Read the code and you will get what I need

flint coyote
#

In that case no, you can't test it without a second account or online-mode false

safe leaf
robust pebble
flint coyote
#

Or you fire the event yourself

halcyon temple
#

The System.currentTimeMills() returns the current Unix Timestamp and the value is for milliseconds so

void onPlayerJoin() {
    long time = System.currentTimeMills(); //Just imagine this value is zero
    setPlayerKickTime(player, time + (20 * 1000));
}

void check() {
    long time = System.currentTimeMills();
    forEach(p -> {
        if (getPlayerKickTime(p) >= time) {
            kickPlayer(p)
            //The conditional checking for the time is passed or not
        }    
    })
}
#

i hope this helps

halcyon temple
#

idk actually

robust pebble
#

WE COULDVE DONE THAT'

halcyon temple
#

i'm just trying to help

#

if he wants the playtime he can do that

robust pebble
#

im confusedeth

#

you know grians limited life

eternal oxide
#

its not play time, it's a death clock. you gain time by killing, lose it for being killed

robust pebble
#

like that

eternal oxide
#

It would probably be easier for you to read and understand using Instant

halcyon temple
#

dude you need to implement your own way

robust pebble
#

check is in onenable so I can put a forever loop

eternal oxide
#
Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
//put on pdc
expires.toEpochMilli();```
zenith gate
#

can someone explain to me what exactly this error message means? I know something is null, but it says plugin is null. I don't know what part it is or how to even begin to fix it.

java.lang.NullPointerException: Cannot invoke "toast.pine.overhaulweapons.OverhaulWeapons.getServer()" because "toast.pine.overhaulweapons.Swords.RogueRunner.plugin" is null
eternal oxide
#

reading it from the pdc you take the long and java Instant expires = Instant.ofEpochMilli(/* pdc value */);

remote swallow
eternal oxide
#

you can then check if it's expired by expiresjava if (Instant.now().isAfter(expires))

robust pebble
#

oooh

halcyon temple
#

yeah using instant is also good way

zenith gate
halcyon temple
#

but the main thing you need to get storing them not creating

robust pebble
#

*set timer

halcyon temple
zenith gate
remote swallow
#

okay, do you set the plugin instance inRogueRunner to that

robust pebble
#

here I set to 10

zenith gate
remote swallow
#

?paste your main class and the rouge runner class

undone axleBOT
eternal oxide
robust pebble
#

OH

eternal oxide
#

it basically converts the expires value to a Long you can store on the PDC

remote swallow
halcyon temple
#

and you don't have to

remote swallow
#

?di or add = OverhaulWeapons.getPlugin()

undone axleBOT
halcyon temple
#

just use it from the OverhaulWeapons#getPlugin

zenith gate
#

omg

halcyon temple
robust pebble
#

im gonna need to use string value of

eternal oxide
#

no

halcyon temple
#

i think you can create your own type

#

but this is fine until you are parsing it

eternal oxide
#

new NamespacedKey(plugin, "death_clock")

halcyon temple
#

ohh my bad yeah you need to give a name first

eternal oxide
#

you then use that key to store your expires

#

pdc.set(key, type...LONG, expires.toEpocMillis())

robust pebble
#

expires.toEpocMillis()

eternal oxide
#

death_clock all lower case

robust pebble
#

alr

eternal oxide
#

you may want to create that key as a field, you'll be using it a lot

robust pebble
#

ok

eternal oxide
#

so a class level variable

robust pebble
#

alright

#

nice

#

can I decrease and check time in on enable, then save it

eternal oxide
#

not in onEnable

robust pebble
#

oh

eternal oxide
#

no players online then, unless it's a restart

robust pebble
#

that is true but I could do onenable then check if player on line or for every play if onlione or smth

eternal oxide
#

why do you want to do something in onEnable?

robust pebble
#

I just thought it might work lol

eternal oxide
#

Not sure what you are trying to do

robust pebble
#

i wanna decrease time / check time and save the time

eternal oxide
#

um, you'd not do any of those in onEnable

robust pebble
#

oh lol

eternal oxide
#

in your onEnable you start your repeating task is all

robust pebble
#

which is where I decrease the time, am I right?

#

and save

eternal oxide
#

nope, all you do in there is compare times and kick/ban if expired

#

you only increase/decrease time when a player gains or loses time

#

on death or whatever tasks you give time for

robust pebble
#

um its a clock you lose time continuously

#

I think

eternal oxide
#

no, it's actually a future clock

#

its a specific time in the future

robust pebble
#

samsung notification noise

eternal oxide
#

so all you do is compare the current time to it to see if you reached it yet

robust pebble
#

but the server restarts tho...

eternal oxide
#

doesn;t matter

robust pebble
#

ok makes sence

eternal oxide
#

its a future time saved on teh player

robust pebble
#

so all I have to do is...

#

kill and death

eternal oxide
#

yes, and compare

robust pebble
#

comapre meaning if player time 0 or less than ban

eternal oxide
#
public boolean hasExpired(Player player) {

    Instant expired = Instant.ofEpocMillis(player.getPersistantDataContainer().get(key, PersistentDataType.LONG));
    return Instant.now().isAfter(expired);
}```
#

so if (hasExpired(player)) { kill/ban

eternal oxide
#

you could

robust pebble
#

ayy

eternal oxide
#

its a utility method so it's fine

#

true

#

although most of his methods will be utility methods

#

I'd probably create a deathclock utility class

#

just the namespaced key at the top and all static methods below

robust pebble
#

I should do that

eternal oxide
#

would keep it clean

#

then you'd have static methods for hasExpired, addTime and subtractTime

#

also add one for setTime

robust pebble
#

true

#

I could do settime()+1hour or something

#

and vise versa for death and live

eternal oxide
#

yep, keepign all clock methods in one class

#

um I just though the key breaks the stateless pattern of a utils class

#

as it needs the plugin

robust pebble
#

this line isnt going in the util class

vast ledge
#

My code works 😄

robust pebble
#

evry tick I need to check if player should be banned or not where do I do that

eternal oxide
#

I'd not do it as precise at every tick

robust pebble
#

second?

eternal oxide
#

at most every minute or a few seconds

quaint mantle
#

i don't understand how can i use tags ? 😢

robust pebble
quaint mantle
#

i did but i got some warnings

eternal oxide
robust pebble
eternal oxide
#

yes

halcyon temple
quaint mantle
robust pebble
# eternal oxide yes

Long timeInSeconds = 10;
Long timeInTicks = 20 * timeInSeconds;
new BukkitRunnable() {

@Override
public void run() {
    //The code inside will be executed in {timeInTicks} ticks.
    
}

}.runTaskLater(plugin, timeInTicks); // Your plugin instance, the time to be delayed.

halcyon temple
#

ekle özelden

robust pebble
#

Can I put this in on enable

unique bay
#

hi little people, how do I include .yml file into my jar file when I export my build? it's my first time doing this

eternal oxide
#

runTaskTimer

#

are all of your add/subtract going to be in hours?

robust pebble
#

yessir

unique bay
#

please

robust pebble
#

^^^^^ this guy

unique bay
#

danke

robust pebble
eternal oxide
#

I'm having a play writing a utils class for it

shadow gazelle
#

Would an empty entry give you an empty list?

eternal oxide
#

it got me interested 🙂

shadow gazelle
#

or should I add a - with no entry

robust pebble
robust pebble
# eternal oxide it got me interested 🙂

Long timeInSeconds = 10;
Long timeInTicks = 20 * timeInSeconds;
new BukkitRunnable() {

@Override
public void run() {
    //The code inside will be executed in {timeInTicks} ticks.

}

}.runTaskLater(plugin, timeInTicks); // Your plugin instance, the time to be delayed.

#

can I put this in on enable

eternal oxide
#

yes

onyx fjord
#

Can you somehow get all item containers in the server?

eternal oxide
#

runTaskTimer not runTaskLater

onyx fjord
#

All chests etc etc

shadow gazelle
robust pebble
# eternal oxide runTaskTimer not runTaskLater

int timeInSeconds = 10;
int timeInTicks = 20 * timeInSeconds;
new BukkitRunnable() {

        @Override
        public void run() {
            //The code inside will be executed in {timeInTicks} ticks.


        }
    }.runTaskTimer(plugin, 1,timeInTicks);
#

this is what I got

eternal oxide
#

yep

robust pebble
#

can I get a list of online players and check if they are expired or not

onyx fjord
#

Expired?

robust pebble
#

returns array?

eternal oxide
#

.forEach

#

whats teh data command to lists a players full nbt/pdc?

fierce salmon
#

I am trying to make a plugin for water bucket clutching, but ran into a problem. Sometimes you can place the water bucket and pick it up before you actually clutch. Is there any way to tell if the player actually clutched or not?

eternal oxide
#

thanks that worked

#

?paste

undone axleBOT
eternal oxide
#

You can use those as examples and add things like getting the length of time left on a players clock

#

you could then display their death clock in the action bar as it ticks down

robust pebble
#

how do I ban the player

eternal oxide
#

ban then kick

robust pebble
eternal oxide
#

Player#ban I think

robust pebble
worldly ingot
#

BanLists

#

Bukkit#getBanList()

robust pebble
#

could you give a usage?

worldly ingot
#

If you have an IDE I'm almost certain you could figure out how to use this just by putting a . after the result of Bukkit.getBanList(BanList.Type.NAME)

#

(the type is NAME, but you can, and should, use a stringified UUID)

robust pebble
#

Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName());

eternal oxide
#

.NAME not .IP

robust pebble
#

oh lol

eternal oxide
#

sender.getUniqueId().toString()

robust pebble
#

what is sender

eternal oxide
#

Player

robust pebble
#

oh ok

fierce salmon
#

I am trying to make a plugin that detects when the player makes a water bucket clutch and was wondering how I can do this?

robust pebble
#

Bukkit.getBanList(BanList.Type.NAME).addBan(p.getName(), "bro died out of old age in MINECRAFT lmaooo", null, p.getName());

#

p is player btw

eternal oxide
#

not name use their UUID

kind hatch
eternal oxide
#

addBan(p.getUniqueId().toString(), "Clock ran out", null, null)

robust pebble
#

String.valueOf(p.getUniqueId())

eternal oxide
#

I gave you exactly what you need

robust pebble
#

alright the rest should be a breeze

wise mesa
fierce salmon
tough crater
#

Ok so this is a stupid question but is it possible to make a WiFi network that works on just a phone and no provider or no hotspots

rough ibex
undone axleBOT
tough crater
rough ibex
#

sure

wise mesa
#

well you have to pay someone

rough ibex
#

of course you'll have no connection

wise mesa
#

because you're using someone's infrastructure

wise mesa
rough ibex
#

you can make a fake wifi network that only sees what is in the network

#

and no internet

tough crater
#

Is it possible to make your own network provider

remote swallow
#

if you have money for it sure

tough crater
#

But how do you do that

remote swallow
#

if you want it to be self sufficent you pay to build either a wireless tower or get fibre cable you put it in and then supply the internet to, most likely using someone elses infrastructure, or you can pay a company to use their infra but under your name

#

its way easier to just pay the company a lot less than that to use their services

remote swallow
#

and get one of those 4g sim card routers or something

hazy parrot
#

I think we all as a kids questioned that hahahahag

remote swallow
#

real

tough crater
#

If am rich I’ll probably make my own WiFi network and service

robust pebble
#

im done

eternal oxide
#

perfect

#

You see how a utils class for that makes it so clean

robust pebble
#

ikrrrr

silent belfry
#

How would I set the log level of an external dependency jar. LogManager.getLogger and LogManager.getLogerManager().getLogger() fails to find it? This is from java.util.logging.LogManager and org.apache.logging.log4j.LogManager

kind hatch
#

Your JDBC url is wrong. The format is jdbc:<STORAGE_TYPE>://<HOSTNAME>:<PORT>/<OPTIONAL_TABLE_NAME>
You can include the username and the password in the JDBC string, but since you are using the hikari config, you don't need to include them and just use the methods to set the username and password.

#

I think their URLs are for a direct MySQL database connection. It's different from the JDBC ones.

#

Oh wait, yes it is supposed to represent the database name. Although it is an optional parameter.

#

It's not neccessary for the string to be valid.

#

Although you probably want to include it if you don't want to have to be using the USE DATABASE_NAME constantly.

fierce salmon
kind hatch
#

That error normally shows up when you have more than one JavaPlugin instance.

fierce salmon
#

My runnable wants a value Plugin, what do I put there?

kind hatch
#

You put an instance of your main class that extends JavaPlugin. Although you shouldn't be creating new instances when doing it. Use dependency injection or use a static instance of it.

#

?di

undone axleBOT
fierce salmon
#

@quaint mantle can you show me some of your code that involves dependency injection

#

tysm

robust pebble
#

how would I turn an instant variable to a long or double

#

`public static Instant getTime(Player player) {

    PersistentDataContainer pdc = player.getPersistentDataContainer();
    Instant expires = Instant.ofEpochMilli(pdc.getOrDefault(key, PersistentDataType.LONG, Instant.now().toEpochMilli()));
    return expires;
}`
eternal oxide
#

.toEpochMilli()

eternal oxide
kind hatch
#

Dependency injection eliminates the need for the static keyword. The static keyword is also seldomly used in spigot plugins anyways.

eternal oxide
#

Its already a Long in the PDC

robust pebble
#

oh rlly

#

so this is milliseconds then

eternal oxide
#

since 1970

echo basalt
#

refer to this

robust pebble
#

10 hours is 3.6e+7

eternal oxide
#

it won;t be

kind hatch
#

That doesn't sound right.

robust pebble
#

alr

#

i tried it in another ide it works

#

10 hours goes in a long

eternal oxide
#

many years go in a long

robust pebble
#

oh dang

eternal oxide
#

it's capacity is exponentually bigger with every bit

warm mica
#

Likely because beginners don't plan to turn their programming session into a life lasting career and instead would rather create something useful using the limited time they have instead of learning something that they will forget anyways in a week

#

Nothing wrong with having messy code if you keep it in your own pockets. Nobody cares

kind hatch
robust pebble
#

static is useful

#

WAIT long's limit is 2147483647 Which is 20:36:23 ---> 20 hours 36 minutes 23 seconds...

warm mica
#

I don't think that there has been any project by a beginner that didn't deserve a rewrite after he improved his skills

kind hatch
#

How are you currently storing that data?

robust pebble
#

milliseconds --> long

kind hatch
#

Ok, now how are you reading it?

robust pebble
#

PersistentDataContainer pdc = player.getPersistentDataContainer();
Instant expires = Instant.ofEpochMilli(pdc.getOrDefault(key, PersistentDataType.LONG, Instant.now().toEpochMilli()));
return pdc.getOrDefault(key, PersistentDataType.LONG, Instant.now().toEpochMilli());

#

whatever this is

#

pdc

kind hatch
#

Just wondering, why are you using Instant.now() instead of System.currentTimeMillis()?

eternal oxide
#

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)

robust pebble
#

my man it isnt working for me

kind hatch
#

Wtf, why are you compiling in a terminal?

eternal oxide
#

you can;t put a long into an integer

kind hatch
#

Also that ^

robust pebble
eternal oxide
#

err sec

#

yes your max value is an int not a long

kind hatch
robust pebble
#

oh lol

#

long millis = 214748364876577; this is an int?

kind hatch
#

No, that's the MAX_VALUE of a long. 😛

ruby mesa
#

yo how would I access playerInteractionManager in nms

kind hatch
#

Although your compiler thinks it's assigned as an int for some reason.

robust pebble
#

oh lol

kind hatch
#

Oh wait.

#

Just add an L at the end of the number.

#

The compiler should pick that up.

wise mesa
#

how do I automatically generate and deploy sources for my api

robust pebble
wise mesa
#

idk how to use the maven source plugin

robust pebble
#

goofy terminal

eternal oxide
#

what exactly are you trying to do?

robust pebble
#

replit 👎

robust pebble
kind hatch
#

What format specifically?

eternal oxide
robust pebble
#

class Main {
public static void main(String[] args) {
long millis = 396000000000L;
Date date = new Date(millis);
// formattter
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// Pass date object
String formatted = formatter.format(date);
System.out.println("Result: " + formatted);
System.out.println();
}
}

#

this is what im doing lmao

#

imma try this

#

long HH = duration.toHours();
long MM = duration.toMinutesPart();
long SS = duration.toSecondsPart();
String timeInHHMMSS = String.format("%02d:%02d:%02d", HH, MM, SS);

kind hatch
#

It might be that the issue is the use of the max value itself. Try reducing it by one and see if it still compiles.

robust pebble
#

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_FORMAT) .withZone(ZoneId.systemDefault()); Instant instant = Instant.parse("2022-02-15T18:35:24.00Z"); String formattedInstant = formatter.format(instant);

#

PATTER_FORMAT

#

what is the variable

#

dont answer the question

#

pls

#

i figured out

eternal oxide
robust pebble
#

OHHH MAKE SENSE

eternal oxide
#

or you use the until method of Instant

robust pebble
#

getTime-instant.now()

#

or vice versa

eternal oxide
#

I'd actually use the second one, the until method

#

it's better fitting with Instants

robust pebble
#

it finds seconds tho

robust pebble
eternal oxide
#

finds setting?

robust pebble
#

seconds

eternal oxide
#

only if you ask for them

robust pebble
#

rlly

eternal oxide
#

look at teh second link I gave you

robust pebble
#

1
2
3

long noOfSeconds = instantBefore.until(instantAfter, ChronoUnit.SECONDS);

#

long noOfSeconds = instantBefore.until(getTime(p), ChronoUnit.MILLIS);

eternal oxide
#

Instant.now().until(getTime(player), ChronoUnit.MINUTES);

robust pebble
#

Instant.now().until(getTime(p), ChronoUnit.MILLIS);

#

ok so this is my time

#

in milliseconds

#

cuz it says millis

eternal oxide
#

yes, if you want it in milli

robust pebble
#

so it returns long so I have to use something other than instance formatter

#

I have to use long formatter

eternal oxide
#

or you could probably java Period period = Period.between(Instant.now(), getTime(p)); sysout period.getHours() period.getMinutes() etc

#

I think Period works with Instants

robust pebble
eternal oxide
#

looks like it would

#

you could do away with the duration

#

just do teh math on frt

#

oh no you couldn't

#

ignore me 🙂

delicate obsidian
#

It is posible to disable cobweb slowdown for mobs?

tough crater
#

How can I make a fake WiFi network on my phone

#

Am in Mexico am just trying to test it out

drowsy helm
#

whats does this have to do with spigot lol

tough crater
#

Idk

olive lance
#

Personal hotspot

#

But it won’t be fake I guess

wet breach
tough crater
#

Bruh am in Mexico and the only house by me is abandoned

robust pebble
#

vpn

wet breach
#

so you say.

robust pebble
#

any good title api for actionbar

tough crater
robust pebble
worldly ingot
#

what?

robust pebble
#

like "TIME : " + my epictimevar

#

like would it be in the action bar forever

worldly ingot
#

No, you would have to re-send the action bar

vocal cloud
robust pebble
#

oh wai nvm I could do that

#

Long Frt = Instant.now().until(getTime(p), ChronoUnit.MILLIS);
Duration duration = Duration.ofMillis(Frt);

    long h = duration.toHours();
    long m = duration.toMinutes() % 60;
    long s = duration.getSeconds() % 60;

    String timeInHms = String.format("%02d:%02d:%02d", h, m, s);
    p.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(timeInHms));
#

so this should be valid im guessing

worldly ingot
#

Yes, though the fromLegacyText() isn't really necessary. You can just wrap it in the text component. new TextComponent(timeInHms)

#

You would only have to do fromLegacyText() if you have legacy text formatting in the string, which in this case it doesnt' seem you do

robust pebble
#

alr thanks!

#

if I maven jar:jar my plugin should build im guessing

worldly ingot
#

mvn clean package will get you a build

thick gust
#

hey, I am experiencing issues with building an artifact in intellij idea (for my plugin). whenever I try building it, there is no jar file in the specified path and there is no progress bar appearing on the bottom bar of the IDE when trying to build it. It seems like it gets sorta aborted instantly. Can someone help? I have also tried watching tutorials and even followed the spigot docs.

unkempt peak
#

?paste

undone axleBOT
cobalt thorn
#

Hi, something strange is happening with this code, this code runs correctly every Monday runs etc.. but sometimes happens the code runs on days that shouldn't run like today ran at 9 pm

Code: https://sourceb.in/Rwnft8usIm
Main Class:

TimeUtils.getDate();
TimeUtils.startScheduler();

I don't know what I'm doing wrong but should be everything correct for adding something
here the line save in the config "Mon May 29 00:00:00 CEST 2023"

frail gale
#

You can use this for CurrentTime

cobalt thorn
#

Line?

hybrid spoke
#

or just create a new date

#

or use instant

#

but first thing i noticed is, that you compare the date integer objects by adress and not by value

cobalt thorn
hybrid spoke
#

primitives

#

Integer to int

cobalt thorn
#

You mean change it from a primitive object to an int

hybrid spoke
#

what

cobalt thorn
#

Integer to int

hybrid spoke
#

exactly, but there is no primitive object

cobalt thorn
#

Nothing else as a problem because i don’t see i stared to the code for hours but nothing else like as a problem

hybrid spoke
#

well, today is not the second day of the week

cobalt thorn
hybrid spoke
#

also monday is not the second day of the week

eternal oxide
#

In some countries it is

#

in some it's the third day

hybrid spoke
#

just dont use calendar for that

#

its weird anyways

cobalt thorn
#

What should i use then?

buoyant viper
#

wtf country makes monday the third day

eternal oxide
#

Afganistan I think

buoyant viper
eternal oxide
#

oh a few, Afganistan, algeria, egypt etc

cobalt thorn
#

So than what should i use if this system has a problem?

buoyant viper
eternal oxide
#

and discord

buoyant viper
#

ah yeah u sent http://

#

i got auto-https on

eternal oxide
#

ah

#

oddly it seems the US also has sunday as the first day of the week

buoyant viper
#

yeah

#

knew that one :p

eternal oxide
#

🙂

buoyant viper
#

but almost nothing here really ever like

#

uses? it

#

idk

eternal oxide
#

So if you want monday to always be the first day you need to not use calendar or locale

#
DayOfWeek weekStart = DayOfWeek.MONDAY;
return localDate.with(TemporalAdjusters.nextOrSame(weekStart));```
cobalt thorn
#

I just can ask how i can rework this part of the code and what should i use

eternal oxide
#

you can get teh next time you shoudl run your updater

sullen canyon
#

make a runnable run every a few seconds

#

shouldn't be a big del

eternal oxide
#

I'd just schedule it at startup

#

NOT bukkit scheduler

#

ScheduledExecutorService

cobalt thorn
#

What a coincidence

eternal oxide
#

After reading about the temporal adjuster I'd probably ber a mix of the two

#

use a Scheduled executor but calculate teh Duration using a temporaladjuster

cobalt thorn
#
Bukkit.getLogger().info("Started Event");
        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                Calendar c = Calendar.getInstance();
                if (c.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
                    try {
                        spawn();
                    } catch (Exception ex) {
                        ex.printStackTrace(); // or loggger would be better
                    }
                }
            }
        }, 0, 1, TimeUnit.DAYS);

I made this code reading some of the docs

eternal oxide
#
LocalDate nextDate = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.MONDAY));
Long midnight = LocalDateTime.now().until(nextDate.atStartOfDay(), ChronoUnit.MINUTES);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(()-> { /* Code here */ }, midnight, TimeUnit.DAYS.toMinutes(7), TimeUnit.MINUTES);```
cobalt thorn
#

in my theory should work just fine

cobalt thorn
eternal oxide
#

Not good

orchid trout
#

🍞🦴

eternal oxide
#

your runs every day

#

and once it hits monday yours will call spawn() every tick for the whole day

#

The code I showed calculates teh time between now (server start) and the next Monday. it then schedules to run at that time and not before

cobalt thorn
#

And then should auto restart or i need to reschedule it

#

Recalling the function inside the spawn

eternal oxide
#

you need to change teh 1440 to a week though

#

thats told it to run every day after

#

fixed

shy rock
#

What version is the ideal to make plugings for? That basicly work on feuture versions too

#

1.12.2 ?

eternal oxide
#

Latest

#

is always preferred

unique bay
#

I need help man

#

I always get an error about my jar file not having plugin.yml contained despite

  • selecting to include the file in the jar in the compiler settings
  • the YML file being valid
  • following a tutorial word for word, and it still doesn't work
sage patio
#

What IDE are you using

unique bay
#

intelliJ

sage patio
#

did you installed Minecraft Development plugin?

unique bay
#

yeah

glossy venture
#

check the jar with winrar

#

or an archive viewer

sage patio
#

see if there is an plugin.yml in the main directory or not

glossy venture
#

if youre using gradle or maven your file needs to be in src/main/resources

unique bay
#

there isn't, despite me selecting the option to include it

eternal oxide
#

You are probably using Artifacts instead of the m (maven) tab to the right and running package under lifecycles

unique bay
#

yeah I'm using artifacts

#

should I not?

sage patio
#

its better not

#

do Maven > Lifecycle > install

glossy venture
#

no if you use a build system you should use the build system to build

eternal oxide
#

not install, use package

sage patio
unique bay
#

I'm using gradle

sage patio
#

then build

#

ig

eternal oxide
#

install adds every version of the jar you build to yoru local maven repository

glossy venture
#

then use the build task

#

gradle on the right -> 'build' category -> build

sage patio
eternal oxide
#

package only builds it

sage patio
#

nice, thanks

unique bay
#

I'm just gonna switch to maven

sage patio
#

Gradle is better

glossy venture
#

its not an issue with your build system

#

why would you switch

#

the output jar is in build/libs/

sage patio
#

Just simply click on the 🐘 icon on the right, open build category and double click on build

glossy venture
#

its the same with maven

unique bay
#

there still isn't the plugin.yml, only a manifest file in the build

glossy venture
#

what directory is your plugin.yml in

unique bay
#

src

glossy venture
#

tf

sage patio
#

it should be in the resources folder

unique bay
#

there is none 💀

glossy venture
#

do you have a src/main/java and src/main/resources

sage patio
#

so move it

glossy venture
#

create the directory

unique bay
#

alright wait

glossy venture
#

put your source code in src/main/java and your plugin.yml in src/main/resources

unique bay
#

now it has it

glossy venture
#

lit

unique bay
#

it still does say jar does not contain plugin.yml, does the fact it's named paper-plugin.yml have anything to do with it

glossy venture
#

yes

unique bay
#

lit

glossy venture
#

i think

chrome beacon
#

Paper plugin yml will only work on modern Paper

glossy venture
#

rename it to plugin.yml

unique bay
#

it worked finally

#

thank you babes

quaint mantle
#

?whereami

unique bay
#

i'm lost

sage patio
#

I've this method for restoring blocks and materials into a Map

private final static Map<Block, Material> blocks = new HashMap<>();
public static void loadBlocks() {
        blocks.clear();
        for (String key : NLJobs.getFileManager().getConfig().getConfigurationSection("blocks").getKeys(false)) {
            String[] parts = key.split(";");
            int x = Integer.parseInt(parts[0]);
            int y = Integer.parseInt(parts[1]);
            int z = Integer.parseInt(parts[2]);
            World world = Bukkit.getWorld("world");
            Location location = new Location(world, x, y, z);
            Block block = location.getBlock();
            String materialString = NLJobs.getFileManager().getConfig().getConfigurationSection("blocks").getString(key);
            Material material = Material.getMaterial(materialString);
            if (!blocks.containsKey(block)) blocks.put(block, material);
        }
    }

the data file looks like this:

blocks:
56;50;439: GOLD_BLOCK
...
5963;58;-9757: DIAMOND_BLOCK

how can i store and restore direction too?

eternal oxide
#

neither of those blocks have a direction

chrome beacon
#

^^

sage patio
#

i know the don't

#

but maybe there is a wood block

#

a stair

#

or whatever

chrome beacon
#

56;50;439:
material: CHEST
data: smth

sage patio
#

i should store blockdata?

eternal oxide
#

yes

unique bay
#

yes

eternal oxide
#

for relevant blocks

sage patio
#

can i cast the data string into BlockData?

#

pls don't tell me i should use serializers

chrome beacon
#

^^ I'd use the one that accepts both material and string

#

just in case

eternal oxide
#

yep

sage patio
#

nice

#

thanks

shy rock
#
skeleton.setDamage()
skeleton.setTargetRange()```
Are not vallid ?
agile anvil
#

What

#

We need context

#

And more info

shy rock
#

Basically I want to customize their damage and range

agile anvil
#

Oh

#

You can't change it this way

#

You have to change the behaviour of the entity

#

For the damage you could listen for entitydamageevent

#

For the target range, you'll have to change the sekeleton ai

shy rock
#

Alright thanks

#

I guess it would be easier to just adjust their weapon than the entity it self

drowsy helm
#

iirc it can be set as an attribute

#

yeah

sacred mountain
#

yo

#

how would i go about creating a method that waits for something else before returning a value? im not great with threads and synchronization

drowsy helm
#

what is 'something else'

#

depends on the context

sacred mountain
#

this isn't the minecraft side of the program so it's for an actionlistener or mouse click

drowsy helm
#

if you want to use threads all you really have to do is continously run it every x millis and have an if statement but you should really be using some sort of event method rather than a constant check

#

like some lambda function that is called would be ideal

sacred mountain
#

hm

drowsy helm
#

again, really depends on the specifics of what you are needing to do

round finch
#

i'm clearly doing something wrong

int hour = LocalTime.now().getHour() - hours.get("autovote");
int min = LocalTime.now().getMinute() - mins.get("autovote");
int sec = LocalTime.now().getSecond() - secs.get("autovote");
sacred mountain
#

i was thinking an actionlistener with a synchronized wait() and notify()

sacred mountain
#

the server side has an admin GUI that is a standalone java application

#

the main frame opens a popup which has a bunch of options, i just want to wait for any of said buttons to be pressed before the method returns a value

drowsy helm
#

yeah a lambda function that is called once the button is pressed would probably be best

#

no recursive methods, no useless if checks

sacred mountain
#

how would that work in a method which needs a return

round finch
sacred mountain
#

am i being stupid but wouldnt any sort of listener apply

#

and not actually run before the method has completed

drowsy helm
#

oh so you want to sort of have an await before returning the value

drowsy helm
#

just use time milliseconds

lilac dagger
#

Is it better to have one sqlite file or multiple files performance wise?

flint coyote
#

there is no general answer to that. It depends how often you access which data

drowsy helm
lilac dagger
#

if i was to split the files it would be different tables that i would split

#

so i just wonder if searching is cheaper if the files are per tables

sacred mountain
#
public int openRankPromotionDialogue() {
  JPanel panel = new JPanel();
  // Left out the formatting
  JButton exampleRank = new JButton("ExampleText");
  // Left out visuals
  exampleRank.setAction(new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
      synchronized (exampleRank) {
        exampleRank.notify();
      }
    }
  });

  panel.add(exampleRank);
  // Display panel in frame

  synchronized (exampleRank) {
    try {
      exampleRank.wait();
    } catch (InterruptedExeption e) {
      throw new RuntimeException(e);
    }
  }

  return 0; // a value
}```
#

thats what i have atm

lilac dagger
#

the acces is per player once in a while i guess

drowsy helm
#

for the most part its cached anyways

round finch
lilac dagger
#

hmm, thanks for the help then

drowsy helm
round finch
#

So no?
Period.between(Instant.now(), SomethingTime)

round finch
drowsy helm
#

That wouldn't really be following good programming principles, you should have the buttons execute the promotion function themselves

#

or return a promise

sacred mountain
#

fair enough but i'd rather not rewrite that part, it's got to the point where this is really the only way it'll work without having to recode half of it

#

i'm fairly sure wait() and notify() work but i'm unsure of how to properly implement as the above code doesnt work

#

just lags out

#

oh and i should mention that the buttons sometimes aren't used for instant promotion they can be saved as promotion presets

drowsy helm
#

pretty sure you should just be calling
wait()
not
exampleRank.wait();

#

same with notify

sacred mountain
#

🫠

#

i swear

#

if thats why

karmic mural
#

Sometimes it's so obvious you don't think of it, don't let it keep you up at night

drowsy helm
#

but either way i still think that wont work since wait is on another thread

#

the return will still fire

#

theres no way of delaying the return without pausing the main thread

sacred mountain
#

i can just create another thread

#

Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException: current thread is not owner
bro what

#

never seen that before

drowsy helm
#

sorry no i was incorrect

#

exampleRank.wait(); is correct

sacred mountain
#

ah ok

sacred mountain
#

uh oh just got 32 fatal errors :)

#

LET GO A DIFFERENT ERROR

eternal oxide
#

It sounds like you want to get a rank from somewhere slow, then apply it when it returns.

#

You can;t wait on the response, but you can use Futures to run code once it returns

tardy delta
#

wait sets are hard to debug

sacred mountain
#

i did it

sacred mountain
#

JOptionPane#showOptionDialogue()

eternal oxide
#

what specifically are you making wait?

#

ah

#

I was expecting somethign Spigot

sacred mountain
#

ignore the scuffed jlabels

glossy venture
#

why is 0b100 | 0b0001 resulting in 0b101

eternal oxide
#

it won't

glossy venture
#

reacting to me?

eternal oxide
#

yes

glossy venture
#

because i tested it and it does

eternal oxide
#

I guess your testing is flawed

glossy venture
#

if i do 0b1000 | 0b0001 does result in 0b1001

#

but 0b100 | 0b0001 results in 0b101

glossy venture
#

yeah

#

thats normal

eternal oxide
glossy venture
#

??

#

0b101?

eternal oxide
#

just open a scientific calculator

#

no it's an or

#

so 0b100 | 0b0001 = bb101

glossy venture
#

i guess java is just weird or smth

smoky anchor
#

no ?

eternal oxide
#

you are casting to byte

hybrid spoke
#

you are

smoky anchor
glossy venture
#

yeah so

smoky anchor
#

I don't see what you don't understand

glossy venture
#

its big endian so it will just truncate the zeros

smoky anchor
#

the leading zeros are ignored

glossy venture
#

one leading zero is ignored

eternal oxide
#

a byte doersn;t have the capacity of 111111

smoky anchor
#

He's manipulating 4 bits

eternal oxide
#

um

glossy venture
#

all i know is that java gives
0b100 | 0b0001 = 0b101
0b1000 | 0b0001 = 0b1001

smoky anchor
#

Would C not do the same ?
What do you expect

hybrid spoke
#

which is correct

glossy venture
#

bruh wdym

#

i expect 0b10000000 | 0b00010000 = 0b10010000

smoky anchor
#

but that should happen ?

glossy venture
#

it doesnt when i use 0b100 as the left operand

smoky anchor
#

Yes

#

try to translate them to deciman

glossy venture
smoky anchor
#

0b10000000 = 128
0b100 = 4

quiet ice
#

What is your issue?

glossy venture
#

tf

smoky anchor
glossy venture
#

fancy names?

quiet ice
#

All leading zeros are useless for OR

smoky anchor
smoky anchor
glossy venture
#

if java is big endian

0b1    = 1
0b1000 = 1

right

smoky anchor
#

no

quiet ice
quiet ice
glossy venture
#

wtf so java is little endian

quiet ice
#

Everything is LE these days

smoky anchor
#

Are you sure you don't have your defenition mixed ?

glossy venture
#

some site said java was big endian

smoky anchor
#

Google says big endian

glossy venture
#

in which case the first bit always is 1

#

but that doesnt seem to be true

quiet ice
#

But uh, it shouldn't matter qnyways

eternal oxide
tardy delta
quiet ice
#

The LE/BE diff only matters if you encode decimal numbers

eternal oxide
#

oh sorry, notation missed

quiet ice
#

For binary numbers it does not matter at all

#

BUT everything is LEFT-padded

glossy venture
#

no i know

#

ok

quiet ice
#

Like it should be

#

Right-padding makes no sense in the modern (LE) world

glossy venture
#

yeah exactly but i thought java was big endian

#

so i thought 0b100 or 0b1000 didnt matter

quiet ice
#

Perhaps the JVMS is BE

#

But the JLS and all java APIs are LE

glossy venture
#

weird

#

ok thanks

quiet ice
#

Though probably the JVM smartly chooses between BE and LE depending on the CPU and only converts on an as-needed basis

sullen canyon
#

can I somehow force players to send interact packets?

young knoll
#

You can force them to swing their hands

#

And just run whatever code is run when they do send interaction packets

sullen canyon
#

O nice, how can I do this?

young knoll
#

Depends what you want to do

#

You could manually fire an interact event I guess

mortal hare
#

Little endian for the win

#

big endian is mostly used in networking afaik

kindred valley
#

How to add item to smithing table

worldly ingot
#

Depending on where you want to add it, Inventory#setItem() should work just fine

unique bay
#

does anyone know how I can reference a .json file from resources into my main java file?

young knoll
#

Plugin.getResource

unique bay
# young knoll Plugin.getResource
    public class playerJoin implements Listener {
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            Player p = event.getPlayer();
            @NotNull UUID playerID = p.getUniqueId();
            public abstract Plugin.getResource(
                    String "database.json"
            );
            if playerID
            System.out.println(p.name() + "Has joined with a UUID of " + playerID);
        }
    }```
#

not sure about it

worldly ingot
#

I'm not sure about 50% of that snippet

unique bay
#

me neither

worldly ingot
#
            public abstract Plugin.getResource(
                    String "database.json"
            );
            if playerID```
This is not valid Java at all
unique bay
#

I wanna know how I can implement data from a .json file in my resources folder

worldly ingot
#

You will need an instance of your plugin class. From there you can invoke the getResource() method which will get you an InputStream from which you can read

unique bay
#

like java URL resourceURL = getClass().getResource("/database.json"); if (resourceURL != null) { try (InputStreamReader reader = new InputStreamReader(resourceURL.openStream())) { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonElement jsonElement = JsonParser.parseReader(reader); }
this?

worldly ingot
#

getClass().getResource() might not get you exactly what you want. There's a getResource() method from JavaPlugin

#
public class PlayerJoinListener implements Listener {

    private final Plugin plugin;
    private final Gson gson = new Gson(); // If you want to read JSON, Gson is a must

    public PlayerJoinListener(Plugin plugin) {
        this.plugin = plugin;
    }

    @EventHandler
    private void onJoin(PlayerJoinEvent event) {
        InputStream stream = plugin.getResource("my_file.json");
        JsonObject object = gson.fromJson(new InputStreamReader(stream), JsonObject.class);
        // You can do whatever you want with the object now
    }

}```
#

I wouldn't necessarily recommend synchronously reading and parsing the JSON file every single time a player joins, you're going to inevitably halt your server and cause performance issues, but this would work in theory

ancient plank
#

Wait

unique bay
#

in my case I'm just trying to make some sort of playtime function for my first plugin, where as a player joins it checks if their UUID is in the database, then checks for their playtime and saves when they join, and when they leave

worldly ingot
#

Oh, definitely a big nope for a database there. Again, you would have to read and parse the whole file for that

unique bay
#

I'm not too familiar with working with java here so I don't really know where I would store that data

worldly ingot
#

Say you have 1,000 unique players. You would have to read and parse all 1,000 entries and load them into memory to only get one of them

#

Because you can't* pick and choose which area of a file you want to read from

unique bay
#

what would you recommened to be a better way to get the data?

worldly ingot
#

Some form of SQL or NoSQL database would be ideal. Though if you have no experience with SQL at all, the preferred alternative would probably be per-user files

chrome beacon
#

Vanilla already saves playtime though 🤔

worldly ingot
#

That as well

ancient plank
#

all my homies use per-user files*

#

* (I don't have homies)

#

woah

unique bay
unique bay
unique bay
#

I'll work on understanding how to properly use per-player files

ancient plank
#

You just create a separate json/any file using the uuid of the player and voila you've got a per-user file

unique bay
worldly ingot
#

Not terribly difficult. You're just creating and reading from files that are named after the player's UUID

#

e.g. 73c62196-2af7-463d-8be1-a7a2270f4696.json

unique bay
#

yeah I know that much, just the process of actually creating and reading from the files

ancient plank
unique bay
#

I've never used Java before this project

worldly ingot
#

Yes

#

You could definitely look up some tutorials on reading/writing files for just vanilla Java here 🙂

unique bay
#

pfft who needs tutorials anyway..-

worldly ingot
#

For your convenience, JavaPlugin provides you with your own data directory using plugin.getDataFolder()

#

Gives you a FIle object where your config.yml and whatnot would be stored

ancient plank
#

I can never specifically remember the java classes for it so I just go check google for smth simple to refresh my brain ngl

#

worst memory ever

worldly ingot
#

They get imprinted in your head after using them for a few years

ancient plank
#

it's been a few years

unique bay
#

last time I needed help I asked for something very simple, and I got linked to a 30 minute long video (that didn't even have what I needed)

ancient plank
#

it's because I don't do it very often, usually once or twice in a span of a couple months

unique bay
#

turns out I just needed to press a different button

ancient plank
#

welp time to code since I have nothing to do today

flat ruin
unique bay
#
    public class playerJoinListener implements Listener {
        @EventHandler
        public void onPlayerJoin(PlayerJoinEvent event) {
            Player p = event.getPlayer();
            @NotNull UUID playerID = p.getUniqueId();
            File f=new File(getDataFolder(), playerID + ".yml");
            @NotNull YamlConfiguration config;
            if(f.exists()) {
                config = YamlConfiguration.loadConfiguration(f);
            }
            else try {
                f.createNewFile();
                config=YamlConfiguration.loadConfiguration(f);
                } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(p.name() + "Has joined with a UUID of " + playerID);
        }
    }
#

something more like this?

unique bay
quaint mantle
#

is there an event for command executions?

flat ruin
#

bruh no WAY

flat ruin
unique bay
#

because I'm not exactly sure what I should be doing yet

#

annonating it where?

quaint mantle
flat ruin
#

@NotNull YamlConfiguration config;

unique bay
#

what should I be doing instead

chrome beacon
quaint mantle
#

so onCommandExecution

#

or like that

flat ruin
#

you'd use that exactly