#help-development
1 messages · Page 542 of 1
public void moisture(MoistureChangeEvent e) {
e.setCancelled(true);
World world = e.getBlock().getWorld();
if (!(world.isClearWeather())) {
e.setCancelled(false);
}
}```
you need to detect if the block is near a watering block, and only water below a certain level.
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
have you got the correct world name this time?
yes lol it was the first thing I checked after yesterday's incident
sysout the block location
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"
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
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
you are setting a velocity of just under 13
Ehh, iirc rgb might not be possible on score names
can i check if blocks gets hit by a water ( i mean rain water ( particles ) )
Are there any possible ways as I have seen other plugins using hex codes or rgb for that
Uhh, and what about that?
https://www.spigotmc.org/threads/1-16-1-19-scoreboard-objective-score-with-rgb-hex-color.468079/
hacky as fuck
I believe 10 is the max velocity per tick
I have no idea about velocity
Rn I'm multiplying it by 8.05
arrow.setVelocity(player.getLocation().getDirection().multiply(8.05));
then reduce your multiplier
Is there no other way?
It's still throwing that warning
No
flame mojang for not providing component support in scoreboard scores
teh max may be lower, like 4, I read it was 10
so try 4
direction is a unit vector
so multiply by 4 should give the max velocity
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
Isn't LiveOverflow that yt channel with that german guy who likes to hack minecraft in different ways? Or am I thinking of something wrong?
That is correct, yes
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..
That seems to be fast enough and doesn't trigger the warning, thank you very much
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)
well like I said, I dont care about what it spawns
I just need it visually
for inventory
Not without a resource pack
sad
AFAIK atleast
I wish teams supported rgb. Mojang pls.
teams ? 
team names do
scoreboard teams still have a preset colour set
just not the scoreboard easily
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
oops
i kinda just copied and pasted my old code and changed it a bit
but is that the issue?
maybe ™️
lemme test
wow that was the issue. appreciate it
How can I make a variable that applies to one specific player?
a variable to do what?
Do you know of any good online tutorials on how to do that?
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
Sure. Just use a Hashmap with either time left or bantime and adjust it whenever you need
Yeah you could but you'd still require a map
like Player --- Time
explain what you are trying to do and we can give better advice
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
ok does this persist between player relog or server restarts?
save it on the player
good idea
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
im gonna have to play with that according to the lag
adding/subtracting will be simple as you are just updating the value already on the player
?pdc
Thanks
when the player joins for the first time should I just set the time and save
if they don't already have a time, yes
How can I use a for loop to loop through the different UUID values in a hashmap?
nvm
map.entrySet().forEach
Whats the best way to find a memory leak in a plugin
experience
how to use Tag ?
see if your memory usage goes up over time
if it doesn't
Meh probably not a memory leak
naw ik it has one
if it does probably a memory leak
im saying to find what it is
you're probably not emptying a map or something when people leave etc
look at lists and maps
usually they're the source
this is what I have so far, how should I go with this?
should I set a time variable at the beginning and have getter settter
What about just setting players kick time as a Unix Timestamp and loop thorugh all online player data and if it's passed then kicking them
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
yeah you can change it as you want
uhh I have no idea what you mean lol
linguistically or technically?
because i'm not native
Could be why it doesn't exist then.
everymineut or 5, you decide
new BukkitRunnable() {
@Override
public void run() {
//methods
cancel();
}
}.runTaskTimer(plugin, 1, 1);
like this im guessing
yeahh
but i think incresaing the interval might be better
because you are checking 20 times in a second now
oh rlly
I kind of need this because I dont want anyone to evade their ban or something
how would that look like?
replace the last 1 with 72000
new BukkitRunnable() {
@Override
public void run() {
//methods
cancel();
}
}.runTaskTimer(plugin, 1, 72000);
by this, the task is checking the players in every minute
yes I see
but when it created it immideaditly checks (the first value is the delay)
should I put this snippet in what type of class (like event class command class etc)
You can run it JavaPlugin#onEnable
sweeet
or you can create a extra class for this
I dont want to rlly
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
oh nice!
now that I have that
where would I create the time and save it
when the player joined im guessing
how would you store the data?
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
Is there a plugin makes fake player so I can test the player damage event?
yeah
ok so now where do I decresetime
there is no player damage event
sorry I meant Death.
you won't
you can get the current unix timestamp by System.currentTimeMills()
can't you die yourself?
could you show that to me in code (an example)
@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
In that case no, you can't test it without a second account or online-mode false
So I need to play with two accounts to test it?
will there be 2 version according to the player joining first time and player joining second time
yes
Or you fire the event yourself
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
use tlauncher
idk actually
WE COULDVE DONE THAT'
its not play time, it's a death clock. you gain time by killing, lose it for being killed
like that
saves the day
It would probably be easier for you to read and understand using Instant
dont exist
dude you need to implement your own way
fi=gured it oyut
check is in onenable so I can put a forever loop
Instant expires = Instant.now().plus(1, ChronoUnit.HOURS);
//put on pdc
expires.toEpochMilli();```
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
reading it from the pdc you take the long and java Instant expires = Instant.ofEpochMilli(/* pdc value */);
a gobal field called plugin inthat class is null
you can then check if it's expired by expiresjava if (Instant.now().isAfter(expires))
oooh
yeah using instant is also good way
This is the only thing i have reolving plugin
private static OverhaulWeapons plugin;
but the main thing you need to get storing them not creating
do you set it anywhere
true but lets create it first tho
*set timer
is there a line onEnable for initialazing it
I mean I have this
public static OverhaulWeapons getPlugin() {
return plugin;
}
okay, do you set the plugin instance inRogueRunner to that
here I set to 10
I dont know what you mean.
?paste your main class and the rouge runner class
that toEpoc bit needs to be put on the players PDC
OH
it basically converts the expires value to a Long you can store on the PDC
in your rouge runner class you never set you plugin instance
and you don't have to
?di or add = OverhaulWeapons.getPlugin()
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
just use it from the OverhaulWeapons#getPlugin
omg
this commands are interesting though lol
no
new NamespacedKey(plugin, "death_clock")
ohh my bad yeah you need to give a name first
you then use that key to store your expires
pdc.set(key, type...LONG, expires.toEpocMillis())
expires.toEpocMillis()
death_clock all lower case
alr
you may want to create that key as a field, you'll be using it a lot
ok
so a class level variable
not in onEnable
oh
no players online then, unless it's a restart
that is true but I could do onenable then check if player on line or for every play if onlione or smth
why do you want to do something in onEnable?
I just thought it might work lol
Not sure what you are trying to do
i wanna decrease time / check time and save the time
um, you'd not do any of those in onEnable
oh lol
in your onEnable you start your repeating task is all
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
samsung notification noise
so all you do is compare the current time to it to see if you reached it yet
but the server restarts tho...
doesn;t matter
ok makes sence
its a future time saved on teh player
yes, and compare
comapre meaning if player time 0 or less than ban
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
alright thanks
can I make this static
you could
ayy
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
I should do that
would keep it clean
then you'd have static methods for hasExpired, addTime and subtractTime
also add one for setTime
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
this line isnt going in the util class
My code works 😄
evry tick I need to check if player should be banned or not where do I do that
I'd not do it as precise at every tick
second?
at most every minute or a few seconds
i don't understand how can i use tags ? 😢
alright but where would I do that
i did but i got some warnings
in your repeating task
my runnable
yes
türk müsün la
yep
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.
ekle özelden
Can I put this in on enable
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
yessir
Learn how to use the config.yml! Finding known and unknown values from the config.yml file :)
------ Links ------
Download Eclipse: https://www.eclipse.org/downloads/packages/release/2019-03/r/eclipse-ide-java-developers
Download Spigot: https://getbukkit.org/download/spigot
Build Spigot: https://www.spigotmc.org/wiki/buildtools/
Starting S...
^^^^^ this guy
danke
whyd you ask
I'm having a play writing a utils class for it
Would an empty entry give you an empty list?
it got me interested 🙂
or should I add a - with no entry
oh
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
yes
Can you somehow get all item containers in the server?
runTaskTimer not runTaskLater
All chests etc etc
An empty entry in a yml entry
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
yep
can I get a list of online players and check if they are expired or not
Expired?
returns array?
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?
a util class if you want to use it. Do with as you like https://paste.md-5.net/ohiwipagor.java
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
how do I ban the player
ban then kick
Player#ban I think
thats depricated
could you give a usage?
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)
Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName());
.NAME not .IP
oh lol
sender.getUniqueId().toString()
what is sender
Player
oh ok
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?
Bukkit.getBanList(BanList.Type.NAME).addBan(p.getName(), "bro died out of old age in MINECRAFT lmaooo", null, p.getName());
p is player btw
not name use their UUID
You could compare player velocity and their Y value over the last few seconds to determine if they were falling.
addBan(p.getUniqueId().toString(), "Clock ran out", null, null)
String.valueOf(p.getUniqueId())
I gave you exactly what you need
thanks
alright the rest should be a breeze
when they place water check if they're above it and if they land in it later
How long should I delay before I check to see if the player landed in the water?
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
idk
do some tests
how is that different from a normal wifi network
So like a provider you have to pay and a hotspot on yo phone is going to have a poor connection and it will keep disconnecting if nobody else is using it
sure
well you have to pay someone
of course you'll have no connection
because you're using someone's infrastructure
this is true you can have a free wifi network that only lets you do lan stuff
you can make a fake wifi network that only sees what is in the network
and no internet
Is it possible to make your own network provider
if you have money for it sure
But how do you do that
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
and get one of those 4g sim card routers or something
I think we all as a kids questioned that hahahahag
real
Yeah lol
If am rich I’ll probably make my own WiFi network and service
ikrrrr
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
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.
I am getting this error from my plugin: https://paste.md-5.net/kofotinumo.pl
Here is my Main code: https://paste.md-5.net/dewikumozo.java
Here is my code for PlayerWaterBucketEmptyEvent: https://paste.md-5.net/bijeriqapa.java
That error normally shows up when you have more than one JavaPlugin instance.
My runnable wants a value Plugin, what do I put there?
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
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
@quaint mantle can you show me some of your code that involves dependency injection
tysm
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;
}`
.toEpochMilli()
just do java return pdc.getOrDefault(key, PersistentDataType.LONG, Instant.now().toEpochMilli());
Dependency injection eliminates the need for the static keyword. The static keyword is also seldomly used in spigot plugins anyways.
Its already a Long in the PDC
since 1970
refer to this
what if the number is too long for the long tho
10 hours is 3.6e+7
it won;t be
That doesn't sound right.
many years go in a long
oh dang
it's capacity is exponentually bigger with every bit
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
The neat thing about relative time is that it can be stored in a number of ways. It just depends on how you want to read the data.
static is useful
WAIT long's limit is 2147483647 Which is 20:36:23 ---> 20 hours 36 minutes 23 seconds...
welp
I don't think that there has been any project by a beginner that didn't deserve a rewrite after he improved his skills
Again, it comes down to how you store and read the data. You can store mellenia if you really wanted to.
How are you currently storing that data?
milliseconds --> long
Ok, now how are you reading it?
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
Just wondering, why are you using Instant.now() instead of System.currentTimeMillis()?
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)
Wtf, why are you compiling in a terminal?
you can;t put a long into an integer
Also that ^
whats wrong?
Nothing really, just surprised to see it as I hardly ever see anyone do that.
No, that's the MAX_VALUE of a long. 😛
yo how would I access playerInteractionManager in nms
Although your compiler thinks it's assigned as an int for some reason.
oh lol
how do I automatically generate and deploy sources for my api
\
idk how to use the maven source plugin
goofy terminal
what exactly are you trying to do?
replit 👎
turn milliseconds to formatted time
What format specifically?
use the instant, it's simpler https://www.baeldung.com/java-instant-to-string
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);
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.
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
What you are wanting is Duration as you only want the difference between Instant.now() and your getTime. https://www.tutorialspoint.com/how-to-get-the-duration-between-two-instant-timestamps-in-java
OHHH MAKE SENSE
I'd actually use the second one, the until method
it's better fitting with Instants
it finds seconds tho
^^^^
finds setting?
seconds
only if you ask for them
rlly
look at teh second link I gave you
1
2
3
long noOfSeconds = instantBefore.until(instantAfter, ChronoUnit.SECONDS);
long noOfSeconds = instantBefore.until(getTime(p), ChronoUnit.MILLIS);
Instant.now().until(getTime(player), ChronoUnit.MINUTES);
Instant.now().until(getTime(p), ChronoUnit.MILLIS);
ok so this is my time
in milliseconds
cuz it says millis
yes, if you want it in milli
so it returns long so I have to use something other than instance formatter
I have to use long formatter
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
could this work tho
looks like it would
you could do away with the duration
just do teh math on frt
oh no you couldn't
ignore me 🙂
It is posible to disable cobweb slowdown for mobs?
How can I make a fake WiFi network on my phone
Am in Mexico am just trying to test it out
whats does this have to do with spigot lol
Idk
we are not going to help in scamming people -.-
Bruh am in Mexico and the only house by me is abandoned
vpn
so you say.
any good title api for actionbar
What ??
is it permanant and automatically updates if I have added a variable in there?
what?
No, you would have to re-send the action bar
You'd need to have a phone that has a wifi card with monitor mode
oof
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
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
mvn clean package will get you a build
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.
?paste
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"
Get time with LocalDateTime
You can use this for CurrentTime
Line?
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
I should do them as long or what?
You mean change it from a primitive object to an int
what
Integer to int
exactly, but there is no primitive object
Nothing else as a problem because i don’t see i stared to the code for hours but nothing else like as a problem
well, today is not the second day of the week
That check for the next monday
also monday is not the second day of the week
What should i use then?
wtf country makes monday the third day
Afganistan I think
hmm
So than what should i use if this system has a problem?
what
👀
🙂
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));```
I just can ask how i can rework this part of the code and what should i use
Wait the dude is trying to make something similar to mine so it should work the same lol
What a coincidence
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
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
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);```
in my theory should work just fine
@eternal oxide sorry for the ping but should be the same code as yours
Not good
🍞🦴
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
Ok thanks for the help
And then should auto restart or i need to reschedule it
Recalling the function inside the spawn
you need to change teh 1440 to a week though
thats told it to run every day after
fixed
What version is the ideal to make plugings for? That basicly work on feuture versions too
1.12.2 ?
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
What IDE are you using
intelliJ
did you installed Minecraft Development plugin?
yeah
see if there is an plugin.yml in the main directory or not
if youre using gradle or maven your file needs to be in src/main/resources
there isn't, despite me selecting the option to include it
You are probably using Artifacts instead of the m (maven) tab to the right and running package under lifecycles
no if you use a build system you should use the build system to build
not install, use package
what is the difference?
I'm using gradle
install adds every version of the jar you build to yoru local maven repository
oh yea so thats why i see 3 or 4 type of .jar files
package only builds it
nice, thanks
I'm just gonna switch to maven
Gradle is better
its not an issue with your build system
why would you switch
the output jar is in build/libs/
Just simply click on the 🐘 icon on the right, open build category and double click on build
its the same with maven
there still isn't the plugin.yml, only a manifest file in the build
what directory is your plugin.yml in
src
tf
it should be in the resources folder
there is none 💀
do you have a src/main/java and src/main/resources
so move it
create the directory
alright wait
put your source code in src/main/java and your plugin.yml in src/main/resources
now it has it
lit
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
yes
lit
i think
Paper plugin yml will only work on modern Paper
rename it to plugin.yml
?whereami
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?
neither of those blocks have a direction
^^
56;50;439:
material: CHEST
data: smth
i should store blockdata?
yes
yes
for relevant blocks
can i cast the data string into BlockData?
pls don't tell me i should use serializers
yep
skeleton.setDamage()
skeleton.setTargetRange()```
Are not vallid ?
Oh
You can't change it this way
declaration: package: org.bukkit.entity, interface: Skeleton
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
Alright thanks
I guess it would be easier to just adjust their weapon than the entity it self
iirc it can be set as an attribute
declaration: package: org.bukkit.attribute, enum: Attribute
yeah
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
this isn't the minecraft side of the program so it's for an actionlistener or mouse click
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
hm
again, really depends on the specifics of what you are needing to do
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");
i was thinking an actionlistener with a synchronized wait() and notify()
client server stuff
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
yeah a lambda function that is called once the button is pressed would probably be best
no recursive methods, no useless if checks
how would that work in a method which needs a return
how i calculate time beteewn?
past time and now
am i being stupid but wouldnt any sort of listener apply
and not actually run before the method has completed
oh so you want to sort of have an await before returning the value
what are you attempting to do?
just use time milliseconds
Is it better to have one sqlite file or multiple files performance wise?
there is no general answer to that. It depends how often you access which data
theres pros and cons to both
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
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
not ncessesarily
the acces is per player once in a while i guess
for the most part its cached anyways
i want to have a list of things after a certain time has reach it will do that
and reset the timer
hmm, thanks for the help then
yeah just use time milliseconds it'll make oyur life far easier
So no?
Period.between(Instant.now(), SomethingTime)
How exactly do you wanna use milliseconds like that?
oh so the return will be the rank they want to promote to?
That wouldn't really be following good programming principles, you should have the buttons execute the promotion function themselves
or return a promise
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
pretty sure you should just be calling
wait()
not
exampleRank.wait();
same with notify
Sometimes it's so obvious you don't think of it, don't let it keep you up at night
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
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
ah ok
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
wait sets are hard to debug
i did it
i can wait actually
JOptionPane#showOptionDialogue()
ignore the scuffed jlabels
why is 0b100 | 0b0001 resulting in 0b101
it won't
yes
because i tested it and it does
I guess your testing is flawed
if i do 0b1000 | 0b0001 does result in 0b1001
but 0b100 | 0b0001 results in 0b101
This results in BB101
no ?
you are casting to byte
you are
that does not change anything
yeah so
I don't see what you don't understand
its big endian so it will just truncate the zeros
the leading zeros are ignored
one leading zero is ignored
a byte doersn;t have the capacity of 111111
He's manipulating 4 bits
um
all i know is that java gives
0b100 | 0b0001 = 0b101
0b1000 | 0b0001 = 0b1001
Would C not do the same ?
What do you expect
which is correct
but that should happen ?
it doesnt when i use 0b100 as the left operand
its big endian right
0b10000000 = 128
0b100 = 4
What is your issue?
tf
idk those fancy names for stuff lol
I just know how it works
fancy names?
All leading zeros are useless for OR
big, little edian
all leading are useless. Period.
no ?
if java is big endian
0b1 = 1
0b1000 = 1
right
no
Two's complement
0b1 = 0x0001
0b1000 = 0x008
wtf so java is little endian
Everything is LE these days
Are you sure you don't have your defenition mixed ?
some site said java was big endian
Google says big endian
But uh, it shouldn't matter qnyways
he's not manipulating 4 bits, he's using hex so he is using 3 bytes
0b is for binary
The LE/BE diff only matters if you encode decimal numbers
oh sorry, notation missed
yeah exactly but i thought java was big endian
so i thought 0b100 or 0b1000 didnt matter
Though probably the JVM smartly chooses between BE and LE depending on the CPU and only converts on an as-needed basis
can I somehow force players to send interact packets?
You can force them to swing their hands
And just run whatever code is run when they do send interaction packets
O nice, how can I do this?
How to add item to smithing table
Depending on where you want to add it, Inventory#setItem() should work just fine
does anyone know how I can reference a .json file from resources into my main java file?
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
I'm not sure about 50% of that snippet
me neither
public abstract Plugin.getResource(
String "database.json"
);
if playerID```
This is not valid Java at all
I know that much, I'm not sure how to implement what he said
I wanna know how I can implement data from a .json file in my resources folder
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
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?
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
Wait
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
Oh, definitely a big nope for a database there. Again, you would have to read and parse the whole file for that
I'm not too familiar with working with java here so I don't really know where I would store that data
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
what would you recommened to be a better way to get the data?
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
Vanilla already saves playtime though 🤔
That as well
I wanted to do this but I have less of a clue about this
dw i'm your homie
never touched SQL tbh
I'll work on understanding how to properly use per-player files
You just create a separate json/any file using the uuid of the player and voila you've got a per-user file
yeahh but I'm working for experience, not useful plugins
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
yeah I know that much, just the process of actually creating and reading from the files
did you just go to namemc to get your uuid
I've never used Java before this project
Yes
You could definitely look up some tutorials on reading/writing files for just vanilla Java here 🙂
pfft who needs tutorials anyway..-
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
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
They get imprinted in your head after using them for a few years
it's been a few years
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)
it's because I don't do it very often, usually once or twice in a span of a couple months
turns out I just needed to press a different button
gotta get used to it
welp time to code since I have nothing to do today
I feel this
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?
the fact i have finals and still choosing to code because i can't be bothered
is there an event for command executions?
Why are you annotating @urban grotto here
bruh no WAY
Yes when you register the command
like java public void onCommandSomething(commandThing event) { } on command execution
@NotNull YamlConfiguration config;
what should I be doing instead
If you want to listen to another plugins command use the PreProccess event
nah I want to make something like command logger for dc
so onCommandExecution
or like that
you'd use that exactly
declaration: package: org.bukkit.event.player, class: PlayerCommandPreprocessEvent