#help-development
1 messages · Page 86 of 1
Those also have capacitors
how would you clean it 💀
on discord
no, here
FECK
Once you're verified your nickname is set to your forums username
nono im poor for that
would an earbud and some alcohol clean it properly
....
..........
Hey guys. code origination from external pom.xml package from github (via jitpack) is suddenly giving me noMethod error after new compile.. yet I dont think I recently changed anything, what do I do? I use IDEA
I tried updating the version but I am still on the latest "tag"
?changename
Name changes on the forums are granted to those who have donated to the project. Donations are processed manually and generally take up to 24 hours. The donation widget can be found on the home page of SpigotMC at: https://www.spigotmc.org/.
originating*
yes. the best you can
did that github repo change?
do i just clean it best i can and hope it works?
10$??? IT'S MY WHOLE FORTUNE
Doesnt seem to work, and main class path is same regardless, must be not it, right?
EDDGALR
ONE MORE QUESTION
nevermind i forgot google exists
wait no
ARE DUCKS GREEN?
.-.
hnmh, barbecue
doin ur mom doin doin ur mom
I'd stop there before the mods come by
@green prism do you actually want a code review
yES
it's bad ik
It just makes sense for that kind of plugin
hmh
Like an undefined gender?
X Gender?
@Override
public void onDisable() {
for(Player p : Bukkit.getOnlinePlayers()) p.closeInventory();
}```
This seems bad
Solved.
It could force them out of inventories unrelated to your plugin
No, just a separate option for it
Pronouns don't necessarily have to be related to gender
hmhmhmhmhmhm
Do note that bukkit automagically does that on disconnect
It's always recommended
Or better said minecraft
@green prism i noticed you have a seperate Listener class for all your inventories. that can easily be reduced to just 1 listener
Unless you use the reload command
And what's personHashMap used for?
But as I said, reload command bad
There is not much that can go wrong outside of a short-circuit
gimme a moment, Im solving everything and I tell you
So the worst thing that can happen is a small fire and a triggered breaker
Person playerIdentity = personHashMap.get(player.getName());
Oh..
You should really use UUID for that
you must be fun at parties
Yes, people miss out a lot from me when I do not show up
lmao
This class has tons of whitespace between some methods
I find myself better to read the name of a class and know that there inside you will find everything about
hmhmhm
There also seems to be a lot of static abuse going on here
wher
what can I do about that hmh
?di
Guide to dependency injection: https://www.spigotmc.org/wiki/using-dependency-injection/
why not have a proper inventory system and have 1 class to handle that inventories look and its funtionality as well?
@waxen plinth uh
ouch, that's a good idea
suppose hashmaps
wat
had in their constructor
Look at the link the bot sent
It's a better way to design object oriented projects
is having a public static variable in ur main class bad even if the variable type is a class that's only initialized once
make it final and you are good
Static abuse makes your code more inflexible, and harder to unit test if you want to do that
what if its initialized in onEnable for example
i cant fucking do it
u cant make it final
nope
im confused
im too scared
im both
????
Dependency injection is simple
i need some reassurance
Rather than using static fields
that nothing will go wrong
Pass dependencies into their dependents
public static final HashMap<String, Person> personHashMap = new HashMap<>();
what if u cant make it final, since its initialized in onEnable
not good
That's still static abuse
HMHMHM
my name is Mike
my name is walter hartwell white
my name is Gustavo Fring
is having a public static variable in ur main class bad even if the variable type is a class that's only initialized once
If it's the plugin object it's generally fine
omg gas stone and fridge
no, it's not
But for just about anything else you should avoid static fields
what if I create a new class with that static abuse and initialise that from the onEnable?
No
It makes your code inflexible
The plugin is never going to be extended
It's instantiated once and anything that needs it needs that one specific instance
Now, ideally you should still inject it
what about that
@Getter
private HashMap<String, Person> personHashMap;
@Override
public void onEnable() {
this.personHashMap = new HashMap<>();
But exposing a static getter or field for convenience in API is fine
- Enforcing that the field type is only initialized once
- Enforcing that the class that has the field cannot be extended
That map have a key type of UUID, not string
don;t expose teh Map, getter and setter on contents
And the field should be a Map, not a HashMap
You can, but should still prefer dependency injection
For singletons it's fine to have a static getter or field though
public HashMap<UUID, Person> personHashMap;
@Override
public void onEnable() {
this.personHashMap = new HashMap<>();
Not public
HashMap -> Map
Make a getPerson(UUID) method
You can, but you should generally not expose that kind of thing directly if you can avoid it
Think of it this way
oK
You run a business in your home
a millionaire business
player.addPotionEffects(new PotionEffect(PotionEffectType.getByName("BLIND")), 1, 10);
PotionEffectType#getByName requires a string but shows an error when I put the string there
You invite people in and make them coffee
Would you give them the keys to your house to come in and ask for coffee?
Or would you have them ring the doorbell so you can serve them?
So, if i have this:
public final class A {
public static final B b = new B();
}
public class B {
public B() {
if (objectAlreadyInitializedBefore) {
throw new RuntimeException("Initializing Failed");
}
}
}```
is having the field "b" as it is, okay?
The singleton instance should be in its own class
is it okay though
Besides that yes
since that's literally what bukkit does
lol
in this case B is the plugin and A is bukkit
Singletons are basically the only time you should ignore DI principles
so using public static is fine as long as these two rules are met
Not always but they're a good rule of thumb
,
What's worth noting is that you should only do that if you need the SPECIFIC instance
If any Plugin instance will suffice, inject
public Person getPerson(UUID uuid) {
return personHashMap.get(uuid);
}
public UUID getUUID(Person person) {
for (UUID uuid : personHashMap.keySet()) {
if (personHashMap.get(uuid).equals(person)) {
return uuid;
}
}
return null;
}
I see
e.g. registering listeners or similar
Im randomly spawning campfires
but I don't want them to be inside/on trees
should I try to scout some radius around the tree for free spot without trees or somehow remove the tree?
Do you need the UUID of a person?
HOYLY CK
YSE
THE CHARGER WORKS
AND THE ELECTRICITY IS STILL HERE
this isnt shitposting i genuinely had troubles with my charger 💀
proof here
Maik, feel free to start a thread if this channel is too chaotic
Hello guys, how can I make a city build plugin? I want to create one my own
can u describe it a bit more
Ive 19 errors to solve before
Oh lol
I know that these design principles might seem just annoying on a small project
But they help make sure it can scale
whats that supposed to do?
main.getPerson(p.getUniqueId()).setAge(actualAge);
When structuring large codebases it will keep things clean
You mean for when the person doesn't exist?
You could have a getOrCreatePerson method
I mean, if I get the person and then do the age set, the person’s value in the hashmap is no longer up to date, right?
It's returning the object
The object isn't copied in the process
It's the same one
So if you change it, it will be reflected in the map
So this will do something
main.getPerson(p.getUniqueId()).setAge(actualAge);
cool
lmao
Yes
Do you mean me
Your command code can also be cleaned up a lot
how, I don't understand how to use a commandframework
yes
I want to start small. first that this world is created with the plots
Is it possible to programmatically remove the when player teleports using Player#teleport(location) spam console with "Player moved too quickly! (coords)"
yes
but i dont recommend it
use System.setOut
System.setOut(new PrintStream(System.out) {
public void println(String s) {
// here, we check if the message being written in console doesnt contain "moved too quickly", so if it does it wont be printed
if (!(s.contains("moved too quickly"))) {
super.println(s);
}
}
});```
i want to spawn a mob without AI . can enyone help ?
Is there anyreason why its detected as moving too fast when teleporting?
as far as i know
teleporting isnt actually teleporting
it just moves you extremely fast
oh wth lmao
or
Look into the spigot.yml file for the following:
moved-wrongly-threshold: 0.0625
moved-too-quickly-multiplier: 10.0
Might need to adjust those higher for the first. Maybe increment by 0.0025 to see if it makes a difference.
import lombok.experimental.UtilityClass;
import me.frandma.soup.Soup;
import org.bson.Document;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import java.util.function.Consumer;
@UtilityClass
public class Kits {
public void createKit(Player p, String kitname){
Document document = new Document("kitname", kitname).append("displayitem", p.getItemInHand().getType());
ArrayList<ItemStack> items = new ArrayList<>();
for (ItemStack item : p.getInventory().getContents()){
items.add(item);
}
document.put("items", items);
Soup.kitCol.insertOne(document);
}
public void claimKit(Player p, String kitname){
Soup.kitCol.find().forEach((Consumer<Document>) document -> {
if (document.get("displayname").equals(kitname)){
ArrayList<ItemStack> items = (ArrayList<ItemStack>) document.get("items");
for (ItemStack item : items){
p.getInventory().addItem(item);
}
p.sendMessage("Claimed kit §b" + kitname + "§f.");
}
});
}
}
```https://paste.md-5.net/qoqatokofa.bash
oh
did it the opposite way
reload command, 🤮 🤮 🤮 🤮 🤢 🤢 🤢 🤢
me and my Gs just flip the electrons that represent the status of the server
ayo
helwp
owo
?notworking
"Does not working" is a useless statement. Please describe what exactly is not working, what you expect it to do, and what actually happens. If you get any console errors, also ?paste the entire stacktrace.
can u show this info please
what's this line at me.frandma.soup.kits.Kits.createKit(Kits.java:21)
Kits.createKit(p, args[0]);
i did /kitcreate boat
with boat
in hand
{|
thumbs u]p
because it doesn't know how to save a material in mongo
you probably need to toString() it
arraylist itemstack
string too?
the ArrayList<ItemStack> items = new ArrayList<>();
ima try
might be
cause i connected to the mongodb database wrong
MongoClient mongoClient = MongoClients.create("mongodb+srv://crackma:password@crackma.gasczoq.mongodb.net/?retryWrites=true&w=majority");
MongoDatabase database = mongoClient.getDatabase("soup");
playerCol = database.getCollection("players");
}
private void mongoConnectKits() {
MongoClient mongoClient = MongoClients.create("mongodb+srv://crackma:password@crackma.gasczoq.mongodb.net/?retryWrites=true&w=majority");
MongoDatabase database = mongoClient.getDatabase("soup");
kitCol = database.getCollection("kits");```
i did it right yes?
Why do you always create a connection?

you have converted the object toString
it is now a String
its a string that looks like an arraylist
If you mean a string that can be converted back in ArrayList: no
u can tbh
ok so
the problem is
i cant convert itemstack to string
for some reason
and its erroring
wrong image
thats casting it to a string
No, ItemStack will print object reference
is there any way to override the default bukkit ban message
You have to serialize it. You can use Gson
Multiple possibilities: create your own serializer, find one, or use an existing method which should exist
Exactly
https://www.spigotmc.org/threads/serializing-and-deserializing-itemstack-with-gson.277972/ random thread I found on the topic
what is serializing
Changing an object into a form of data that can be stored for later
In your case, converting an ItemStack to a String.
i dont understand
is there any way to override the default bukkit ban message
at org.bukkit.inventory.ItemStack.addEnchantment(ItemStack.java:401) ~[paper-api-1.19.2-R0.1-SNAPSHOT.jar:?]```
im trying to apply "sharpness" to a Material.BOOK
send code
ItemStack outputItem = new ItemStack(Material.BOOK, 1);
outputItem.addEnchantment(Objects.requireNonNull(Enchantment.getByKey(NamespacedKey.minecraft("sharpness"))), 2);
yap
thanks for help lemme test it
is there any way to override the default bukkit ban message
I bet you can configure it
how
Have you tried bukkit.yml or spigot.yml ?
Then program it
Listen for prelogin
If banned
Set the message
Boom
Easy
hey I know this has probably more to do with the java language itself.
But since what I'm struggling with involves Events and the need for Events to be registered (therefore instantiating the class where those events are declared in), I think here is a good place to ask.
So let's say I want to create a different inventory menu for every player, where the inv's title is the player's name.
I create a class called Menu, declare a private Inventory inventory, use a constructor in that class to perform something like inventory = Bukkit.createInventory(player, 27, Component.text(player.getName())); and create a getter for that same inventory.
Now when I want to create that inventory and open it I would do Menu menu = new Menu(player) and player.openInventory(menu.get(player)).
This works fine, and I can pass this menu instance to whatever class I want it used, for example a MenuItem class to say create and add items to that menu.
Problem is: what should I do if I want to check if one of these menus has been clicked in by the player, using the InventoryClickEvent. I obviously can't pass the instance to the InventoryClickEvent class cause that's being registered in the onEnable() method in the main class.
Would a static HashMap where key is Player and value is Inventory make sense for this situation? Or is there a better way of doing this? Thanks in advance.
You can register a listener when a menu is created
Make the Menu itself a listener if you want
Otherwise a map is the best solution
But do a map by UUID, not Player
right, because if that player leaves the server and joins again, it's no longer the same object
is this something that is usually done? It seems pretty smart to me now that you pointed it out
Yeah it's pretty common
How do I suppose configure this to run Server from Inteliji?
?jd-s
is it bad practice making it static? or does it make sense in this situation because there is only one copy of that map, class owns the map, etc.?
what exactly do you mean by this? I think I know what you're talking about, just so I'm 100% sure I understand cause consensus on what situations static is okay to use is so ambiguous
If it's only used internally within that class, that's the ideal setup
If its only to be created once, you could use a singleton?
yap, but I should be okay with then creating a public static getter in that class that gets inventories from the map, right?
That should be fine. Tbf its really your decision on your code design.
Is there a way to check if a hostile mob can attack a player
I'd avoid it if possible
Shouldnt every hostile mob be able to attack? Can you elaborate?
Basically check if the mob is being farmed
I need a Boolean of if the entity has a path to the player
oh yeah? then how would you go about doing what I'm trying to accomplish? just go with registering the listener when menu is created?
if I do go with the Map route, how should I do it? sorry for so many questions, really want to get this matter taken care of in my head lmao
cause if I make the map static, that would be with the intention of then accessing it from other classes
EntityTargetLivingEntityEvent, this is the event that is triggered when it targets another Entity.
Ok
You can access it from other classes
It's not ideal design
But it's unlikely to matter
ideal should be?
Make a manager class
if you can summarize it
That holds the map, you pass the manager around to whatever needs it
I've send you manager example
Hey, so I was able to fix my config issue thanks to @waxen plinth's awesome library, but now I'm facing a new issue, essentially, I need to get offline players by their name or UUID, but the server that the plugin is being ran on is in offline mode to work with Bungee, but offline mode server's can't get offline players the same way as online ones, how can I go about getting an offline player on an offline mode server?
Might need to invoke authlib
Yeah, that's what I thought, do you think there's any way to avoid something like that?
Output on offline mode server: [CraftPlayer{name=JohnnyGooodTime}]
Same output on online mode server: [CraftOfflinePlayer[UUID=fc1baadf-af0c-403b-a7f4-fa50f68d92f7]]
These are two different players, but you get the idea of the difference of how it works.
?jd-s
Can somebody help me with my question?
Hello guys, how can I make a city build plugin? I want to create one my own
No
It's harder then you think it is
Ik
I think better to make extention for some plot's plugin then reinvent wheel
Ok
wouldn't this mean I'll have to create a Manager instance everytime I create a Menu?
No
You would create one and pass it around
Did you ever seen that ?
its definitely possible with packets or something
lets hope its not handled client side
i doubt the api has it
but maybe packets do
this looks like it
https://wiki.vg/Protocol#Set_Camera
no
Is it possible to create Crafting inventory?
you shouldn't be checking titles for inventories, you should store the inventory somewhere else and check if it's the same one
NVM I should use InventoryType.WORKBENCH instead of InvenotryType.Crafting
final ScheduledExecutorService executorService= Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
int count=0;
@Override
public void run() {
if (count==10)
executorService.shutdown();
player.sendMessage("working "+var);
player.getWorld().spawnEntity(player.getLocation(),EntityType.CHICKEN);
player.sendMessage("test");
count++;
}
},1,1, TimeUnit.SECONDS);
Hey I was trying to run the above part of the code but this spawnEntity line is giving some issues
the code works fine without that line
You get error because spigot code need to be run on the spigot thread
player.getWorld().spawnEntity(player.getLocation(),EntityType.CHICKEN);
player.sendMessage("test");``` this chunk of code
thats because that needs to be sync iirc
You can not use any spigot api from a different thread
Unless its specifically stated
umm .... any fixes possible... basically I need to spawn a chicken at a particular location every second for a minute
yea. make it sync
?scheduling
?scheduling
public void test(Player player, Plugin plugin)
{
int seconds = 2;
Bukkit.getScheduler().runTaskTimer(plugin, (e) ->
{
if(count == 10)
e.cancel();
/* player.sendMessage("working "+var);
player.getWorld().spawnEntity(player.getLocation(),EntityType.CHICKEN);
player.sendMessage("test");*/
count ++;
}, 0, 20 * seconds);
}``` you can make it like this
Minus this atrocious bracket style
if (condition)
{
}``` looks so terrible
@lost matrix you are welcome
You just made it worse

Just add more lines. If you want to edit an existing lore then you can use the methods of List to edit the lore to your liking.
In newer java versions you can also just do this
ItemMeta meta;
meta.setLore(List.of(
"Line one",
"Line two",
"Line three"
));
naming conventions
Side note: List.of is actually Arrays.asList on java 8 :)
Does this have a varargs param?
Yes
afaik Arrays.asList can be a bit cursed
c# code style sucks
actually depends
Really depends on the version
On some java versions it's mutable
on others it's immutable
Although you can also make the point that List#of has better performance
Yeah but it's not compatible with older versions and all
not a thing on java 8 type deal
One more benefit
Returns a fixed-size list backed by the specified array. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array. The returned list is Serializable and implements RandomAccess.
I feel like that would break that contract
kinda wouldnt
because the stupid mfs that wrote the Arrays class made their own ArrayList class just to break consistency
oh lol
That being said List#of is unmodifiable in it's contract
So Arrays#asList cannot delegate to List#of without breaking it's contract
is there a way to detect if the player sent /kill in the entity damage event? Since /kill seems to send a void damage event, however, I'm trying to detect if the player is in the void
you'll have to track that manually
dam alright
Yes
Depends
bruh
Make a multimodule maven project if you're using nms
what
One module per nms revision
what
The package it all together and you're done
what's nms? can you speak in simple words
Then a 1.16 plugin already supports 1.19
^
If you do not use anything that isn't public API mc versions do not matter starting from 1.14+
As long as you don't do anything too cursed, java versions do not matter either
is that too cursed?
Should still add pronouns
ahaha
A placeholder for those so you could have them show up when you hover over someone's name
I will in the update n'999
That would be perfect
wat ahah
Also what do you guys think about https://www.spigotmc.org/resources/harvesterhoe.104388/?
(screenshot of decompiled code for those that are too lazy)
I have code for that
I like the code. It is easy to understand
Almost all of the event listener classes (probably are 40) are near identical
wilding
bruuuh does it have different listeners for each crop for each enchant?
Yep.
40 event listeners just for this
lmao
Even more crazy: For each enchantment level
wtf
the math for enchantment level is so easy
there's a whole ass wiki page on it
And it hard-depends on claimchunk (which is a pretty obscure plugin imo)
yeah
what the fuuuuuuuck am I looking at
so what does it do per listener
like unbreaking 3 listener is the same as unbreaking 1 listener just less damage?\
Yes
Fortune 0 Beetroots = 1
Fortune 1 Beetroots = 1 to 2
Fortune 2 Beetroots = 1 to 3
Fortune 3 Beetroots = 1 to 4
same with rest
Unbreaking 0 Tool Damage 4
Unbreaking 1 Tool Damage 3
Unbreaking 2 Tool Damage 2
Unbreaking 3 Tool Damage 1
?paste
i was able to use hasLineOfsight to check if the entity that was killed was farmed maybe using a grinder but how can i make a check for if they are in a hole or are stuck in flowing water where they cannot get to the player
and just get the material why there a diff listener for every item
😩
Floodfilling would be the best bet there I assume
Do note that checking if the mob is spawned from a spawner (which is tracked by paper for sure, probably by spigot too) is a far safer and less resource-intensive way of dealing with player farms
what about those big tall grinders people make using the dark to spawn all the mobs
Mob spawn caps do exist...
You are kinda solving a problem that doesn't exist with tools that make the problem worse
Spigot mappings is something from the past
minecraft already knows if the pathfinding of a mob can hit a player so why can't i check if entity has a path to player
¿paste
?paste
thanks
Assuming if you did that and it would work as intended. Are you seriously going to despawn all mobs near the player if the player closes the door?
I'm going down the rabbit hole they have so many plugins 😩
I kinda have the feeling that they are farming something on spigot
Holy fuck
no
Is this what happens when you never get anyone to look at your code
😩 bro
they made a million classes for subcommands to spawn every mob
and the only changes are things like "/spawner phantom" "/spawner pig"
Living the enterprise dream
@quiet ice this guy wants a plugin that decreases drops on mobs that had no way to fight
basically if it was a free kill
this shit is so fucking annoying
I was like "tf this guy shade into a plugin --that is basically a simplified /give command for spawners-- to make it 125KB"
minecraft already knows if the entity can attack the player
basically i need to check if the entity is locked onto a player
?jd-s
the only thing that changes in these classes are the api methods they don't even use
If mean you can check if there is a player near the mob, if it is you can do a small amount of floodfilling to check if the mob could reach the player
Unfortunately, bukkit/spigot does not expose any pathfinding/goal API
one day
Although there is https://hub.spigotmc.org/javadocs/spigot/org/bukkit/entity/Mob.html#getTarget() to check if the mob is aggro towards the player
what the fuck
my local servers icon is cursed or smth
looks like the optifine cape layout
thats localhost
So in spring boot hibernate if I have a Car entity that have a Garage annotated with @ManyToOne so is it always necessary to annotate the Garage with @OneToMany as well?
Better than the entity one being called Hurtable or some shit
Protip: In eclipse you can prevent packages from being auto-completed
Protip: Use IntelliJ
As such in eclipse you will not have the issue that you will automagically auto-complete java.awt.List, because that class is in that list (for a while the entire java.awt package was in that list, but they removed it for making swing near unusuable)
yeah i occasionally import fucking java.awt.List
its one of those little things which are extremely annoying
hey adele
can you leave a review pls (:
https://www.spigotmc.org/resources/identity.104776/
Im a good guy
nobody cares about your plugin
IEntityCanBeHurt
:c
I mean he never said a good review
default.png being messed up moment
huh, then either that is something specific to localhost, or your server software is a bit strange
Imagine not setting a custom server-icon.png
https://paste.md-5.net/zufivoqive.java i think i recreated the main part of the plugin in 42 lines of code, except that the stupid drops wont spawn for some fucking reason
oh the .setUnlimitedLifetime(true) was for testing
lets gooo
Discord Android 😏
What do you mean? Do you have error?
Just input the version you want and update your pol
Pom
If doesn't work, run buildtool
alr thx will try
so, im guessing I cant extend JavaPlugin here (Line 24)
public class Move extends JavaPlugin implements Listener {}
Error
[14:59:48] [Server thread/ERROR]: Error occurred while enabling OreIgin v0.1-BETA (Is it up to date?)
java.lang.IllegalArgumentException: Plugin already initialized!
at org.bukkit.plugin.java.PluginClassLoader.initialize(PluginClassLoader.java:225) ~[spigot-api-1.19.2-R0.1-SNAPSHOT.jar:?]
at org.bukkit.plugin.java.JavaPlugin.<init>(JavaPlugin.java:53) ~[spigot-api-1.19.2-R0.1-SNAPSHOT.jar:?]
at me.teleputer.oreiginplugin.listeners.Move.<init>(Move.java:24) ~[?:?]
I just wanted to start a bukkit task for my Move event
what is line 24
java.lang.IllegalArgumentException: Plugin already initialized!
You can;t create a new instance of yoru main class
is the default walk speed 0.2f?
ProtocolLib solution: https://wiki.vg/Protocol#Set_Cooldown
yes
How can i fix this error https://pastebin.com/U7V1utVw
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
?
is this your plugin?
ty
by ensuring checking for nulls in your command class
also 1.12 :/
/**
* Apply enchants to item here according to TeamUpgrades.
*/
switch (afterUnderscore.toLowerCase()) {
case "stick":
final var sharpness = gameStorage.getSharpnessLevel(team).orElseThrow();
if (sharpness > 0 && sharpness < 5) {
newItem.get().addEnchantment(Enchantment.KNOCKBACK, item.getEnchantmentLevel(Enchantment.KNOCKBACK) + sharpness);
}```
when I put "item.getEnchantmentLevel(Enchantment.KNOCKBACK)" "item" returns as an error. Any idea why?
Im trying to get the current knockback level of the stick that is selected and ADD it to the sharpness variable.
**FIXED**
changed "item" to "materialItem"
pdc on players are saved?
Big question, and yes I've googled it but the solutions all don't work or only show 4 events not every single event.
I want to know when any event in the entire game is fired but without creating a ton of event handlers just one that listens for all events.
(1.8.8 server version)
pluginManager#registerEvent(Class, Listener, EventPriority, EventListener, Plugin) will fix it
but given you're using 1.8 I suggest you make the listeners by yourself because clowns are supposed to make us laugh
you expect me to #1 know every single event in the entire bukkit api
and also that would defeat my purpose of making the plugin im making
javadoc
im making an custom event manager
Remove the entire purpose of making the plugin though, it'd be a huge waste of my time to just do that lol
example of what im making
EventManager.newEvent(PlayerJoinEvent.class, new Event() {
public void onEvent(PlayerJoinEvent event) {
}
})
would it be possible to skull.setOwningPlayer(); but using a png file?
uh no
actually
yeah no u'd need a player name
with that skull
u could change ur skin
and get the texture id
and yeah
do that\
i have the textureid
but what do i do with it
alr
public ItemStack getCustomSkull(String url) {
ItemStack head = new ItemStack(Material.PLAYER_HEAD);
if (url.isEmpty()) return head;
SkullMeta skullMeta = (SkullMeta) head.getItemMeta();
GameProfile profile = new GameProfile(UUID.randomUUID(), null);
profile.getProperties().put("textures", new Property("textures", url));
try {
Method mtd = skullMeta.getClass().getDeclaredMethod("setProfile", GameProfile.class);
mtd.setAccessible(true);
mtd.invoke(skullMeta, profile);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
ex.printStackTrace();
}
head.setItemMeta(skullMeta);
return head;
}
url would be texture
// Example
getCustomSkull("eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTc2MmExNWIwNDY5MmEyZTRiM2ZiMzY2M2JkNGI3ODQzNGRjZTE3MzJiOGViMWM3YTlmN2MwZmJmNmYifX19");
yw
no idea how it works but 🤷♂️
game profiles is a json object
you are adding a key pair value
textures and then the url
then it sets the profile using reflections
to the gameprofile class
then it invokes method
setsmeta
returns head
Mind if I yank
yank the code sure
its public code
i think i got this code from a bukkit forum 2 years ago
i used it for a few plugins
Eh ima assume it's GPL
if you are using 1.18.2+ you no longer need to use reflection
/**
* Create a Skull with a texture using the new PlayerProfile
* Post 1.18.2
*
* @param id UUID to assign the skull.
* @param name a name for the skull
* @param texture a Base64 texture String
* @return Skull ItemStack
*/
public ItemStack getHeadByProfile(UUID id, String name, String base64Texture) {
ItemStack head = new ItemStack(Material.PLAYER_HEAD);
PlayerProfile profile = Bukkit.getServer().createPlayerProfile(id, name);
try {
profile.getTextures().setSkin(new URL(getURLFromBase64(base64Texture)));
SkullMeta meta = (SkullMeta) head.getItemMeta();
meta.setOwnerProfile(profile);
head.setItemMeta(meta);
} catch (MalformedURLException e) {
e.printStackTrace();
}
return head;
}
private String getURLFromBase64(String base64) {
return new String(Base64.getDecoder().decode(base64.getBytes())).replace("{\"textures\":{\"SKIN\":{\"url\":\"", "").replace("\"}}}", "");
}```
Spigot API W
Yep I love mojang maps
it made me use latest versions
good for anticheats
Majang maps made me have a play
and a lot of thing
even made a plugin if u send a packet u get kicked lol
@Override
public Map.Entry<Boolean, Boolean> handlePurchase(Player player, AtomicReference<ItemStack> newItem, AtomicReference<Item> materialItem, PlayerItemInfo itemInfo, ItemSpawnerType type) {
final var game = Main.getInstance().getGameOfPlayer(player);
var gameStorage = SBA
.getInstance()
.getGameStorage(game)
.orElseThrow();
final var typeName = newItem.get().getType().name();
final var team = game.getTeamOfPlayer(player);
final var afterUnderscore = typeName.substring(typeName.contains("_") ? typeName.indexOf("_") + 1 : 0);
/**
* Apply enchants to item here according to TeamUpgrades.
*/
switch (afterUnderscore.toLowerCase()) {
case "stick":
final var sharpness = gameStorage.getSharpnessLevel(team).orElseThrow();
if (sharpness > 0 && sharpness < 5) {
newItem.get().addEnchantment(Enchantment.KNOCKBACK, ```**materialItem.getEnchantmentLevel(Enchantment.KNOCKBACK) + sharpness);**```
}
if (SBAConfig.getInstance().node("replace-sword-on-upgrade").getBoolean(true)) {
Arrays.stream(player.getInventory().getContents().clone())
.filter(Objects::nonNull)
.filter(itemStack -> itemStack.getType().name().endsWith("STICK"))
.filter(itemStack -> !itemStack.isSimilar(newItem.get()))
.forEach(stick -> player.getInventory().removeItem(stick));
}
break;
case "boots":
case "chestplate":
case "helmet":
case "leggings":
return Map.entry(ShopUtil.buyArmor(player, newItem.get().getType(), gameStorage, game), false);
case "axe":
final var efficiency = gameStorage.getEfficiencyLevel(team).orElseThrow();
if (efficiency > 0 && efficiency < 5) {
newItem.get().addEnchantment(Enchantment.DIG_SPEED, efficiency);
}
break;
}
return Map.entry(true, true);
}```
Any one know why "getEnchantmentLevel" gives: Cannot resolve method 'getEnchantmentLevel' in 'AtomicReference'
materialItem.get().getEnchantmentLevel
my tab completer isnt working this is what i have
public class TabCompletion implements TabCompleter{
@Override
public List<String> onTabComplete (CommandSender sender, Command cmd, String label, String[] args){
List<String> completions = new ArrayList<>();
if(args.length == 0){
completions.add("reload");
completions.add("clear");
completions.add("edititem");
completions.add("removeitem");
return completions;
}
return null;
}
}
getCommand("ahadmin").setTabCompleter(new TabCompletion());
length == 1
thats it lol
Yeah, you're operating on the first argument, args[0], which would be of length 1
It's a little counterintuitive at first but you get used to it
and do i need to use this to retrieve the output
getCommand("ahadmin").setTabCompleter(new TabCompletion());
getCommand("ahadmin").setExecutor(new AhAdmin());
now it gives me this:
Cannot resolve method 'getEnchantmentLevel' in 'Item'
You still have to register both, no?
kk thx
are you trying to get the enchants of a dropped item?
enchant level*
trying to get the enchants of an item in someones inventory
it the inventory of the shop
you would use implements CommandExecutor, TabCompleter
it will be in someones storage the entire time
No, I know that. There's a class called TabExecutor which combines the two
implements TabExecutor
Item refers to a dropped item
What I'm saying is that this is incorrect
/**
* Sets the {@link CommandExecutor} to run when parsing this command
*
* @param executor New executor to run
*/
public void setExecutor(@Nullable CommandExecutor executor) {
this.executor = executor == null ? owningPlugin : executor;
}```
Thats all I do in GM and it works fine. no need to set teh TabExecutor
if it'll be in someone's inventory, you are looking for an ItemStack
Then you have some special handling or something because Bukkit doesn't do that
if (item.getType().name().endsWith("STICK")) {
item.addUnsafeEnchantment(Enchantment.KNOCKBACK,item.getEnchantmentLevel(Enchantment.KNOCKBACK) + finalTeamSharpnessLevel);
}``` so this would try to get the knockback level of a dropped item?
nope nothing
Oop, nope, you're right
if (completer != null) {
completions = completer.onTabComplete(sender, this, alias, args);
}
if (completions == null && executor instanceof TabCompleter) {
completions = ((TabCompleter) executor).onTabComplete(sender, this, alias, args);
}```
TIL
that looks like it's adding an enchant onto an item
yeah
thats the point of both of these
its the exact same thing that needs to be done, just two diff conditions
when it replace materialItem for ItemStack I now get this:
Non-static method 'getEnchantmentLevel(org.bukkit.enchantments.@org.jetbrains.annotations.NotNull Enchantment)' cannot be referenced from a static context
because you need an instance of an ItemStack
i got
💀
did you register teh executor? Did you remember to return true?
yes
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args[1] == "reload") {
Ah.getInstance().reloadConfig();
sender.sendMessage("[AH] Config reloaded");
}
return true;
getCommand("ahadmin").setExecutor(new AhAdmin());
acf cough cough
you shoudl not get a useage message if you return true
ik that
- Probably want
args[0] - You should check the size of the args array first before accessing it
- .equals(), not == on a string
also @desert frigate adding on to this ok, this is an example of a use of reflections (simple channel system for sending messages and receiving them)
Reflections reflections = new Reflections(SciChannels.getClazz().getPackage().getName(), new TypeAnnotationsScanner());
for (Class<?> clazz : reflections.getTypesAnnotatedWith(ChannelInfo.class)) {
if (clazz.getAnnotation(ChannelInfo.class).name().equals(jsonObject.getString("channel"))) {
Channel instance = (Channel) clazz.newInstance();
instance.onMessageReceived(jsonObject);
}
}
i'd recommend learning it
it's very useful it you are making any sort of apis
and its just 100x easier in the long run it can help with big projects so you don't have to register commands or listeners
@boreal python after looking at your code for a bit, looks like you should be doing newItem.get().getEnchantmentLevel(blah blah blah)
it does it for you
If its an Atomic reference of an Item you probably shoudl be doing .get().getItemStack().getEnchantmentLevel...
bingo. that worked
thank you so much
👍
bro what 😭😭
I don't even know the basics of java
?learnjava
Here are some links to get you started on learning Java:
- https://www.codecademy.com/learn/learn-java
- https://www.sololearn.com/learning/1068
- https://www.learnjavaonline.org/
- https://programmingbydoing.com/
- https://docs.oracle.com/javase/tutorial/java/index.html
The last one is the only official one, however some of those concepts assume that you already know a bit about programming.
helpful links for those who don't know anything
am I allowed to profit from a plugin that copies Hypixel skyblock in many aspects but it's not called Hypixel skyblock?
and it has many different things on top of the plagiarised content
Id think so if it’s not hypixel’s source code? But I’m also not a legal expert or familiar with how Hypixel licenses their work
Ping one of the Hypixel admins in here 😄
@ornate mantle I’ve always wondered about copywrite and how that all works. I doubt you would get in trouble for it if you didn’t take any code.
Jk don’t do that.
Just cause it’s a plug-in to a funny block game
Also hypixle stole bedwars or smthng
I don’t remember
Something to do with hypixle and bedwars
And nothing came from it
So
It’s conceptually similar to egg wars but a lot of the content is original
they stole bedwars from a Roblox game
Lmao
and Roblox stole some content from Hypixel back
and I think Simon said it's fine
fuck it I'm not gonna finish this plugin anyways 💀
Lmao
there are many plugins that already copy hypixel and profit from it
they even said "inspired by hypixel"
is it possible to extend void setWalkSpeed(float value) bigger then 1? like make them go faster.
I read somewhere that Hypixel can send you a cease and desist letter with fines
they cant do anything if u dont steal their code lmfao
i dont think im doing this right
fyi those lines are red because for some reason it's not setting/saving the player config
it reads it just fine tho
hey guys. i coded a cutscene plugin that tps players 20 times a second. this is a tiny bit jittery. do u guys have any recommendations for a smoother alternative?
i tried velocity but when the player moves it somehow still affects velocity and the camera path changes
i didnt even think that was possible
which part xd
basically yes
xDD
pretty clever using teleportation to make a cutscene
yeah but its jittery
i can imagine
im not sure if there is a whole other way to control a player plugin sided
yeah
id hope so, that sounds dope
armor stands kind of smooth it out
but not really
it kinda just smooths the jitters a tiny bit, but you can still see them
if I were you i'd make a thread here. id hate to see this get swept under
hey guys i coded a cutscene plugin that
👍
thanks
np
bruh with armor stands you can't see blindness effects either
so it ruins it
eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
f
i have one last idea
but if this doesnt work im giving up until someone else with big brain has idea
xDD
.set() not setting or saving... why?
at this point id say that would be the best option.
What is the best way to track the damages in an entity?
So basically check if x% of damages are from the following sources
this is killing my brain
You can either use ram and then hard drive or just pdc since all entities are persistent data holders
What about meta data
I just found that
How does that work does it actually attach to the nbt
only until server shutdown iirc, so use pdc instead
Also can you get how much an entity has regened or total damage ever taken
What is pdc
persistent data container
yes
You can do Entity#getPersistentDataContainer
The same as meta
How does it work
Is the name space for the plugin or for the value
Because it seems to take an object that contains 2 objects
After it
The class acts like a map. The key is the key to access it and the value is the value associated with the key.
However data is always stored in binary, thats why you always need to specify a PersistentDataType
PersistentDataType basically converts from type to byte[] and vice versa
Hello, I’m testing out creating custom enchantments however it does not seem like it is registering
public static final Enchantment TNTSHOOTER =
new ModEnchants("tntshooter", "TNT Shooter", 1);
// check if list contains enchantment otherwise register it
public static void register() {
boolean registered = Arrays.stream(Enchantment.values()).collect(Collectors.toList()).contains(TNTSHOOTER);
if (!registered){
registerEnchantment(TNTSHOOTER);
}
}
// register method
public static void registerEnchantment(Enchantment enchantment){
boolean registered = true;
try {
Field f = Enchantment.class.getDeclaredField("acceptingNew");
f.setAccessible(true);
f.set(null, true);
Enchantment.registerEnchantment(enchantment);
}
catch (Exception e){
registered = false;
e.printStackTrace();
}
if (registered) {
System.out.println("Registered " + enchantment + " Enchantment");
}
}```
It’s printing out Registered Enchantment[minecraft:tntshooter, null] Enchantment
Solved!
have you installed java?
yes
9
8*
ig its not getting the java file how do I change the path
its not getting the java 8 file
yes
if so you need to find its location
I found it
for me it will look like this
/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -jar BuildTools.jar --rev 1.13 --remapped
so replace java with location
alr thx
np
disk too right?
put it in quotes
''?
"java location"
Any idea why I sometimes get this log: net.minecraft.server.CancelledPacketHandleException: null. Seems to happen when receiving plugin messages.
bro he fixed it
hi, is there a better way to write this code? Right now, you have to specify either one of the WorldTypes exactly as they are and if you don't, no code will run cos it doesn't match either of the two inputs. It just doesn't seem like using a string for a parameter that only takes 2 values doesnt seem quite right. Also just to confirm, this isn't gonna have anything to do with the Bukkit WorldType class.
public static void addMinigameWorld(String minigameName, String worldName, String worldType) {
if (worldType.equals("type1")) {
//run some code here
} else if (worldType.equals("type2")) {
//run some code here
}
}
if theres only 2 options use a boolean
hmm. maybe but what if I had more than 2 values?
use an enum
You could make an enum if you want to expand it and have the enum contain a lambda expression:
public enum WorldTypes {
TYPE_1((minigameName, worldName) -> { // code }),
TYPE_2((minigameName, worldName) -> { // code }),
...
private final BiConsumer<String, String> action;
WorldTypes(BiConsumer<String, String> action) {
this.action = action;
}
public BiConsumer<String, String> getAction() {
return action;
}
}
ok yea I was thinking of taking a look at enums. thanks for the example!
Though I would recommend not using BiConsumer<String, String> but rather creating an interface with maybe a function called onCall(String minigameName, String worldName) or smth
Hey I'm trying to build a listener that checks all commands that are executed. For example "//brush" from WorldEdit. I don't want to overwrite the command, but I want to execute certain actions when the command is entered. Is that possible somehow?
You can listen to https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/player/PlayerCommandPreprocessEvent.html
declaration: package: org.bukkit.event.player, class: PlayerCommandPreprocessEvent
or PlayerCommandSendEvent
Awesome, thanks @chrome beacon and @old cloud
I'm testing out vectors by making a bow that draws in entities to the arrow
Code:
private final SurprisePlugin plugin;
static final double rangeX = 5;
static final double rangeY = 5;
static final double rangeZ = 5;
public VoidBow(SurprisePlugin plugin) {
this.plugin = plugin;
}
@EventHandler
public void onArrowLaunch(ProjectileLaunchEvent event) {
if (event.getEntity().getShooter() instanceof Player) {
Player player = (Player) event.getEntity().getShooter();
if (event.getEntityType() == EntityType.ARROW) {
ArrowVortex((Arrow) event.getEntity());
}
}
}
public void ArrowVortex(final Arrow arrow) {
new BukkitRunnable() {
private int counter = 10;
@Override
public void run() {
if (counter < 3 || arrow.isOnGround()){
arrow.remove();
cancel();
return;
}
Location arrowLocation = arrow.getLocation();
List<Entity> nearbyMobs = arrow.getNearbyEntities(rangeX,rangeY,rangeZ);
for (Entity e : nearbyMobs){
if (e.getType() != EntityType.PLAYER || e.getType() != EntityType.ARROW){
Entity entities = (Entity) e;
entities.setVelocity(entities.getLocation().subtract(arrowLocation).toVector().normalize().multiply(3));
}
}
counter --;
}
}.runTaskTimer(new SurprisePlugin(), 0, 1);
}
}```
However it is giving me errors such as `java.lang.IllegalStateException: Initial initialization`
I'm not sure what's happening and am hoping if someone knew how to fix this issue...
Can you send the whole stacktrace ?
Btw your runnable will work 0.5s
Even less
new SurprisePlugin()
you cannot create a new instance of your plugins main class
use the one you pass through the constructor
Oh I see I was confused with what It wanted
Thanks! It somewhat works now, just need to figure out the vector part
?
hi i cant find out wait i can't stop player from taking it
if (e.getView().getTitle().equalsIgnoreCase(ChatColor.WHITE + "Ban This Noob")) {
Economy economy = Out.getEconomy();
switch (e.getCurrentItem().getType()) {
case EMERALD_BLOCK:
Inventory clickedInventory = e.getClickedInventory(); // Get the clicked inventory
ItemStack skull = clickedInventory.getItem(4); // Get the skull you made when you created the inventory
SkullMeta skullMeta = (SkullMeta) skull.getItemMeta(); // Get the skull meta
OfflinePlayer personToBan = skullMeta.getOwningPlayer();
economy.withdrawPlayer(personToBan, 1000);
if (personToBan.isOnline()) {
personToBan.getPlayer().sendMessage(ChatColor.GREEN + "Tatt 1000 fra deg for sandtak"); // If person is online, send them a message also
}
sandtak2.openfyll1(player);
break;
}
e.setCancelled(true);
i did stop the player from taking it befor but rgt now i can take it from the inv and i can't do any thing with it
Put the Event#setCancelled just after the first bracket (if inventory title...)
Why can't it find the 1.13 spigot repository? https://paste.md-5.net/uzevogujob.xml
and yes I ran this beforehand /usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -jar BuildTools.jar --rev 1.13 --remapped
the exact notice is Could not find artifact org.spigotmc:spigot:jar:remapped-mojang:1.13-R0.1-SNAPSHOT in spigot-repo (https://hub.spigotmc.org/nexus/content/repositories/snapshots/)
i do alsow have this in there but that works
case BARRIER:
sandtak2.openMenu(player);
break;
?paste Can you paste your code, it's hard to read on here
need more?
Don't use inventory names to detect inventories
Use the inventory instance or the inventory holder
like size?
?
Remapped is for 1.17 and above
how do i get inventory instance ?
thats discriminatory
That's the thing you use to open the inventory
ok
but that won't help
What does this do? sandtak2.openfyll1(player)
open a new inv
There's your problem
It is
but
yeah and then how can i fix it?
The following should never be invoked by an EventHandler for InventoryClickEvent using the HumanEntity or InventoryView associated with this event:
HumanEntity.closeInventory() HumanEntity.openInventory(Inventory) HumanEntity.openWorkbench(Location, boolean) HumanEntity.openEnchanting(Location, boolean) InventoryView.close()
but it workes on barriers
You're not opening the inventory when clicking the barrier
It's not written "It won't work"
At least not with the code you sent
yes i do just another
so um, I had this bug with minecraft where any versions 1.18 and above would freeze every 1 second, meaning the graph would be some thing like this:
300 -> 1 - 250 -> 1..etc
so well i used some jvm args i got recommended which ill send later,
and that fixed it, however after 3 days the bug is back, but i realized something, when the bug was fixed i had 2gb allocated and it was using 2.7gb, but when the bug still existed it was using 2gb flat, so i thought maybe that was the problem, i just tried allocating 3gb or 4gb and no luck.
the jvm args are here: https://pastebin.com/3mK9yZFf
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
it did work on 1.18
Which one works and which one doesn't ?
i sad need more code?
gold block does work but don't take money
So
Explain clearly your problem, and illustrate with error or something else relevant please
public void onClick(PlayerInteractEvent e){
if (e.getItem().isSimilar(totem)) {
Player player = e.getPlayer();
player.getInventory().removeItem(totem);
player.playSound(player.getLocation(), Sound.ENTITY_ITEM_BREAK, 1.0F, 1.0F);
player.sendMessage(ChatColor.AQUA + "[SHENLONG] " + ChatColor.RED + "Has invocado a los dioses");
player.sendMessage(ChatColor.AQUA + "[SHENLONG] " +ChatColor.RED + "y tienes la oportunidad de revivir");
player.sendMessage(ChatColor.AQUA + "[SHENLONG] " +ChatColor.RED + "a alguien... ¡pero cuidado! Si desconocemos");
player.sendMessage(ChatColor.AQUA + "[SHENLONG] " +ChatColor.RED + "el nombre perderas todo derecho a comunicarte");
player.sendMessage("");
player.sendMessage(ChatColor.AQUA + "[SHENLONG] " + ChatColor.RED + "Escribe su nombre: ");
aSync.add(player.getName());
}
}```
When the first item is used, all works but the second time the server crashes, why?
Do you have errors ?
Dude just make a prefix variable
and do early returns
dont have a collection with player names but rather with their uuid
Dry principle, you wanna be as „Lazy“ as possible
Life principle*
let me check
btw is there a good reason to use CharColor.<Color> instead of just color codes?
if you use color codes you still gotta translate those so same thing
if you got a long string then i use color codes and pass that string to ChatColor.translateBlaBlaBla
yes, https://paste.md-5.net/kazevajewa.cs the error starts at the first page, I haven't read it I'll do it now
Honestly never done that, always been using §0-9, etc
But i think like this will still crash
It did before i believe
Errors are not there to decorate and scare you, they're here to help you fix a problem. And Java errors are pretty helpful since they often explain exactly what is the problem, and where it's located
try it
reverse your logic and check if token.isSimilar(e.getItem())