#development

1 messages · Page 44 of 1

dense drift
#

I will play around with this, thank you Emily

#

Can I use a different version of java for the test module than the one from main?

broken elbow
#

pretty sure you can. In gradle you would set sourceCompatibility in compileJava and CompileTestJava

minor summit
#

ew source compatibility

#

release flag my beloved

broken elbow
#

how'd you use that?

dense drift
#

oh nice

#

I hope this is good and it will work as intended 🤣

minor summit
#

to run tests on a different version you'd use the toolchain stuff

#

and there are some test properties to define the toolchain to use

#

i don't recall where those are, never used it

dense drift
#
    compileTestJava {
        options.release.set(17)
    }```
This worked fine
minor summit
#

that's only for compiling, not running

dense drift
#

well since it accepts var in src/test I'd say it worked?

minor summit
#

sigh

dense drift
minor summit
#

it is compiling against java 17 yes

dusty frost
#

is this in-memory?

minor summit
#

and the toolchain used has to be 17 or greater for that to work

dense drift
#

ah okay

dusty frost
#

cause if it's using any external data store that's not just like plain files, that definitely has its own transaction logic to be ACID compliant

dense drift
#

if you are talking about my stuff, yes, transactions are stored in memory
transaction might not be the perfect works to describe this but it represents the situation when a player attempts to buy an item

dusty frost
#

you're not persisting the item amounts or the transaction history?

dense drift
#

the Transaction objects holds info about the player, the item and the amount

#

hm, I might make some sort of logging at some point

dusty frost
#

but like, if the server crashes or shuts down, there's new stock of items?

spiral prairie
#

i think gaby hasnt thought this through all the way

dense drift
#

ah no, the amount will persist between restarts until the next restock

dusty frost
#

in what way will this amount persist

spiral prairie
#

so you cant store it in memory

dense drift
#

the shop data will be saved in a database probably, I haven't decided yet

spiral prairie
#

thats another problem then

dusty frost
#

okay well, this is exactly the kind of system that needs a centralized database

#

as in, you design everything around the database's transaction locking to ensure consistency

#

and record every transaction, etc. etc.

#

this is absolutely not the kind of thing you do in memory all willy nilly and only rarely write to database

dense drift
#

that's actually a fair point, mhm

dusty frost
#

i am quite literally designing a very similar system for my server network currently lol

#

though mine is centralized on a website backend that talks to the database, rather than directly

#

but similar point, you definitely want transaction integrity if anyone is going to trust their purchases or balances or whatever

dense drift
#

yeah I will document myself more about how to do this with a database

#

brb now I'm going to take a shower

spiral prairie
#

i remember some kid paying a guy $200 for developing such a system in Minecraft but with real crypto coins that cost actual money
guess what: the kid lost about 20k (not really but thats what it would have costed the players) due to a bug in database saving allowing the players to access their values up to 100 times KEKW_laugh

#

man the crypto boom was crazy

#

just depend on the fact that databases can lock themselves and pray you wrote a good implementation

#

idk how multiple connections would work there but

broken elbow
#

I still can't believe it is dead ngl. It lasted way too long

spiral prairie
#

nfts were crazy too

dense drift
#

Crypto should have remained a currency used by drug dealers 🤣

broken elbow
spiral prairie
#

nah

spiral prairie
#

crypto is pretty cool for sending money

#

not for exploiting kids

torpid raft
#

crypto is great as a replacement for cash imo

spiral prairie
#

^^

#

especially monero

torpid raft
#

monero is ungodly based

dense drift
minor summit
spiral prairie
#

on second thought that makes sense, i just havent worked with databases in such a long time

dusty frost
#

might be a little scary if you use like higher level ORMs and stuff, but if you just do a straight up like pl/pgsql impl it will be great

#

stored procedure is the word i was looking for there

spiral prairie
#

cool cool

dense drift
#

I guess sqlite has locking function? D:

dusty frost
#

i mean it has transactions

#

i wouldn't recommend sqlite for this kind of stuff though lol

#

doesn't do great with multithreading iirc

dense drift
#

ok any suggestions for a local db?

#

maybe h2? idk if that's advanced than sqlite or <=

dusty frost
#

you're not gonna get any kind of synchronization stuff with a local db

#

you need a dedicated server that can do all the synchronization stuff

dense drift
#

hmm, okay

#

do you have any resources I can read for this? I don't really know what to search for tbh 😬

dusty frost
#

database transactions

dense drift
#

thanks Star

#

seems pretty simple from their bank example, now I need to see how to implement this in my project

dusty frost
#

should not be that hard

#

whatever SQL thing you're using should have it

#

and if you're just using raw JDBC prepared statements, you can just do a multiline thingy like that iirc

#

might have to do separate ones, that might be a bit weird

#

okay nope they have special shit

dense drift
#

yeah

minor summit
#

poop

spiral mural
#

Quick question, can I leave getCommand("").setExecutor(new CommandManager()); empty? I want the args[0] to handle as labels

dense drift
#

no

#

if you want to override commands or something like that, use the command process event

spiral mural
#

havn't touched it before, but I assume something like this ? ?``` @EventHandler
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String[] args = event.getMessage().split(" ");

    if (args[0].equalsIgnoreCase("/command")) {
        event.setCancelled(true); 
        
    }
}```
dense drift
#

yeah

tired olive
#

if you're on paper you can easily access it through the server

#

if ur on spigot ull have to use reflection tho

proud pebble
#

to some non spigot place

minor summit
#

no, paper exposes the commandmap in the api, spigot doesn't

proud pebble
#

then why would reflection be required?

minor summit
#

because spigot doesn't expose a getter

#

so you need to use reflection to get it

proud pebble
#

oh cus every point is under protected or private methods/fields?

minor summit
#

huh

#

Paper adds a Server#getCommandMap() method, Spigot does not have that, so to get the command map on Spigot you have to use reflection

proud pebble
#

the command map is still somewhere

minor summit
#

Yes

#

The field is in the same place

#

Paper simply adds a getter in the API

proud pebble
#

by that im taking it as the command map is a single variable, with no getter and is private, meaning the only way to access said variable is through reflection? is that right?

karmic bison
#

Hello, is it possible to parse a placeholder in a TextComponent using PlaceholderAPI ? If yes how can I do it ? And if no, is there a workaround to convert my TextComponent to a String so that I can use #setPlaceholders() and then put it back into a TextComponent ?

dense drift
#

LegacyComponentSerializer#serialize

karmic bison
#

oh okay

dense drift
#

Actually, GsonComponentSerializer to preserve the click events and hover

stuck hearth
#

So true

karmic bison
#

makes sense now that you say it

karmic bison
dusky harness
#

BUT

#

oh

#

ok

stuck hearth
#

Mm doesn't go to string boingus

dusky harness
#

yes it does

#

minimessage is designed for strings <-> components

#

as like a configuration "serializer"

dense drift
#

Well it depends dkim, if they want to parse placeholders internally and expose to the users only the final component, then the other serializers would be fine

dusky harness
#

maybe im just worried about like random %s breaking something
since i think papi had a bug related to that in the past

dense drift
#

Ah, now that you say it

karmic bison
#

I'm not using MiniMessage, i'm actually learning how to use Components, it's the first time I'm using the Paper API since they've been implemented

dense drift
#

aight

dusky harness
#

nice

stuck hearth
#

Don't you need the plaintext serializer?

karmic bison
#
TextComponent configReloaded = EnPaCoreMessagesManager.CONFIG_RELOADED;
                        
String serializedComponent = LegacyComponentSerializer.legacyAmpersand().serialize(configReloaded);

serializedComponent = PlaceholderAPI.setPlaceholders(offlinePlayer, serializedComponent);

configReloaded = LegacyComponentSerializer.legacyAmpersand().deserialize(serializedComponent);
                        
commandSender.sendMessage(configReloaded);```

This should work, right ?
dusky harness
dense drift
#

yeah I've found out recently when I've looked back to their discord to get the code

dense drift
stuck hearth
stuck hearth
dusky harness
dusky harness
dense drift
#

especially for beginners

dusky harness
#

adventure 😌 😋

dense drift
#

sponge, fabric

dusky harness
#

ooh fabric too

#

wow

dense drift
#

they have native support like paper

dusky harness
#

rip forge & spigot

#

🪦

dense drift
#

who cares about forge, and spigot is, you know, spigot

stuck hearth
#

Zml for instance

dense drift
#

some of them are everywhere in the mc community kek

stuck hearth
#

Fr

dense drift
#

or well, at this on this side of the community

stuck hearth
#

Sponge is pretty widespread outside of its own ecosystem

karmic bison
#

I have another question, do you know how I can check that a TextComponent contains a specific String ?

dusky harness
dense drift
#

One way is to use #text() or #content() (I can't remember which is the right method)

dusky harness
#

do u know what the diff is?

#

between that and text serializer

#

or should i ask kyori

dense drift
dusky harness
#

asking kyori 👍

stuck hearth
#

One probably includes formatting if I had to guess, but we'll find out soon enough I spose

dusky harness
#

oh

dusky harness
#

so ig for Components you should use serializer

#

but TextComponents its fine to use content

stuck hearth
pulsar ferry
#

Because not all components have text content

dusky harness
#

ye

dense drift
#

@dusty frost I've tried to find some documentation for how to do the transaction thing but I can't find anything useful, besides how to do them in situations like moving things from a database or row to another ugh
I don't get how it should help me with execution of the shop transactions in the order they were created.
So player one tried to buy 5x item1 and player two tries to buy 10x item1, so it should first try to sell the items to the first player and then to the second.

dusty frost
# dense drift <@186255788212355073> I've tried to find some documentation for how to do the tr...

The point of transactions is that they are Atomic. This means they either complete all the parts, or none of them. So you need to put all the logic in that transaction, including the removal, because if two transactions are happening concurrently, the first one to execute will lock that row and complete, and the second one executing will see that that row is no longer available, and cancel itself/rollback, so it's like it never happened

dense drift
#

I legit don't know what to search for 🤣smiling_face_with_3_tears

dusty frost
#

It's the A in ACID compliant lol

#

there's really not a lot to search for

#

you just need to do all your logic in the transaction so that it can be atomically rolled back

dense drift
#

So I should do it all in a sql query?

dusty frost
#

yeah

#

ideally you'd do it in a stored procedure of some kind

#

pl/pgsql for postgres

#

whatever the procedural lang is for mysql

dense drift
#

ok, that's something I can search on google at least xd

dusty frost
#

i guess for your case of things sold, you'd want to set a flag or whatever on the item being sold that it has been sold, and then create a purchase entry

#

then you check in the transaction if that flag is already set before doing it

#

and it's guaranteed to happen atomically

dense drift
#

Hmm, ok

#

I saw some examples that were doing everything in a single query but I wasn't sure if I should too 😬

dusty frost
#

yeah that's good to have

#

makes double sure it happens atomically lol

dense drift
#

Yeah, fair.

dusty frost
#

but you can't really do a lot of nice checks that way, hence the stored procedures stuff

#

this is a classic case of a nice stored procedure check

dense drift
#

Also, I assume that if a group of people tries to buy item 1 and another to buy item 2, there will be like 2 "queues", one for each item?

dusty frost
#

it's row-level locking

#

so if they're not trying to buy the same item, they run concurrently uninterrupted

dense drift
#

So two transactions can be executed in parallel if different rows are used

dusty frost
#

yes

dense drift
#

Ok nice, nice

dusty frost
#

so it preserves speed in the vast majority of cases

#

and preserves correctness in the small minority of conflicts

dense drift
#

Thank you star

dusty frost
#

oh yeah, sql design is wild my man

#

i had to do a shit ton of Oracle stored procedures at my work

#

makes me real grateful for postgres lol

dense drift
#

Indeed, sql is something 🤯

river solstice
#

Oracle procedures 💀

#

Have that at my work too

dense drift
#

I'm trying to get my hands on more complex stuff, you know, to learn new things xD

dusty frost
#

but they announced they're going to become postgres based in like 4 years lol

#

everyone hates paying the Oracle fees

dense drift
#

🤣

#

hey, at least it is not M$ access

dusty frost
#

it's close lol

river solstice
#

Kinda same but not really
We use data from billing, like goverment data stuff, and they use oracle, we import data from it

dusty frost
#

ah rough

dense drift
#

what's up with oracle db though? I've seen it used in many places

#

are stuff like postgres newer than oracle or?

dusty frost
#

it's bad and costs a shit ton, the only reason people use it is because they're locked in

#

postgres is a bit newer iirc, it's just much better designed

dense drift
#

no I'm saying why are these software not using something else, but I guess it is because of the time they were made at

dusty frost
#

it's because they're getting kickbacks from Oracle

#

that's basically the only reason anyone does it

dense drift
#

wdym?

dusty frost
#

Oracle pays people who make big software packages to make Oracle the only database that works with their product

river solstice
#

Yeah our product is a nationwide data exchange platform intended for independent electricity suppliers to view historical electricity consumption data that is shared by customers and inform other suppliers about contracts made by clients

dusty frost
#

so then their customers down the line have to become Oracle customers

dense drift
#

oh.. wonderful 🌈

#

if I was to take a blind guess, I'd say ms does a similar thing with their database? 🤣 Microsoft SQL Server

dusty frost
#

nah SQL Server is actually pretty all right

#

it has a lot of features that integrate well with other MS stuff like AD and Azure

dense drift
#

ok that is fair

river solstice
#

The company I work in is a child company owned by the biggest independent electricity supplier in my country and the product client is the main electricity and gas distribution company lol

dusty frost
#

keeping it in house lol

dense drift
#

🤣

river solstice
#

Monehs do be pretty allright ngl

thorn cape
#

So I'm trying to send the BlockBreakAnimation so players on the server for a specific block but every time the packet is recieved it immediately changes back to stage 0, do I need to be listening for a specific packet and cancelling or mutating the data from it?

— Edit
So apparently NMS sends a packet every time I try to set the block break stage of bedrock. I tried to filter this and ignore all outgoing packets not sent by me for the block but it is still flickering and not keeping my stage rendered on the client.

edgy lintel
icy path
dense drift
#

@dusty frost Another thing, since I have to keep a local cache of each player's balance, I'm thinking about deducting the amount they would have to pay for the item they want to buy before doing the db transaction. If they are unable to buy the item I simply restore the balance and send a message like "You can not buy n item x". I guess that's fine? 🫡

dusty frost
#

that way things never get too out of date

dense drift
#
buyItem(Item item, Player player) {
  cost = item.amount() * item.price();
  removeBalance(player, cost);

  // do database transaction

  if (success) {
    player.sendMessage("You have bought ...");
  } else {
    player.sendMessage("You can not buy ...");
    giveBalance(player, cost);
  }
}```
smth like this
#

I know caching is a pain but this is a plugin and I can not query the db every time I need the balance / the balance gets updated =//

dusty frost
#

something something async vault like I was talking about in #dev-general lol

dense drift
#

yeah maybe at some point nevertm

tropic trench
#

I have been in the Spigot language for a short time. What I'm trying to do is if the user holds shift X it will pop up a prompt, but if they release it earlier it aborts.

I tried to do it with a "do while", but I saw that Runnables existed

    public void playerSneaking(PlayerToggleSneakEvent event ){
        final int[] count = {0};
        BukkitTask task = null;
        if (event.isSneaking()){

            event.getPlayer().sendMessage("shifting");
            task = new BukkitRunnable() {
                @Override
                public void run() {
                    event.getPlayer().sendMessage("shifting for " + count[0]);
                    count[0]++;
                }
            }.runTaskTimer(this, 0, 30);

        } else {
            event.getPlayer().sendMessage("oh no");


                task.cancel();
                task = null;

        }
    } ````
what gives me an error is that "task" will always return null and I don't know how to cancel the runnable
shy canopy
#

**

code
```**


```java
code

pls use code blocks

proud pebble
#

or not creating one at all

#

if you want to call that task object, you will have to store a reference to it somewhere, for example, having a Map<UUID,BukkitTask>

#

which would allow you to store the task, and then call it using the player's uuid

#

which can be gotten from player.getUniqueId()

#

also your count isnt being updated

#

or atleast i dont believe it is

#

and its going to be the same count for every player

#

your better off having the count in the run method

#

also you dont have to create a new task like that

#
Bukkit.getSchedular().runTaskTimer(mainClassInstance,() -> {
    //your code here
},0,30L);

also 30 ticks isnt alot of time btw

stuck hearth
#

1.5 seconds on average

proud pebble
#

also you would be using the java language, and the spigot api, spigot doesnt have its own language

#

also when you cancel a task, you dont have to make it = null

#

also doing a while loop will cause the server to be unresponsive if you dont exit out of it, thats why the scheduler exists

stuck hearth
proud pebble
#

the garbage collector will do that for you

tropic trench
#

but make a verification before if you are doing shift and if you are not inside the map

river solstice
#

spigot language 🥴

warm steppe
#

lombok

#

oml

wanton terrace
#

Is there a program where i can open a existing code and showing it in a python ui designer program?

proud pebble
#

store the count on the inside of the task

#

and hopefully bobs your uncle

minor summit
#

@mods

#

bruh

river solstice
#

@everyone

spare quiverBOT
#

The 'everyone' mention is disabled so you can't annoy people.

river solstice
#

real

queen swift
#
open_command: stats
register_command: true```

this deluxe command it not working
river solstice
#

cool

marble heart
unborn ivy
#

does anyone know whats going on with my code... its giving me a nullpointerexception warning and deletes the items and idk whats causing it (trying to remove only bookandquills/written books from my inventory)

                          for (int i = 0; i < 36; i++) {
                              Material items = p.getInventory().getItem(i).getType();
                              if (items == null) {
                                  return;
                              } else {
                                  if (items == Material.WRITTEN_BOOK || items == Material.BOOK_AND_QUILL) {
                                      p.getInventory().getItem(i).setAmount(0);
                                  }
                              }
                          }
                      }
                  }
              }
          }, 20L, 20L);
#

warning says that the error is with this line Material items = p.getInventory().getItem(i).getType();

#

this is actually sort of the same issue ive got in the past, ive even tried checking if item wasnt null and then checking if the item material was written books or books and quills, it still gave a warning and ran code

tired olive
unborn ivy
tired olive
#

theres no other way that can throw an npe

#

just try it trust me

unborn ivy
#

try what

tired olive
#

add an if conditions that checks if getItem() returns null and if so continue

tired olive
unborn ivy
#

i thought u could just directly check if it was null

#

with .getType()

tired olive
#

did you read my explanation?

unborn ivy
#

i sort of understand ig

#

ill try it

tired olive
#

you should probably learn some basic java before even trying to use any external api

#

but up to u ig

unborn ivy
#

what are you saying lol

#

me not knowing how that works doesnt mean i dont know basic java

#

like i said i thought i could easily check if item was null with the gettype method

#

anyways thanks for telling me the issue

#

i fixed it now

dense drift
unborn ivy
proud pebble
#

if player was null and you tried to use player.getInventory() it would throw an npe
if getItem() returns null and you tried to do getType() then it would throw an npe

#

getType will never be null since afaik its not allowed to but the ItemStack that getItem() returns can be

#

also you dont have to do that else statement

#

since your doing return

river solstice
#

don't bother explaining

#

he knows basic java

karmic bison
#

Hello, I have a question about the ItemStack#displayName() method. Why does it put the item's displayname in between brackets ? Is there a way to remove them ?

broken elbow
#

ItemStack#displayName method returns the name that the item will have ingame

#

Use ItemStack#getItemMeta#displayName instead

karmic bison
#

oh okay

proud pebble
river solstice
#

no he implicitly said he knows basic java

proud pebble
#

we are supposed to believe that?

karmic bison
#

Hello, is it possible to get an ItemFrame entity from a location and then remove it ? I've been trying this but it doesn't work (I get the following error : https://paste.helpch.at/tivibufewa.rb) :

Location shopLocation = shop.getLocation();

List<Entity> entityList = List.of(shopLocation.getChunk().getEntities());

for(Entity entity : entityList) {
  if(shopLocation.distance(entity.getLocation()) > 1) {
    if(entity instanceof ItemFrame) {
      ItemFrame itemFrame = (ItemFrame) entity;
      itemFrame.remove();
      break;
    }
  }
}
river solstice
#
Location location = new Location(world, x, y, z);

for (Entity entity : location.getWorld().getNearbyEntities(location, 1, 1, 1)) {
    if (entity.getType() == EntityType.ITEM_FRAME) {
        entity.remove();
    }
}

maybe

dense drift
#

I think distance() returns the distance in a 2D space (so without y)

#

d;Location#distance

uneven lanternBOT
#
public double distance(@NotNull Location o)
throws IllegalArgumentException```
Description:

Get the distance between this location and another. The value of this method is not cached and uses a costly square-root function, so do not repeatedly call this method to get the location's magnitude. NaN will be returned if the inner result of the sqrt() function overflows, which will be caused if the distance is too long.

Returns:

the distance

Parameters:

o - The other location

Throws:

IllegalArgumentException - for differing worlds

wind tapir
#

Hello, I have a problem with nametagedit, I used it with my plugin, but now, it says that it can't be initialized because it's already initialized:

[18:58:29 ERROR]: Could not load 'plugins/NametagEdit (1).jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.IllegalArgumentException: Plugin already initialized!
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:135) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:329) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) [server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.craftbukkit.v1_8_R3.CraftServer.loadPlugins(CraftServer.java:292) [server.jar:git-Spigot-21fe707-741a1bd]
at net.minecraft.server.v1_8_R3.DedicatedServer.init(DedicatedServer.java:198) [server.jar:git-Spigot-21fe707-741a1bd]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:525) [server.jar:git-Spigot-21fe707-741a1bd]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_312]
Caused by: java.lang.IllegalArgumentException: Plugin already initialized!
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:122) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:66) ~[server.jar:git-Spigot-21fe707-741a1bd]
at com.nametagedit.plugin.NametagEdit.<init>(NametagEdit.java:17) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_312]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_312]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_312]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_312]
at java.lang.Class.newInstance(Class.java:442) ~[?:1.8.0_312]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[server.jar:git-Spigot-21fe707-741a1bd]
... 6 more
Caused by: java.lang.IllegalStateException: Initial initialization
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:125) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:66) ~[server.jar:git-Spigot-21fe707-741a1bd]
at fr.idaamo.essentials.Main.<init>(Main.java:17) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_312]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[?:1.8.0_312]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[?:1.8.0_312]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[?:1.8.0_312]
at java.lang.Class.newInstance(Class.java:442) ~[?:1.8.0_312]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[server.jar:git-Spigot-21fe707-741a1bd]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[server.jar:git-Spigot-21fe707-741a1bd]
... 6 more

and, in my code, I have this in line 17... thonking

public class Main extends JavaPlugin implements Listener

and btw, I uninstalled nametagedit from my plugin, I removed it from the librairies and every import.
( when I remove my plugin, everything's ok )

neat pierBOT
#
FAQ Answer:

Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
HelpChat Paste - How To Use

dense drift
#

share the full code

dense drift
#

yeah idk tbh

wind tapir
#

bruh

sterile thunder
# dense drift yeah idk tbh

Could it be they didn't define the plugin as a dependency and it's loading incorrectly, or is that not what it would look like?

wind tapir
#

if you were talking about my problem

sterile thunder
#

Thanks, but I wasn't asking you. 🙂

#

Or that question actually

tired olive
#

how can someone possibly claim they know basic java if they dont

#

null pointers are also very advanced so idk why u think they dont know basics

minor summit
#

lol

lost narwhal
#

Hi! I'm trying to edit the text a plugin sends in chat when the command is ran.

I've exported the .jar and decompiled the .class file.

I have then changed the text accordingly.. and saved the file as a .java

#

But now i'm wondering how I re-compile the file into the new .class?

river solstice
#

Via the terminal javac MyCoolJavaFile.java

lost narwhal
spiral prairie
#

Probably gonna have to edit bytecode here using recaf

lost narwhal
#

whut

#

all i want to do is change the resulting message from the command

burnt dagger
#

How can I return a 0 for a placeholder instead of it returning the placeholder itself if it is not filled

river solstice
river solstice
#

also, it has to be in the same project hierarchy from where you took it from.

#

you can't take out the file out of the context with all its imports and tell the compiler to compile it without those other classes present

lost narwhal
#

I’m trying to compile it where the .class file was

river solstice
#

use an ide

dense drift
#

There should be a tool that lets you edit variables or strings from a jar, I remember using one

warm spear
#

Hello is there someone already used nms , i created a NPC and i want it to walk to the player location (me) i used this code below but it dont seem to be working he always go at the invert position from me. There are no pathfinder for EntityPlayer and i dont want to use Citizens here is my current code : ``` double x = location.getX() - npc.locX;
double y = location.getY() - npc.locY;
double z = location.getZ() - npc.locZ;
float yaw = location.getYaw();
float pitch = location.getPitch();

    byte relX = (byte) (x * 32.0);
    byte relY = (byte) (y * 32.0);
    byte relZ = (byte) (z * 32.0);


    PacketPlayOutEntity.PacketPlayOutRelEntityMove move = new PacketPlayOutEntity.PacketPlayOutRelEntityMove(npc.getId(), relX,relY,relZ, true);

    for (Player player : Bukkit.getOnlinePlayers()) {
        ((CraftPlayer) player).getHandle().playerConnection.sendPacket(move);
    }```
dense drift
worn jasper
#

Any better way of doing this?

HttpRequest request = HttpRequest.newBuilder()
    .POST(HttpRequest.BodyPublishers.noBody())
    .uri(URI.create("https://hangar.papermc.io/api/v1/authenticate?apiKey=" + apiKey))
    .build();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
    .thenAccept(response -> {
        if (response.statusCode() != 200) {
            throw new RuntimeException("Failed to authenticate: " +  response.body());
        }
        Gson g = new Gson();
        JsonObject obj = g.fromJson(response.body(), JsonObject.class);
        jwtKey = obj.get("token").getAsString();
    });
river solstice
#
private static final HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .build();

private static final String API_URL = "https://hangar.papermc.io/api/v1/authenticate?apiKey=";
private static final String API_KEY = "your-cool-api-key";

private static final Gson gson = new Gson();

public void authenticate() {
    String uri = API_URL + API_KEY

    HttpRequest request = HttpRequest.newBuilder()
            .POST(HttpRequest.BodyPublishers.noBody())
            .uri(URI.create(uri))
            .build();

    httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenApply(json -> {
                JsonObject obj = gson.fromJson(json, JsonObject.class);
                return obj.get("token").getAsString();
            })
            .thenAccept(jwtKey -> {
                // handle success
            })
            .exceptionally(ex -> {
                // handle exception
            });
}
worn jasper
#

apiKey is a private field already btw

#

but yeah looks a lot cleaner

jade wave
#
private static final String API_ENDPOINT = "https://hangar.papermc.io/api/v1/authenticate";
private static final String API_KEY = "your_api_key_here";

public String getJwtToken() {
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .POST(HttpRequest.BodyPublishers.noBody())
                .uri(URI.create(API_ENDPOINT + "?apiKey=" + API_KEY))
                .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() != 200) {
            throw new RuntimeException("Failed to authenticate: " + response.body());
        }
        JsonObject obj = JsonParser.parseString(response.body()).getAsJsonObject();
        return obj.get("token").getAsString();
    } catch (IOException | InterruptedException e) {
        throw new RuntimeException("Failed to send HTTP request: " + e.getMessage(), e);
    } catch (JsonParseException | NullPointerException e) {
        throw new RuntimeException("Failed to parse JSON response: " + e.getMessage(), e);
    }
}

I guess something like this would work.

worn jasper
#

issue is that that isn't async

worn jasper
river solstice
#

yeah well it's just an example

#

you can adapt it to your own needs

worn jasper
#

so in thenApply, I return the jwtKey which is what is returned in thenAccept?

river solstice
#

sendAsync returns a CompletableFuture, which has a thenApply and thenAccept methods.
You can chain thenApply and then end the chain with thenAccept.
each return of thenApply is passed to the next link of the chain.

worn jasper
#

Oh understood, thanks a lot.

#

Also, I assume writing a wrapper like this, is normal to have these big methods... there is not much else you can optimize anymore

river solstice
#

well it's a small request

#

not much left to 'optimize'

#

you could also use connection pooling if you're making multiple requests to the same server

tired olive
#

so itd look smth like this```java
HttpRequest request = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.noBody())
.uri(URI.create("https://hangar.papermc.io/api/v1/authenticate?apiKey=" + apiKey))
.build();
client.sendAsync(request, GsonBodyHandler.of(JsonObject.class))
.thenAccept(response -> {
if (response.statusCode() != 200) {
throw new RuntimeException("Failed to authenticate: " + response.body());
}
jwtKey = response.body().get("token").getAsString();
});

river solstice
#

well, there are a lot of ways to do it

#

personally I don't see the need for another class for such a simple request

worn jasper
#

Wdym another class?

river solstice
worn jasper
#

Ah yeah

#

yeah, it wouldn't save much space if I did either way

#

will read about connection pools

tired olive
worn jasper
#

although it won't be for a JsonObject rather a class directly

#

(POJO)

worn jasper
#

Why does my gut tell me this structure sucks?

#

Naming is a nightmare lol

hoary scarab
worn jasper
hoary scarab
#

Project.Data, Project.UserActions etc...

worn jasper
hoary scarab
#

Oh they're classes...
The package is already "project" don't add that to the class names

dense drift
#

It is fine Afonso

#

Just go with what you feel ok about

worn jasper
worn jasper
#

hence why I asked

#

I completely suck at naming things

dense drift
#

We all do

icy shadow
#

Yeah there’s nothing wrong with that

karmic bison
#

Hello, is there a way to prevent items from stacking in an inventory when using the Inventory#addItem() method ?

dark garnet
#

hi i need to set some yaml values while preserving comments (and blank lines if possible), anyone got any ideas? (i dont have to use bukkit's yaml parser)

#

basically i need to edit just the values, everything else in the file should stay exactly the same

dense drift
dark garnet
#

hi again, new thing, so i have a list of strings. i need to compare all these strings (using jarowinkler), i want to end with groups of similar strings (List<List<String>>), how can i do this? this is for a non-minecraft related thing (discord bot)

tired olive
spiral mural
#

Hey, I am trying to return an ItemStack from a file but it returns null everytime somehow?

        if (files != null) {
            for (File file : files) {
                if (file.isFile() && file.exists()) {
                    config = getConfig(file);

                    Bukkit.getServer().getLogger().info(file.getAbsolutePath());

                    ConfigurationSection section = config.getConfigurationSection("");
                    String arenaID = section.getKeys(false).iterator().next();
                    String display = section.getString("display");

                    ItemStack item = config.getItemStack("item");
                    ItemMeta itemMeta = item.getItemMeta();
                    itemMeta.setDisplayName(display);
                    PersistentDataContainer container = itemMeta.getPersistentDataContainer();
                    container.set(new NamespacedKey(ArenaManager.getInstance(), "CLICK"), PersistentDataType.STRING, arenaID);
                    item.setItemMeta(itemMeta);
                    return item;
                }
            }
        }
        return null;
    }```

        ItemStack arenaItem = LoadArena.ArenaItem();
        inventory.addItem(arenaItem);

I know I'm not checking for null, but the file is there and it shouldn't return null.
```Caused by: java.lang.IllegalArgumentException: Item cannot be null```
#

and in the file item: ==: org.bukkit.inventory.ItemStack v: 3337 type: GRASS_BLOCK meta: ==: ItemMeta meta-type: UNSPECIFIC display-name: '{"extra":[{"bold":false,"italic":false,"underlined":false,"strikethrough":false,"obfuscated":false,"color":"red","text":"Set Arena Item"}],"text":""}' PublicBukkitValues: arenamanager:click: ITEM

minor summit
#

hey

dense drift
#

😛

worn jasper
#

Uhm if I use gson and want to convert json to a custom object and not JsonObject, does that object need a constructor?

tired olive
#

gson doesnt call any constructor when instantiating a class

#

i dont see why you wouldnt have one tho

dense drift
#

If you make a class like the one used by Sparky in their example, you can make the of() method accept a Type, a Class<> and whatever else gson.fromJson() accepts

#

Iirc gson uses field names to map the json properties to object fields, and you can add aliases with @SerializeName or smth like that
You might need an empty constructor if the class doesn't have one I think

karmic bison
#

Hello, does anyone know if AsyncChatEvent can use some methods from the Bukkit API or none of them ?

worn jasper
#

but just one with no args

#

but you do NEED one

wheat carbon
#

no you don't

dense drift
#

Classes have an implicit, empty, constructor if none is defined and the fields are not final

worn jasper
#

Well then that's weird

#

Cause once I added a no args constructor my code worked and stopped receiving a nullpointer

#

without one, I wasn't being able to even start the program

#

Was getting a nullpointer at compiling level

#

Now I am quite confused.

#

isn't it simply like a POJO? Which needs a default no arg constructor?

wheat carbon
#

ye so

#

i just tested it

#

and it works

#

so idk what ur talking about

#

like gaby said java generates a no arg constructor when one isn't present

#

although gson also uses unsafe in some cases to get an instance of the class, I can't tell you what cases it does that for though

worn jasper
#

yeah, that does make sense, although doesn't explain why I was getting a null pointer on compiling lol

#

OH welp, will just ignore it

tired olive
#

so itll never not be able to instantiate the class

elder idol
#

@teal vale

#

sorry for pinf

teal vale
#

It posts as a text file?

elder idol
#

i cant anything else

broken elbow
elder idol
elder idol
#

here

broken elbow
proud pebble
#

this allows you to use the bukkit api since itll basically make the code inside of it run sync instead of async

karmic bison
#

okay thanks

halcyon ermine
#

Hello there, is there any way to put the player somewhere so that the health of the item is not displayed?

worn jasper
#

W structure? (Hangar API wrapper, unsure if it's worth putting in github but yeah)

#

(ignore the fields lol)

dusky harness
spiral prairie
#

aaaaaaaaaaaaa

dusty frost
#

lmao

worn jasper
dusky harness
#

also where do u get that menu?

#

looks familiar

stuck hearth
#

There's a structure button on the side

dusky harness
#

ohhh ty

stuck hearth
#

Or View -> Tool Windows -> Structure
Incase someone else goes looking for it

worn jasper
#

yeah, quite handy for a quick overview

hoary scarab
dusky harness
#

I'm trying to use ScriptEngine (specifically kotlin) inside a spigot plugin, but I'm getting these errors: javax.script.ScriptException: ERROR unable to load class me.dkim19375.spongeextras.plugin.SpongeExtrasPlugin: java.lang.IllegalArgumentException: unable to load class me.dkim19375.spongeextras.plugin.SpongeExtrasPlugin at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.asJsr223EvalResult(KotlinJsr223JvmScriptEngineBase.kt:104) at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.compileAndEval(KotlinJsr223JvmScriptEngineBase.kt:63) at kotlin.script.experimental.jvmhost.jsr223.KotlinJsr223ScriptEngineImpl.compileAndEval(KotlinJsr223ScriptEngineImpl.kt:95) at org.jetbrains.kotlin.cli.common.repl.KotlinJsr223JvmScriptEngineBase.eval(KotlinJsr223JvmScriptEngineBase.kt:31) at java.scripting/javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:262)This occurs when using ScriptEngine#put(String, Object) 🤔
for ex the error above comes from kt engine.put("plugin", plugin) but it also happens with Guild (JDA), etc
Anyone might have an idea why? 🤔
(full code: https://pastes.dev/ps4U2nxPaC, lines 155 -> 165)

#

but I don't know how to make it work with spigot

#

and its libraries feature

#

but I don't know how it should go in spigot ☹️

stuck hearth
#

Trying to load kotlin scripts in Minecraft?

dusty frost
#

bro doesn't realize he can just use kotlin normally 😔

stuck hearth
#

I am curios on the use-case. I considered doing something similar, but I decided against it.

dusky harness
stuck hearth
#

What are you using the scripting engine for?

dusky harness
#

running custom kotlin code at runtime

#

if you look up something like "discord bot eval command" it should show up with examples

stuck hearth
#

Oh I see

dusky harness
#

and since the libraries are managed by spigot, I'm not sure how to use the fix posted by others (both links have the same solution) above

#

I mean I guess I could add stuff in my build.gradle.kts and add it to manifest file

#

and then locate the file

#

since it's going to be in the libraries folder

dark garnet
stuck hearth
#

I don't believe that's the case since it's not apart of yaml spec

dusky harness
#

although a lot of libs still support comments

dusky harness
#

but it doesn't work 😭

burnt storm
#

My plugin has some custom placeholders. Is it possible to make them compatibile with ServerUtils? My problem is when unloading/loading the plugin, placeholders no longer update.

dark garnet
stuck hearth
#

What even happened there

dark garnet
stuck hearth
#

You like pinged me, then deleted the message maybe? Then messaged, edited the message with a ping?

gray dagger
#

anyone there to can help me with an dev problem?

dark garnet
gray dagger
#

my plugin work now on this way:

you write in chat /reward to open a GUI

in this GUI you can click on a gold ingot to recieve your dayli reward and then the plugin write your UUID in an yml for a cooldown timer

now i want that OP players (or players with a permission for that) to ignore the cooldown timer...what i need todo for that?

dark garnet
stuck hearth
dark garnet
gray dagger
#

that you can help me better...here my code

dark garnet
# gray dagger insert there? https://prnt.sc/Yt_bKWD7e8oM

u can include it in the if statement below, the one that checks for the cooldown thing
something like if (!player.hasPermission("no-cooldown") && cooldowns.containsKey(uuid))
it will check if the player has the no-cooldown permission. if they do, the if statement fails. if they dont, the statement will continue and check if cooldowns contains their UUID

gray dagger
#

thank you

#

i cant upload my code...idk why

dark garnet
# dark garnet yeah even it does i assume its not very great lmao

to avoid having to deal with that, heres another one of my issues lmao:
im trying to execute these cmds by the console using Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command) when a player (srnyx) respawns (PlayerRespawnEvent):

  1. execute as srnyx run say hi
  2. say srnyx %killer%
  3. gamemode spectator srnyx
    but, 1 doesnt even run, 2 works, and 3 says "No player found" (i assume cause the player isnt fully loaded in yet?)
gray dagger
#

you want that it say HI if you respawn automaticly?

dark garnet
gray dagger
#

iam not sure if i understand your issue...

dense drift
#

I need to use python to control a microcontroller that measures some data (temperature, humidity, etc.) and then it should send the data through socket to a LoRa network.
This is the code I have for the socket, is copied from the documentation of the controller.

s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

# set the LoRaWAN data rate
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

# make the socket blocking
# (waits for the data to be sent and for the 2 receive windows to expire)
s.setblocking(True)

# send some data
s.send(bytes([0x01, 0x02, 0x03]))

# make the socket non-blocking
# (because if there's no data received it will block forever...)
s.setblocking(False)

# get any data received (if any...)
data = s.recv(64)
print(data)

Now, the platform I need to send the data to expects a hex string with all the values joined together.

This is an example from their documentation: https://liveobjects.orange-business.com/doc/html/lo_manual_v2.html#DEC
This decoder accepts two ints, for pressure and temperature (the template part is just how the data will look after it is decoded, it is not important)

{
  "encoding": "twointegers",
  "enabled": true,
  "format": "int pressure;int temperature;"
  "template":"{\"pressure\":{{pressure}},
  \"temperature\" : \"{{#math}}{{temperature}}/10{{/math}} celsius\"}",
  "model": "model_twointegers"
}```
And this string `000003F5000000DD` will be decoded as `pressure: 1013, temperature: 221 (22.1 after that division by 10)`


Now, my problem is that I don't understand how to send the data through the socket so it gets to the platforms as a hex string. I've tried different approaches, even to send the bytes of a hex string but somehow in the platform the value is something random, like a big number.

The python version available on the controller is smth like 3.6 if I recall correctly
tired olive
#

i aint reading allat

#

especially if its python

dense drift
#

You can as well just not reply winkers

tired olive
deep flume
#

'PlaceholderAPI()' has private access in 'me.clip.placeholderapi.PlaceholderAPI'

how to fix?

    public void onEnable() {
        // Initialize playerGemsMap
        playerGemsMap = new HashMap<>();

        // Load player gem balances from file
        loadPlayerGemsFromYaml();
        if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
            new PlaceholderAPI().registerPlaceholder(this, "gems", (event) -> {
                if (event.isOnline()) {
                    return String.valueOf(GemHandler.getGem(event.getPlayer().getUniqueId()));
                }
                return "";
            });
        }
    }
deep flume
#

random plugin

void orchid
deep flume
#
    public void onEnable() {
        // Initialize playerGemsMap
        playerGemsMap = new HashMap<>();

        // Load player gem balances from file
        loadPlayerGemsFromYaml();
        if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) {
            PlaceholderAPI.registerPlaceholder(this, "gems_balance", e -> {
                if (e != null && e.isOnline()) {
                    return String.valueOf(getGems(e.getPlayer()));
                }
                return null;
            });
        }
    }```
void orchid
#

Have you taken a look at the link I sent you?

karmic bison
#

Hello, could someone help me with this piece of code i've been working on ? I'm trying to change chat format with my plugin, while preventing chat messages from being sent when players have to input something in chat for my other plugin (which asks the player to input a String or int). However, when I try to input something in chat, my message still gets sent in the public chat.

@EventHandler
  public void onChat(AsyncChatEvent event) {
    Player player = event.getPlayer();

    ConfigurationSection modulesSection = main.getCoreModule().getConfig().getConfigurationSection("modules");
    assert modulesSection != null;

    if(Objects.equals(modulesSection.getString("merch"), "enabled")) {
      if(!merchModule.getCreatingProductsPlayers().containsKey(player) && !merchModule.getCreatingStoreNamePlayers().containsKey(player)) {
        String chatFormatString = EnPaChatMessagesManager.CHAT_FORMAT;

        chatFormatString = PlaceholderAPI.setPlaceholders(player, chatFormatString);

        Component chatFormat = miniMessage.deserialize(chatFormatString, Placeholder.parsed("message", miniMessage.serialize(event.message())));

        for(Player onlinePlayer : main.getServer().getOnlinePlayers()) {
          onlinePlayer.sendMessage(chatFormat);
        }
      }
    } else {
      String chatFormatString = EnPaChatMessagesManager.CHAT_FORMAT;

      chatFormatString = PlaceholderAPI.setPlaceholders(player, chatFormatString);

      Component chatFormat = miniMessage.deserialize(chatFormatString, Placeholder.parsed("message", miniMessage.serialize(event.message())));

      for(Player onlinePlayer : main.getServer().getOnlinePlayers()) {
        onlinePlayer.sendMessage(chatFormat);
      }
    }
    event.setCancelled(true);
  }

merchModule is my other plugin's main class instance, and the #getCreatingProductsPlayers() and #getCreatingStoreNamePlayers() methods return two different HashMaps with a Player as key.

dense drift
#

actually I might only have to return null in RegionVisitor#continue

gray dagger
#

hey guys...iam a newbie in developing and try to create my first plugin...

at the moment it works very good, but i have a problem and want ask for help...

my problem is:

GuiItem take = ItemBuilder.from(Material.GOLD_INGOT).name(Component.text("§3§lReward")).lore(Component.text("Get your Dayli Reward!")).asGuiItem(inventoryClickEvent -> {

this line give an gui (what i created before) an item with meta datas...

after the -> {
start the code whats happen if you click ingame on the gold_ingot...

i want give this GUI more items, thats why i want put the code for the gold ingot in another class file and want say in the line
-> { getClass(GoldEvent)

but that dont work, then all is red...

#

pls can anyone help me to say that this line need take the event from another class file?

lyric gyro
#

Full Stack Blockchain Developer - Available for Hire (Remote, Full Time)

Hello,

I am a Senior Blockchain & Full Stack Developer with over 6 years of rich experience in the industry. I am currently available for full-time remote work and can contribute to your projects anytime, anywhere.

Skills & Expertise

Blockchain Development

  • Smart Contract Development/Audit
  • Solidity, Hardhat, Truffle, Ethereum, BSC, Polygon
  • Rust, Anchor, Solana, NEAR, Terra
  • Cosmos SDK, Cosmwasm
  • Web3.js, Ethers.js, Moralis
  • DApps, DEX, DeFi, DAO, NFT marketplace

Front-End Development

  • JavaScript, TypeScript
  • React, Next.js, Redux, Gatsby
  • Vue.js, Nuxt.js, Vuetify, Vuex, Quasar
  • AngularJS, Angular Materials
  • CSS 3, Bootstrap, TailWind CSS
  • Material UI, Styled-Component

Back-End Development

  • Node.js, NestJS, ExpressJS, GoLang
  • PHP, Laravel
  • Python, Django, Flask
  • MongoDB, MySQL, Firebase, PostgreSQL
  • GraphQL, Apollo, Websocket, RESTful API

Availability & Commitment

As an individual freelancer without any ongoing projects, I am available to work full-time and at any time required. My career goal is to continuously learn and grow my skills from a technical standpoint while acquiring new skills over time.

Contact & Further Information

Please feel free to reach out if you are interested in building something together or require more information about my experience. I look forward to connecting with you and discussing how I can contribute to the success of your project.

Thank you for considering my proposal.

Best regards,

gray dagger
proud pebble
#

you should do the way they said

#

as it does work

versed carbon
#

Hello all. 🙂 I just wanted to ask here incase anyone knows.
I'm currently trying to make a boss plugin (vanilla mobs) and I'm trying to add attributes to the mob I summon.

When messing around I made a small datapack, it was so easy. I wrote over 1000 words adding attributes to the mob summoned as well as changing the drops etc etc.

But now when I try and do something similar to that mob I created it doesn't come out right.
I can figure out how to get the mob to spawn, the items to drop as well as adding some effects to the item (enchants, unbreakable, name and lore.)

but I don't seem to be able to figure out how to add similar attributes to the item and mobs as I did with a datapack.

for example, I would like to make the shield that the mob drops unbreakable. That's easy simply

ItemStack itemStack = new ItemStack(Material.GOLDEN_AXE);
Inventory inventory = player.getInventory();
ItemMeta itemMeta = itemStack.getItemMeta();
itemMeta.setUnbreakable(true);
itemStack.setItemMeta(itemMeta);
inventory.addItem(itemStack);

But how would I go about adding extra hearts or extra knockback resistance? Is it as simple as another item meta?
or do I have to mess with effects for the entity or when the entity drops the attributed item would I have to make it so when item is held these effects are applied to player?

Currently I'm using a quick fix making it so when the command is run, it runs the /function command which summons the entity.

If anyone has any clue please let me know. 🙂

dark garnet
#

d;ItemMeta#addAttributeModifier

uneven lanternBOT
#
boolean addAttributeModifier(@NotNull Attribute attribute, @NotNull AttributeModifier modifier)
throws NullPointerException, IllegalArgumentException, NullPointerException```
Description:

Add an Attribute and it's Modifier. AttributeModifiers can now support EquipmentSlots. If not set, the AttributeModifier will be active in ALL slots.
Two AttributeModifiers that have the same UUID cannot exist on the same Attribute.

Returns:

true if the Attribute and AttributeModifier were successfully added

Parameters:

attribute - the Attribute to modify
modifier - the AttributeModifier specifying the modification

Throws:

NullPointerException - if AttributeModifier is null
IllegalArgumentException - if AttributeModifier already exists
NullPointerException - if Attribute is null

dark garnet
#

@versed carbon ^

versed carbon
#

thank you so much 🙂

proud pebble
#

you would either use the instance of the gui thats already created or new GoldEvent

#

you wouldnt use getClass

dense drift
#

yeah, I've just returned null after the first block

minor summit
#

cool cool

gray dagger
#

GuiItem take = ItemBuilder.from(Material.GOLD_INGOT).name(Component.text("§3§lReward")).lore(Component.text("Get your Dayli Reward!")).asGuiItem(inventoryClickEvent ->{ how can i say read the event here from another class file?

spiral prairie
#

classInstance.clickEvent(inventoryClickEvent)

gray dagger
spiral prairie
#

you need an instance of another class

#

or you make a static method

#

also im unsure if § works with kyori without the legacy serializer

gray dagger
#

iam beginner in developing🫤

spiral prairie
#

maybe do a java course now

#

before doing plugin development

gray dagger
spiral prairie
#

ah alrighty

gray dagger
#

my full code works rly great...i only need know to i can split it to make it smaller

#

that i have 1 class file for gui and some other class files for different click events

spiral prairie
#

yeah either make it static and call it directly (which probably makes more sense) or create a class, create an instance of that and call the method on that

gray dagger
#

if i make it static then its in same class file like the gui right?

spiral prairie
#

no

#

just make it static in another file

#

and call ClassName.theMethod(inventoryClickEvent);

gray dagger
spiral prairie
#

yea

gray dagger
#

okk great thank you i will try it

1 last question to be 100% sure

pulsar ferry
#

Don't think of static as "I'll make it static so I can access it on a different class" that is a very wrong way to look at it

gray dagger
#

to make the code static, i just do from public to public static...right?

pulsar ferry
#

Static makes a member not belong to any specific instance but instead makes it belong to the class, it has nothing to do with being able to access it from a different class
If you want something accessed on a different class, you pass the instance of one class to another through dependency injection

spiral prairie
#

except when a static class is fine?

pulsar ferry
#

Wdym?

spiral prairie
#

cough utils?

#

bruh i totally misunderstood your text

#

as a declaration of war against static mb

pulsar ferry
#

The purpose of utils is that they aren't instanced based, so yeah they should be static

spiral prairie
#

yeah

pulsar ferry
#

But that depends, ideally you'd put util classes as private members in the place they are called instead, if they aren't used in multiple different places ofc

gray dagger
#

so i write now
public class GoldEvent extends GUI
??

#

to make the GoldEvent class to an daughter from the GUI class?

spiral prairie
#

please to a free small and quick java course on methods, instances, classes, interfaces and static modifiers etc

#

it will help you out a lot

gray dagger
#

sure, or you help me xD

spiral prairie
#

if i just spoon feed you now, youll come back here and ask a similar question

pulsar ferry
#

The issue is that we can give you the answer you want which is, pass the gui instance to the event instead or vice versa, but you won't understand because you need to know the basics of the language you're using
I definitely recommend you learn it first

gray dagger
#

for what i need ask an similar question? this is the own problem what i have🤦‍♂️

#

or did you think i found a code like that in supermarket?

gray dagger
spiral prairie
#

but how are you going to do it without knowing basic principles of the thing youre trying to do

gray dagger
#

There are people who learn by reading gibberish for months and then there are people like me who learn much better by just doing it🤦‍♂️

spiral prairie
#

well then go on, learn it by trying and doing

broken elbow
gray dagger
#

ye but for that you need help...or do you want say me that you never need help? huh?

broken elbow
#

And that help you'll get from courses

spiral prairie
#

nope, never said that

pulsar ferry
#

pass the gui instance to the event instead or vice versa
I gave you the answer already, if you're learning by doing then do it

spiral prairie
#

its just not possible to provide you with that much information while youre not willing to learn

#

when i need help, i ask because i have exhausted all other options: their docs, github issues, wiki, youtube, any other papers and other stuff the service offers

broken elbow
#

There are interactive courses out there you know. Not just text

#

And you can learn by doing (following the course)

gray dagger
#

many information? the only what you say is make that make that, but what's the point of saying what to do if you don't say how to do it????

so...you dont haved help me🤦‍♂️

broken elbow
#

pass the gui instance to the event instead or vice versa

#

it is that simple

gray dagger
#

or do you want to tell me that you already knew algebra before you were shown how to do it in school??

broken elbow
#

that's the whole point of this conversation

spiral prairie
gray dagger
#

no this isnt a school...this is a help chat, with guys that dont want help...very good

broken elbow
#

very different words

pulsar ferry
broken elbow
#

I'm helping you learn by pointing you in the right direction but you're refusing it

pulsar ferry
#

But anyways, I already gave you the answer you needed

worn jasper
#

eats popcorn

toxic steeple
#

could someone help me with this?, i'm trying to use ormlite in my spigot plugin and everything works as expected until i run it on the server which results in

java.lang.NoClassDefFoundError: com/j256/ormlite/support/ConnectionSource

and honestly, i'm struggling to figure out why this is the case since i clearly have it in my gradle dependencies

dependencies {
    compileOnly "org.spigotmc:spigot-api:1.19.4-R0.1-SNAPSHOT"
    implementation 'org.xerial:sqlite-jdbc:3.40.1.0'
    implementation 'com.j256.ormlite:ormlite-core:6.1'
    implementation 'com.j256.ormlite:ormlite-jdbc:6.1'
}

and it is present in my external libraries
https://cdn.discordapp.com/attachments/833775826050220082/1101191477465469088/image.png

gray dagger
#

i dont want that you give me the answer...bcs i dont want give you my full code...

i only want that you say me how i create an instance (what you say what a solution would be but also a teacher shows you the way to a solution instead of the solution!)

worn jasper
spiral prairie
toxic steeple
#

thanks, i will try that

spiral prairie
#

were not teach chat, again

worn jasper
worn jasper
#

Also, spoiler alert, no one asked for your code, and no one wants it probably.

gray dagger
#

as if you are omniscient, as if you understand everything right away and can do everything immediately without asking questions🤦‍♂️

spiral prairie
#

and if youre not willing to give it out, nobody will be able to help you in the future after you took courses with more complex problems

worn jasper
#

Also, another spoiler alert, google exists, we give you the direction, it's up to you to take our directions and do your own research

gray dagger
#

Dirty bums here... bye

broken elbow
worn jasper
broken elbow
worn jasper
#

lol

spiral prairie
#

blitz abuses is powers pt.2

broken elbow
#

shh

spiral prairie
#

i want caps bypass too

#

xDD

worn jasper
#

he probs left I would assume

#

if he didn't, then well deserved kick/ban tbh, was causing drama in here

spiral prairie
#

yeah he did

#

he gonna have a hard time in life

worn jasper
#

indeed, wouldn't doubt if it was just a kid trying to program something

#

Funnily enough, he went to Triumph's discord

spiral prairie
#

oh god

proud pebble
#

i just read all of that conversation and i was so confused

worn jasper
#

yeah xD

proud pebble
#

the guy was also using an inventory framework at the same time

worn jasper
#

provided more here than anywhere else lol

worn jasper
proud pebble
#

but when you skip the basics you fuck yourself and make everything more difficult

worn jasper
#

exactly

worn jasper
wheat sparrow
#

Hello there, I am trying to prevent an error that I'm facing when the server shuts down where PAPI fails to unregister the expansions. I am unsure how to properly unregister an internal expansion class and I can't seem to find any documentation on the wiki.

spiral prairie
#

i dont think you have to

wheat sparrow
#

I didn't think so either, however I do get an error stating that the plugin is null when PAPI tries to unregister the expansions

#

I cant post you a link to the error as this dc doesn't allow it

proud pebble
#

you could also post your entire latest.log to mclo.gs

wheat sparrow
#

I tried mclo.gs and it was aluto dleted

proud pebble
wheat sparrow
#

i have, how do i proide the link?

proud pebble
#

you copy and paste it, then click the save button

#

then copy and paste the link from the url bar

wheat sparrow
#

ah i see, ok 1 secc

proud pebble
#

can you post the PlaceholderAPIHook class contents to paste aswell

wheat sparrow
#

ok

proud pebble
#

it could also be a bug with the current dev build your using

wheat sparrow
#

ah ive just thought, could it be that im getting the plugin description file to get the identifier, version and authour?

proud pebble
#

set persist to false

#

or hardcode the identifier

wheat sparrow
broken elbow
#

Well first of all you shouldn't really be using a plugin name as a description unless you know that name is fully lowercase. but also, why not save the name, authors, etc when it is constructed and use the saved ones?

proud pebble
#

like i hardcoded the identifier due to it never actually changing

wheat sparrow
#

thanks everyone

proud pebble
#

i recently switched to gradle from maven, and now im trying to figure out the best way to replace the version text in my plugin.yml with the version in my build.gradle.kts

broken elbow
#

replacetoken or whatever it is called

tight junco
#

Does Inventory#getContents() include armor and offhand or is that excluded

tight junco
proud pebble
#

like ive seen a couple tools for generating the full plugin.yml but dont really want to do that if i dont have to

proud pebble
#

getContents is all

broken elbow
#
    processResources {
        filesMatching("plugin.yml") {
            expand("version" to rootProject.version)
        }
    }
wheat sparrow
broken elbow
#

no problem

#

pretty sure you can not hardcode description and authors. I personally don't and never had issues

#

it's probably something to do with the plugin unloading before placeholderapi and whenever placeholderapi unloads after uses the identifier for something

proud pebble
broken elbow
#

${version}

proud pebble
#

ty

broken elbow
#

acording to the docs $version also works

#

damn

#

I didn't know all this

halcyon ermine
#

Hello everybody! Is it possible to intercept the packet of changing the player's health interface to the health of an entity (for example, when the player prays to a horse) and cancel it, so that the player has his health interface?

proud pebble
#

it is possible

#

you can uses protocollib to do this or by using netty

#

its possible to intercept any packet

dusky harness
#

I haven't checked though

dusky harness
#

but which packet is it?

dense drift
#
START TRANSACTION;

SET @AMOUNT_TO_BUY = ?;
SET @ITEM_ID = ?;

SELECT @AMOUNT_LEFT := (amount_left) FROM global_stock WHERE item_id = @ITEM_ID;

IF (@AMOUNT_TO_BUY <= @AMOUNT_LEFT) THEN
    UPDATE global_stock SET amount_left = (@AMOUNT_LEFT - @AMOUNT_TO_BUY) WHERE item_id = @ITEM_ID;
    COMMIT;
ELSE
    ROLLBACK;
END IF;```
Does this look fine by any chance? D: @dusty frost
#

Or well, not entirely wrong at least kek

dusty frost
#

But yeah looks pretty solid tbh

dense drift
#

transaction logging? thinkfused

#

like writing in a database that a user has bought n items?

dusty frost
#

Yes

dense drift
#

ah ok

proud pebble
#

or start riding

dusky harness
proud pebble
#

actually it might not be possible

#

since all i can find is set passengers

dense drift
#

I would assume if it was, people would've already done it - the ridden entity's health is annoying

dusty frost
# dense drift ah ok

I'm not sure how familiar with like accounting principles, etc. you are, but you should record every single thing that happens regarding money, so much so that if you lost the entire table of the current items for sale, you could recreate it from scratch just by following the transaction logs

dense drift
#

yeah I'm not D:

dusty frost
#

So you should have a table that records: every time a new item for sale is posted, every time someone buys anything, any time an item for sale is taken down/expires or whatever, etc.

#

You just want to know every single event related to this market system, including when it was, who did it, and any extra data about it

dense drift
#

It makes sense

#

I'm currently only experiencing with this transaction thing, but I will add the logs later

dusty frost
#

Yeah you definitely need it before you push it to live

#

You can basically never have too much logging in scenarios like these, I have learned that the hard way at my job lol

dense drift
#

Also, using mariadb over mysql applies for clients as well or only for the server? Meaning I can use the maria client to connect to a mysql database or not?

dusty frost
#

Uh, not sure about that way, but you can use the mysql client to connect to mariadb servers for sure

dense drift
#

ok then I will stick to the mysql client

minor summit
tired olive
#

Not just basically

#

It is

#

Its groovy tho 🤮🤮

stuck hearth
#

thonking 🤣

hoary scarab
minor summit
#

my brother in christ

#

for the 5th time, wrong channel

#

or just wait for mods to come 🌚

hushed tinsel
dense drift
broken elbow
#

Using the mongodb driver for java, is there a way to specify a trusted certificate (I have a .pem file) without adding it to the truststore? Directly from a file using code is what I would want to do basically. With the python driver you can just specify the certificate file path in the constructor for example. You can also do that with the command line

broken elbow
#

Or is it maybe possible to put a JKS file in the resources and somehow use it in the javax.net.ssl.trustStore property?

crisp oar
#

Wanted to ask really fast if its possible to have ae placeholder output a number instead of a string.

Essentially, I am trying to convert hex into decimal so I can apply a hex color to a tipped arrows custom potion color.
I have the code working but it is outputting the converted decimal as a string.
So if I try to use it in certain places to try and set the CustomPotionColor it sets it like this: CustomPotionColor: "16711735" instead of CustomPotionColor: 16711735

broken elbow
#

the one resulting from a placeholder

#

Right now PlaceholderAPI only supports returning of nullable Strings

crisp oar
#

Sadly there isn't a way for me to turn the string into an integer. I have to turn it to the string to have it returned by the placeholder and had intended to use the placeholder to convert the color to decimal since I cant use math in the configs.
But if it only outputs as a string then it won't work for what I am trying to do

broken elbow
#

I am a bit confused. Are you using the placeholder in code or in a config?

crisp oar
#

I made the placeholder in my code to take something like this: %decimal_00ff00% and have it output the decimal form of the hex like this: 65280
And that works, but it outputs the integer as a string.

So if I try to use it in various configs of plugins that support placeholders, it ends up having the value set as a string and not the integer it needs

#

Not sure if that makes sense or if I am explaining it poorly, been up all night and haven't had much sleep.

But I am trying to change the CustomPotionColor of a tipped arrow inside of a custom menu that is part of another plugin by setting the nbt data of the item in the config to have the placeholder as the value of the custom potion color

broken elbow
#

Yeah I understand what you're trying to do. Well, either way it isn't possible to make PlaceholderAPI return anything else other than a String. + There is the fact that you have to put the placeholder in a string in YAML. key: "%placeholder_here%". What you should be doing is getting the developer of your menus plugin to translate strings to integers or add an option for it.

crisp oar
#

Yeah, I had mentioned it briefly to them but I wasn't able to set the custom potion color manual so having a placeholder be taken into effect wouldn't help much either. Alright, well no worries lol

proud pebble
#

you can convert a string to int pretty easily

crisp oar
#

I am using String.valueOf(int) because I am turning the result of the conversion to decimal to a string so the placeholder returns it

proud pebble
#

or is there some reason why you cannot do this?

#

well if you need an integer and your using a string then you can do what i said to do

crisp oar
#
    public @Nullable String onRequest(OfflinePlayer player, @NotNull String params) {
        if(params.length() != 6) {
            return "Invalid HEX";
        }
        int decimal = Integer.parseInt(params,16);
        return String.valueOf(decimal);
    }
#

I cant use that inside of a config of another plugin

#

I could only do that if I was able to change the code of the plugin in question

proud pebble
#

is changing the plugin's code not viable?

crisp oar
#

Its not my plugin or it would be

The plugin that I have, which adds this placeholder, is just for custom placeholders to hook into various things

proud pebble
#

so the placeholder is to convert between hex and decimal?

crisp oar
#

Yes

proud pebble
#

does the plugin in question support papi placeholders in their config files?

#

cus if they did i wouldnt see why it wouldnt work

crisp oar
#

They do

proud pebble
#

weird

crisp oar
#

But at the same time its odd.
When I have a placeholder in things like the name of an item, it works but when I have it in the nbt data of the item it doesn't

proud pebble
#

what plugin are you attempting to use the placeholder in?

crisp oar
#

CommandPanels

#

I can show that it works in some cases

#

Or not, seems I cant post images here, which makes sense

neat pierBOT
proud pebble
#

you have to be a higher tier to beable to post images

#

command panels looks pretty similar to deluxemenus

crisp oar
#

Its fine, but the decimal does get put into the name of the item so the placeholder is working in the config

proud pebble
#

i can probably see why it wouldnt support it

#

tho it would be somewhat an easy fix

#

why not just modify command panels and recompile?

#

or get it working and then make a pull request so the owner of commandpanels can allows for placeholders to be used properly for the tipped arrow color

crisp oar
#

Well, that would work but wouldn't for future updates.
It could be possible to use their API to work with it, but that wouldn't solve the issue.
It would just be a work around for it.

They are looking into some of the things I had mentioned, the main one being the way they are setting NBT data to items isnt working properly.
But might do a pull request. That wouldn't be too out of the question.

broken elbow
#

Or there's the option of Pull Requesting

#

as well

#

yeah

crisp oar
#

Well, quite a bit lol
I have files that are hundreds of lines long lol
Dozens of menus and what not

broken elbow
#

Yeah then the best solution would probably be to add support for it yourself and then hope they'll accept your Pull Request.

worn jasper
#

might sound sus but how exactly do you post a library to github and make it available in a repo etc? To be precise, do I need any extra steps or just putting the project in github works? (for the github part) lol

#

never did one

rancid bronze
#

Location as HashMap key should be fine correct?

minor summit
#

no

#

Location is mutable and the hash code will change if it's altered, leading to all sorts of subtle bugs that will drive you insane

dense drift
rancid bronze
minor summit
#

(if world is important) I'd use the world name than the World object itself, but yes
if it isn't then just yeet it lol

rancid bronze
#

Yes yes world name will@be useful otherwise I’d just use a vector

minor summit
#

fair

robust flower
#

Hey there, I've been working on a Kotlin project that uses the Exposed library from JetBrains for database interactions with an H2 database. However, I'm facing an issue with table creation in the database.

My code initializes a Database class instance and calls the initialize() function, which should create the tables. However, when I call the awaitInitialization() function, it times out and throws an exception after the configured max await time has passed instead of gracefully finishing the program. The tables are not being created, and I'm not sure why this is happening. All the log.debug messages are printed without a problem, the initialize() function finishes after about a second of execution.

I've double-checked my H2 database configuration and made sure I have the necessary dependencies, but I still can't seem to find the root cause of the problem. Any help or guidance you could provide to resolve this issue would be greatly appreciated.

Here's all the relevant code: https://paste.helpch.at/domehecebo.kotlin

stuck hearth
#

What the fuck

#

What's the end goal you're trying to achieve with this code? -- #awaitInitialization

#

@robust flower

robust flower
#

This is a mangled code from my application, don't mind why I'm using awaitInitialization, the point is that the tables are never created no matter what

stuck hearth
#

Let me check something rq

robust flower
#

oh no, I just realized that I explained the error I had, not the error that I currently have 🤦‍♂️

#

the code runs just fine, but when I try to insert anything into the database, it throws java.sq.SQLException: Column "filesAmount" not found

#

sorry, I'm kinda sleep deprived today, started to mix infos already lol

stuck hearth
#

Your columns name is filesAmount

robust flower
stuck hearth
#

Ah, I was hoping it was a simple logic error 😛

#

I can't catch anything just looking at the code.
Is it generating tables?

#

Is that table in it?

robust flower
#
class RenameSessionRepository(
    private val database: Database,
    private val jackson: ObjectMapper,
) {
   suspend fun insert(renameSession: RenameSession) {
        awaitDatabase()
        transaction {
            RenameResults.insert { it.set(renameSession) }
        }
    }

 private fun UpdateBuilder<*>.set(renameSession: RenameSession) {
        set(filesAmount, renameSession.filesAmount)
        set(rules, jackson.writeValueAsString(renameSession.rules))
        set(startedAt, renameSession.startedAt)
        set(finishedAt, renameSession.finishedAt)
        set(renameTimings, jackson.writeValueAsString(renameSession.renameTimings))
        set(sessionState, renameSession.sessionState)
        set(id, renameSession.id)
    }
}

data class RenameSession(
    val filesAmount: Int,
    val rules: Collection<Rule>,
    val startedAt: Instant = Instant.now(),
    val finishedAt: Instant? = null,
    val renameTimings: RenameTimings = RenameTimings(),
    val sessionState: SessionState = SessionState.INITIATED,
    val id: UUID = UUID.randomUUID(),
)

data class RenameTimings(
    val calculateNewFileNames: LongAdder = LongAdder(),
    val renameFilesOnDisk: LongAdder = LongAdder(),
    val persistItemsToDatabase: LongAdder = LongAdder(),
    val removeItemsFromDatabaseQueue: LongAdder = LongAdder(),
)

The stacktrace

2023-04-28T23:32:02.743-03:00 ERROR   --- [atcher-worker-2] c.g.s.r.service.FileRenamerService       : Failed to persist RenameSession to database

org.jetbrains.exposed.exceptions.ExposedSQLException: org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "filesAmount" not found; SQL statement:
UPDATE RENAMERESULTS SET "filesAmount"=?, RULES=?, "startedAt"=?, "finishedAt"=?, "renameTimings"=?, "sessionState"=?, ID=? WHERE RENAMESESSIONS.ID = ? [42122-214]
    at org.jetbrains.exposed.sql.statements.Statement.executeIn$exposed_core(Statement.kt:49)
minor summit
#

oh deary

robust flower
#

The database file has 0 KB, even after this error

stuck hearth
#

Oh, so it's not even generating the tables just the file?

stuck hearth
#

Are you sure you need to create the database file?
I think SchemaUtils creates the file as well, I'm wondering if that's part of the issue

robust flower
#

You are right, the file history.db.mv.db is the one generated created by the SchemaUtils, and it has 24 KB so it must have the tables created.

robust flower
#

I inspected the H2 file through my own code (aka show columns from RENAMESESSIONS;), and this is what I got

filesAmount;INTEGER;NO;;NULL
RULES;CHARACTER VARYING(65000);NO;;NULL
startedAt;TIMESTAMP(9);NO;;NULL
finishedAt;TIMESTAMP(9);YES;;NULL
renameTimings;CHARACTER VARYING(10000);NO;;NULL
sessionState;CHARACTER VARYING(128);NO;;NULL
ID;UUID;NO;PRI;NULL

Which seems to suggest that the table RENAMESESSIONS does indeed have a field called filesAmount. After further inspection, I finally found the issue: enameSession repository was referencing RenameResults table, after I fixed that the issue disappeared, thanks for the help y'all

spiral mural
#

How can the getter that I have checked around 80 times for errors now return null object.

```

public void startSetup(UUID player, String arena) {
setupData.put(player, new HashMap<>());
setArenaName(player, arena);
setDisplayName(player, "&a&lSet Arena Display Name"); <-- getter for this...
setMinPlayers(player, 1);
setMaxPlayers(player, 3);
}It's set before the ask, yet somehow it always return object null.Caused by: java.lang.NullPointerException: Cannot invoke "java.util.Map.get(Object)" because the return value of "java.util.Map.get(Object)" is null```

#
        return (String) setupData.get(player).get("displayName");
    }``` is it me is the fact that while object map is good for memmory it's a nightmare to work with 😂
stuck hearth
#

Are you getting from the same map you set?
Does the map you're trying to get from have any entries?

stuck hearth
spiral mural
#

the map is getting entries in the startSetup() then after I open a menu and somehow it returns null object.

#

tried adding a Thread sleep cause I'm out of ideas didn't help 😂

stuck hearth
#

Would you share more code?
A paste site would be perfect.
You shouldn't be putting threads to sleep, that's not going to solve issues.

spiral mural
#

I know I shouldn't put them to sleep, just wanted to see if there was an issue with delay cause I've been looking at this same code for 3 hours now 😂

#

let me know if you need any other code

stuck hearth
#

Do you have the actual error you're getting?

#

Oh is the NPE from new MenuItems() ?

spiral mural
#

Yes, the error is ItemStack[] items = menuItems.getItems(menuUtilities.getOwner()).toArray(new ItemStack[0]); in this class, but before I even initiated this I set the object, so not sure why that would still be an issue.

Error https://paste.helpch.at/oxacenajit.rb

stuck hearth
#

Okay I see what's happening

#

So when the commands is being run you're creating a new instance of SetupManager()

Then you create an instance of MenuItems -- Which creates its own instance of SetupManager

So then MenuItems checks it's instance's list for the owner which is null.

#

So basically you need to ensure that SetupManager is a singleton, or you need to hold instances of it in a map; if you need multiple instances.

spiral mural
#

aha.. ok, what do you recommend to pass the singleton for multiple places? send instance of setupManager to the menuItems?

stuck hearth
#

Your sentence is confusing me, but passing an instance of SetupManager would be a good way to do this.

#

The design pattern is referred to as DI or dependency Injection

spiral mural
#

at this point I'll sacrifice the memory to use regular hashmaps 😂 appreciate the help!

#

I'm not ready for the object map methods..

stuck hearth
#

Oh wait, yeah why are you Doing Map<Sting,Object>

#

What's the object?

spiral mural
#

ehm 😂 you tell me? xd

stuck hearth
#

Oh I just realized what you're doing

#

good lord

spiral mural
#

elaborate? 😛

stuck hearth
#

You're just tossing complex objects into an Object, that's not going to work like you think it does.

#

Hold on

#

No I need to sleep. GL

lyric gyro
#

im making a KBWars minecraft plugin and i want to store players kills and deaths in a placeholder, where do i start with storing them in a placeholder?

#

expansion file; ```package com.matzouni.matzounikbwars.managers;

import com.matzouni.matzounikbwars.Main;
import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;

import java.time.zone.ZoneOffsetTransitionRule;
import java.util.UUID;

public class KBWarsExpansion extends PlaceholderExpansion {
private final Main plugin;

public KBWarsExpansion(Main plugin) {
    this.plugin = plugin;
}

@Override

public @NotNull String getIdentifier() {
    return "kbwars";
}

@Override

public @NotNull String getAuthor() {
    return "Hydro";
}

@Override

public @NotNull String getVersion() {
    return "1.0";
}

@Override
public String onPlaceholderRequest(Player player, String identifier) {
    if (identifier.equals("total_kills")) {


    } else if (identifier.equals("total_deaths")) {


    } else if (identifier.equalsIgnoreCase("add_death")) {

    }

return null;
}
}

modest peak
mortal scaffold
modest peak
#

the placeholder doesnt parse only after i reload placeholder api

#

so i dont think thats the problem

mortal scaffold
modest peak
#

yeah, it probably the solution

#

thanks

mortal scaffold
#

;3

fading stag
mortal scaffold
fading stag
#

it looks like I have to do refactor to my existing plugins :d lol

mortal scaffold
#

ahaha, I do not know under what circumstances placeholders are disabled, but it helped

minor summit
#

/papi reload is one of them

mortal scaffold
#

yes

spiral prairie
#

how do i make a player call a command that opens a deluxe menus inventory? because (for some reason) commands for menus arent registered, calling them as a player using dispatchCommand will result in an unknown command, so what should i do?

dense drift
#

player.chat("/command")

spiral prairie
#

does that work with regsitered commands too?

#

it should

dense drift
#

Yes it does

shy canopy
#

Hi!

Is there way to create nether portal to x world...

hard violet
#

Looking for someone who knows solidity and can make an MEV bot. (Arbitrage trading bot) payment up to 15k

dusty frost
tame wharf
hoary scarab
# shy canopy Hi! Is there way to create nether portal to x world...

Use EntityEnterPortalEvent and check if the portal is a nether portal.

@EventHandler
public void onPortalEnter(EntityEnterPortalEvent e) {
    Block block = e.getLocation().getBlock();
    Material blockType = block.getType();

    if(blockType != Material.NETHER_PORTAL)
        return;

    // Teleport code
}
shy canopy
hoary scarab
shy canopy
#

Im trying do like when player run /nether he got teleported to nether and his location got created portal. It's look like there is no api for that....

Putting nether portal frame on player location seems little bit sketchy.

shy canopy
#

Yeah... It seems i need for that packets but they sucks 😞

hoary scarab
#

But you would have to do the calculations for portal placement if you want it done right.

hoary scarab
#

🤦 I see what you're saying now. You want to act like they're in a netherportal with out having one.

#

You could set the block at the players feet to a netherportal untill they teleport... (Don't need the whole frame.)

shy canopy
#

No, location where player got teleported I want nether portal but not there where player run nether command...

But thx for help ❤️

hoary scarab
#

Could also just use minecrafts cached shapes

shy canopy
#

Yeah... I was hoping if that would exist in spigot or paper api... I probably create portal manually

hoary scarab
#

Could also just uses the worlds PortalForcer
worldserver.getPortalForcer().createPortal(blockposition, enumdirection_enumaxis, this, createRadius)

final sequoia
#

Hello, does anyone happen to have an idea how I can influence the order of the plugins when joining a user?
I practically have a NetworkFilter and a ban system. I banned my second account as a test and would like the ban system to take effect before the network filter makes its query.

proud pebble
#

afaik load before exists

#

so you could use that

final sequoia
#

OK, I'll take a look. The problem is that the NetworkFilter has a limited number of API queries and I want to offload them a bit. Banned players should therefore already be prevented from entering by the ban system so that the NetworkFilter cannot make a request.

proud pebble
#

well loadbefore would make it so that the ban system would load before the network filter

#

or atleast i believe it would

final sequoia
#

Okay.. yeah.. I'll take a look. Thank you :D

spiral mural
#
                    itemMeta.removeItemFlags(ItemFlag.HIDE_ENCHANTS);
                    itemMeta.removeItemFlags(ItemFlag.HIDE_POTION_EFFECTS);```
Isn't this enough to remove these?
warm steppe
#

u could use ItemFlag.values()

wind tapir
#

Hello, does anyone know how to bypass nametag limit with ProtocoLib ? Thanks

silent trench
#

So, I've made a custom shaped recipe (see the code below), but the result is not showing and the PrepareItemCraftEvent gets fired with the value of the recipe as null.
Code rewritten to Java:

final ShadedRecipe doubleCurseDoll = new ShapedRecipe(new NamespacedKey(this, "double_curse_doll"), new VoodooDoll("ERROR", 2).itemStack)
doubleCurseDoll.shape("DU ", "   ", "   ")
final ItemStack voodoo = ItemStack(Material.FISHING_ROD)
final ItemMeta voodooMeta = voodoo.itemMeta
voodooMeta.setCustomModelData(4)
voodoo.setItemMeta(voodooMeta)
doubleCurseDoll.setIngredient('D', voodoo)
doubleCurseDoll.setIngredient('U', Upgrader(1).itemStack)
getServer().addRecipe(doubleCurseDoll)

Original code in Kotlin:

val doubleCurseDoll = ShapedRecipe(NamespacedKey(this, "double_curse_doll"), VoodooDoll("ERROR", 2).itemStack)
doubleCurseDoll.shape("DU ", "   ", "   ")
val voodoo = ItemStack(Material.FISHING_ROD)
val voodooMeta = voodoo.itemMeta
voodooMeta.setCustomModelData(4)
voodoo.itemMeta = voodooMeta
doubleCurseDoll.setIngredient('D', voodoo)
doubleCurseDoll.setIngredient('U', Upgrader(1).itemStack)
server.addRecipe(doubleCurseDoll)

Passed items (NBT, showed using /data get entity PLAYER_NAME):

Inventory: [
  {
    Slot: 0b,
    id: "minecraft:fishing_rod",
    tag: {
      Damage: 0,
      CustomModelDdata: 4
    },
    Count: 1b
  },
  {
    Slot: 1b,
    id: "minecraft:enchanted_book",
    tag: {
      CustomModelData: 2,
      display: {
        Name: '{
          "text":"§4Double curse"
        }'
      }
    },
    Count: 1b
  }
]

Btw code is being ran in the main class

Video: https://cdn.discordapp.com/attachments/1102568434493046794/1102570722984996964/video.mp4

#

Sending the Upgrader class which I forgot to send:
Boring Java 😃:

class Upgrader() {
    final ItemStack itemStack = new ItemStack(Material.ENCHANTED_BOOK)
    
    Upgrader(int level) {
        final ItemMeta meta = itemStack.getItemMeta()
        meta.displayName(Component.text(level == 1 ? "§4Double curse" : "§5Triple curse"))
        meta.setCustomModelData(level + 1)
        itemStack.setItemMeta(meta)
    }
}

Kotlin 🔥:

data class Upgrader(val level: Int) {
    val itemStack = ItemStack(Material.ENCHANTED_BOOK)

    init {
        val meta = itemStack.itemMeta!!
        meta.displayName(Component.text(if (level == 1) "§4Double curse" else "§5Triple curse"))
        meta.setCustomModelData(level + 1)
        itemStack.itemMeta = meta
    }
}
river solstice
#

Java 😎

K 🤮 tlin

worn jasper
#

Any ideas why I am getting this: Process 'command 'C:/Program Files/Java/jdk-18.0.2.1/bin/java.exe'' finished with non-zero exit value 1? Like, I have to restart IJ every time and I can only run it once...

sterile hinge
#

find out why the process finishes with a non-zero exit value

worn jasper
#

unable to find anything, there is no info that I can use

silent trench
# wind tapir wtf is that shit

Some random stuff, already fixed the problem, forgot to mention (it was about the difference when passing Material and ItemStack to the recipe...)

silent trench
proud pebble
#

or atleast it was the last time i looked

wind tapir
#

bruh

wind tapir
silent trench
wind tapir
silent trench
river solstice
stuck hearth
#

Kotlin is nice

slender temple
#

I want to return a TextComponent using PlaceholderAPI, but I want to keep the properties of it.

If this is turning into a xy problem, let me make this more clearer: I want to return a text with custom font (as you can add custom fonts using resource packs) using PlaceholderAPI.

grim oasis
#

BaseComponent#setFont

#

key might be minecraft:test

slender temple
#

I mean, that's a component

#

And I can't return it with PAPI :/

grim oasis
#

is it possible to store a custom font within a string

slender temple
#

I'm looking for that

grim oasis
#

like, color is something like §acolor

#

right

sharp hemlock
#

I don’t think that’s possible

#

Unfortunately

#

As no matter what the implementation will always return and some plugins manipulate those strings and are obviously expecting it to not be a component

silent trench
gloomy tusk
#

Hey, I'm overriding PlaceholderExpansion#getPlaceholders but they're not showing up in tab-completion in /papi parse

dense drift
#

the placeholders are suggested only after you type %identifier_ iirc

mental cypress
#

Yes that sounds correct.

gloomy tusk
broken elbow
#

I completely forgot to raise a ticket about this at the time I found this out

dense drift
#

I was about to say that

gloomy tusk
#

oh that's weird

#

ok so it's on the papi end

broken elbow
#

Yeah. The tab completion is weird. going to raise a ticket as I feel this should be considered a bug

dense drift
#

open an issue Blitz and I will take a look when I get time if you don't do it first

broken elbow
#

👍

gloomy tusk
#

thanks guys

broken elbow
dense drift
#

yeah looks like

broken elbow
#

@gloomy tusk can you provide the response from /papi dump please?

gloomy tusk
#

sure

dense drift
#

by later I mean probably tomorrow

broken elbow
broken elbow