#help-development
1 messages Β· Page 1877 of 1
There is no solution?
not a good one
there is no solution unless all of your objects never require arguments
not sure actually, play around with getSlot method. and debug it until you find out what gives the slot, maybe the event will throw 2 times when doing that who knows
it also doesn't make sense to get rid of new, it exists for a reason
I have seen that spigot has a built-in system called ServiceProvider
So i will have to register with Service.register(new TestService()) right?+
what are you trying to do
yes, I sent example code including this about 3 times
Trying to skip having my main plugin class full of new instance classes and getters
RIP good code lol
thats just a bad idea
this will only make your code horrible and disgusting
debugging nightmare
Annotations, build it like Spring boot π€
inventory move item event ?
annoying thing is it also triggers InventoryClickEvent
that's called for hoppers etc
new Object(); is something you can never really get rid of
I have prob like 10 in one class for a small project
just ignore that if you can get what you need from the latter event. Or use them both to do what you need who knows
unless you use kotlin and just do
val myObject: MyObject = MyObject(myParameters...)
lol
fair lol
(which of course is the same thing actually)
behind the scenes
Why do you not want a ton of news VERANO?
Its possible to the method register a void?
Because it get more than 20x2 lines of code that can be reduced
as I already told you, there are no void objects
because void means nothing
it's less than null
@sterile token I tend to have a Hook class that instanciates everything for me
of lines means nothing
to not clutter the main class
but also for hotswaps?
no
InventoryClickEvent is what you want to use Jelles
focus on readability and debugability rather than less lines
@quaint bough I'll do some testing in 5 minutes
alright
He's not talking about normal hotswapping where you shiftlick an item an it goes into a chest, but rather hovering over an item and pressing a number of the respective inventory slot it goes into
I know
e.hotbarKey will work
what event is that
but then I have to make sure it wont actually move before it opens the inventory
InventoryClickEvent has a property hotbarKey
without a getting just a prop
thats exactly what you need
int getHotbarButton() If the ClickType is NUMBER_KEY, this method will return the index of the pressed key (0-8).
oh
check if the ClickType is NUMBER_KEY. then get the HotbarButton
took only 20 min lool
and that will return the slot position
Verano how are you trying to instanciate the classes
bro you really have no idea what you are doing
ok it works thanks
now you always add null when your object does not exist
you already got it working?
lmao
I have copy your code :/
you haven't. You have changed it to be totally stupid
I sent you perfectly fine working code 3 times
make an interface and implement it for every class you got except the main class. make a default void get() to instanciate the class if its not already instanciated, otherwise return it
but
I wouldnt recommend
at all
e.g. my get Method took a Class<T>, and not a T instance
it makes no sense, when you already have an instance, why would you need to get it again?
You don't even understand the difference between T and Class<T>
So like that?
4th time that I've sent this now
Any good idea's to quickly and effectively debug plugins? like hotswapping jars etc?
with or without maven?
with
then no idea, pls let me know if you find a solution lol
there is an attribute in maven tho you can use to specify the output directory of the jar
Like this so
dont remember it
yes
yeah sure, but I thought they wanted to attach a debugger
not really, I use log4j mostly. Talking more about environment setup to quickly test ur plugins
hope you updated that log4j
yeah nw
just run maven-exec to copy your jar to your server folder
Would be cool to have a test server fire up after building it, that dosnt utilize all aspects of the server like using the world generation etc. would be just for testing purposes for some plugins
that would not implement features using the world etc
prob require a custom fork
you can just let maven run your server start script
yeah probably
MockBukkit
I got a good setup right now for that
lemme knooow
but Im trying to figure out a better way
maven outputs the jar in the plugins dir, then rcon restart or use linux screen/pm2 to restart the server
^ pretty sure rcon works, never tried it
@sterile token
Main class
public class Test extends JavaPlugin implements Listener {
private static Set<Object> myServices = new HashSet<>();
public static <T> T register(T object) {
myServices.add(object);
return object;
}
public static <T> T get(Class<T> clazz) {
Optional<Object> result = myServices
.stream()
.filter(object -> object.getClass().equals(clazz) || clazz.isAssignableFrom(object.getClass()))
.findAny();
return result.isPresent() ? clazz.cast(result.get()) : null;
}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(register(new MyListener(), this);
getCommand("command").setExecutor(register(new MyCommandExecutor());
}
}```
MyListener
```java
public class MyListener implements Listener {
@EventHandler
public void onEvent(Event event) {
MyCommandExecutor executor = Test.get(MyCommandExecutor.class);
executor.onCommand(...);
}
}
although I still wonder what's the benefit of doing this unless you are high on some weird drugs
let's take this one step further lol
Really trying to figure out where I would start when trying to implement net.md_5.bungee.api.ChatColor to Team.setColor.
wait
does player.displayname overwrite team.color
??
but displayname dosnt show up in tab
fuck
public class MyListener implements Listener {
static {
Test.register(new MyListener());
}
}
@Override
public void onEnable() {
getServer().getPluginManager().registerEvents(get(MyListener.class), this);
}
how can the e.getHotbarButton be -1?
Another alternative is:
public interface Service {
default Class get(){
if Main.getServiceFactory().contains(Class) return this;
else {
//add return instanciated class and add it to serviceFactory HashMap<ServiceType, Class
}
}
}
pretty sure that would work no?
you can't
the CLientboundSetPlayerTeamPacket that the server itself uses takes an enum
shit
so the client will only get 0, 1, 2, etc
basically the enums ordinal()
so: no way, the client wouldnt understand it
what do you actually want to achieve?
the color of the playername itself?
yes
I mean tablist supports the prefix as a hex color because Team.prefix is a string
and it displays it correctly
what about this? https://hub.spigotmc.org/javadocs/bukkit/org/bukkit/entity/Player.html#setPlayerListName(java.lang.String)
declaration: package: org.bukkit.entity, interface: Player
I have no idea
I mean if the docs are correct
Sets the name that is shown on the in-game player list.
but now, Team might overwrite the color who knows
you never know
actually
it shouldnt
lemme try
lol
what have you been doing for the past hour? π
I thought you already tried setPlayerListName π
lmao got caught up here
now need to figure out a way to set the tag above the players head
but that I think, is only with Teams and GameProfile
and default ChatColor.
what tag? didnt even know this exists
all this scoreboard and teams thing is way too complicated for me lol
The prefix has Color.of
as Team.setPrefix takes string
but the name remains the color of the Team.color
which I do not want
yes
I did but it doesn't show anything
do a for loop for all onlineplayers
and get their scoreboard
and add the team
public void setPlayer(String playerName, String prefix, String suffix) {
for (Player p : Bukkit.getOnlinePlayers()) {
Scoreboard board = p.getScoreboard();
Team team = getTeam(board, playerName);
team.addEntry(playerName);
team.setPrefix(prefix);
team.setSuffix(suffix);
}
}
oh wait
I actually wanted to send the code lol
private Team team;
{
Scoreboard board = Bukkit.getScoreboardManager().getNewScoreboard();
team = board.registerNewTeam(ChatColor.translateAlternateColorCodes('&',"&x&0&0&f&f&0&0TeamName"));
team.setPrefix(ChatColor.translateAlternateColorCodes('&',"&x&2&4&6&8&a&cPREFIX"));
team.setOption(Team.Option.NAME_TAG_VISIBILITY, Team.OptionStatus.ALWAYS);
team.setDisplayName("asdasdasd");
}
@EventHandler
public void onEvent(PlayerJoinEvent event) {
event.getPlayer().setPlayerListName(ChatColor.translateAlternateColorCodes('&',"&x&f&f&0&0&3&3JesusChrist"));
event.getPlayer().setPlayerListFooter("test");
team.addEntry(event.getPlayer().getName());
}
somehow it doesn't do anything
lemme see ur onEnable
it does run. after all it changes the playerlist name
yes, in the second line of the init block
lol
huh
public static Scoreboard scoreboard;
public static Team team;
@Override
public void onEnable() {
scoreboard = Objects.requireNonNull(getServer().getScoreboardManager()).getMainScoreboard();
scoreboard.getTeams().forEach(Team::unregister);
team = scoreboard.registerNewTeam("test");
this.getServer().getPluginManager().registerEvents(new TeamstestListener(), this);
}
@EventHandler
public void onPlayerJoin(PlayerJoinEvent event) {
event.getPlayer().setPlayerListName(ChatColor.of("#876664")+event.getPlayer().getName());
Teamstest.team.setPrefix(ChatColor.of("#876664") + "[prefix] ");
Teamstest.team.addEntry(event.getPlayer().getName());
}
do not do getNewScoreboard
get the main one
or loop throgh all online players and get their boards
like
this
Yeah from personal experience if you create a new board every loop you'll make compatibility a pain
^
make one new scoreboard and store it to handle the part of your plugin handling the teams
or just do what I sent
still trying to figure out if there is a way to edit the playername color in the name tag above the players head without using GameProfile or Team
Guys, is there a way, to have two players logged in without having two consoles? I ask this for testing plugins
two consoles?
How do I run a command as a player?
Or like
They send a command, and I run a super long command on behalf of them?
do you want to join two servers with one account?
Bukkit.dispatchCommand
@EventHandler
public void onEvent(PlayerJoinEvent event) {
Bukkit.dispatchCommand(event.getPlayer(), "kill");
}
SolarRabbit, the same account but 2 players of that account in the server?
Or in this case of an offline server, I want to know if there is a possibility of creating/mocking a cracked account
Edit the name of the players GameProfile on join, then have the server set to offline
im pretty sure
does anyone have a good resource for fireworks
as the player1 will kick player2 out when joining with the same name
also assign idβs
so u can keep track of the players
explain.
But can we freely switch between both players to control, without having any of both to log out?
im not sure I understand what you are trying to achieve
@charred echo Hex colors work in the name above the player
with one limitation
lol
chat tab?
completion
no, that's no problem
the problem is...
with a limit of 16 chars, you can merely pass one color into it lol
shit
GameProfile yes?
wouldve been cool for the Team.prefix formats to apply to the playername if Team.color was not set. But thatβs not the case..
oo ty
does it not return the command output?
oh well, thanks!
commands do not have any output
all they return is a boolean
oh oops
fr ty
it's an actual command i am doing to test the command sender thing
but if i run, kill
it'll send killed player?
like
oh
you would have to listen for the evebt
event
how to make them/change colours/effects
i mean
it works
all i care about thank you!
progrimatically?
If you do Bukkit.dispatchCommand(player,"kill") it will do the same thing as if a player entered /kill
ohh
e.g. if they don'T have permisison, they get the "no permission" message, etc
ah i see
it's like sudo -u player in linux
alex, you running linux btw?
only on my servers, not on the desktop
haha I'm uncreative today
I'm so happy that I finally have proxmox on the dedicated server
noice, you got ur own mail service
it's just mailcow on a 4GB/2cores server
oh no wait I moved it
it's on the 64GB/12 cores server lol
Is it possible to make blocks unbreakable when certain creepers explode?
remove then from the block list of the EntityExplodeEvent
Thanks
Send the error, spawnEntity can't return null
Where do i download the things i bought
Null returns in .setfuseticks
gimme a sec
GUYS!!!
I JUST FOUND OUT SOMETHING BEUTIFUL!!
I JUST FOUND OUT HOW TO WRITE JAVADOCS
Set max ticks first
That's not a NPE, ^^
Coll are you proud of me?
Uhh
I know It's not NPE
Yes
But I said Null
Nothing is null
What are you printing
Itβs just a generic message when a command fails
Always look for the caused by line
I dont wanna just hop in mid-issue
I never look at that spot in STs though so that's probably why 
But whats line 18? @rough basin
Also why the fuck is your class lowercased first letter
speedCreeper
You just learned how JavaDocs worked, pipe down
Well its a big deal, since ive been working on java a while now and didnt realize that was a thing
Well
IU knew it was a thing
Didnt know how to do it
Never looked it up ig
Wait until you learn IntelliJ can generate the entire JavaDoc site for you 
I mean, i assumed that was a thing. How?
Like where is the button
Tools -> Generate JavaDocs
Well idk what git is, but GitHub integration is what i want
Like push, commit, pull, merge etc?
Yea
Yeah, that's Git.
Im just kidding

From here on i was messin with you
Lol
sorry
smh...
@rough basin
You never gave line 18 lol
.
I already sent the solution
Oh my b
Thats what i was abt to say π’
wat
LOL
it even has a special github plugin, not just generic git lol
Pretty bad, the project is quite literally named terrible-plugin and you made it less terrible.
Oh wait nvm you added Lombok
Great PR π
This definitely needs to be merged
8.6/10
I take it back 3.7/10
@tender shard whats the point of replacing this
getCommand("clearlag").setExecutor(Commandclearlag.static_instance);
With this
getCommand(new StringUtils().reverse("galraelc",null)).setExecutor( Commandclearlag.static_instance);
and whats @hoary knollThrows
Sorry for ping
@SneakyThrows
And why so many lines???
Did ya read the name
"Hide Admin commands from players looking through the source"
Does that mean in-game??
Cause if not then why would you care if people can see admin commands when looking through the plugin code?
I don't trust to know if you're kidding or not anymore
Im not
Look at the repo name
terrible-plugin
I didnt look at anything except this specific commit
that might be why im confused
AHHHHHHHHHHHHHHHHHHHHH
I understand now
Sorry lol
I just read CONTRIBUTING.md
sorry for giving you trust issues

Omg didnt know this existet XDD
if (event.getMessage().toLowerCase().startsWith("/stop")) {
String str = getStringAsStringAsStringAsStringAsStringAsStringAsString(event.getMessage());
// well either way your server is going to stop. after all, the user wanted to stop the server.
// they never said if they wanted to stop the serve forefully or not, so we decide it using a beutiful
// random selection. it is very random and necessary for our needs.
Thread.currentThread().stop();
}
Love it
wait...
you can do this?
if (!(sender instanceof Player plr))
to make plr a variable???
With some newer Java version yeah
Oh java 14
Java 14 it seems like
Or you just dont write plugins for server below 1.16...
Which i recommend
Thats pretty hot, thank you
Ik, but im making a super simple plugin that should work on anything 1.9+
No
I would go the extra mile and just get a random PDC of a spawn chunk just to deny
old spigot servers my plugin even if it would be compatible otherwise
I still play on 1.6 π
So
Im confused
int xp = Integer.parseInt(args[1]);
//Check if player is trying to bottle less than 1 XP
if (xp == 0) {
plr.sendMessage(ChatColor.DARK_RED + "You must bottle more than 1 XP!");
return true;
}
Its working correctly
All my other checks work fine
But for some reason
This check passes every time
Ive tried removing the variable and using straight Interger.parseInt
Still passes
Im confused
Maybe maven isnt packaging it correctly or smthng??
Im adding a sendmessag thing and its not working
Yea wtf
Maven isnt sending out the right jar
its 99% not maven
its an old project from when i first started
Theres a good chance i did something and fucked it up
But it was maven lol
Probably something i did tho
f
Everytime I doubted the build tools or any widely used library, I am always the one wrong
PlayerInteractEvent
Thanks
guys im trying to code a nick plugin 1.8.8
is there any way to change the chat tab completion ?
in commands yea
chat
no
like essentials did
how did they
i cannot figure out where is it done
im not aware of a way to change chat completion outside commands
override the onTabcomplete
CHAT
cannot set
?
guess thats deprecated
Whats the best way to make a GUI refresh every x seconds.
I know I can do this with a runnable or something like that, but the issue I run into is that multiple players can open the GUI at the same time so I wanted to know if its possible to make it so that when a new player enters the GUI the timer will restart as the GUI already updates. Im not sure the best way to do this
end and reschedule the task
alright, I feel real dumb for not thinking of that
i think thats the best way
thanks π
private int id = -1;
/**
* Utility method.
* Wrapper for cancelling and rescheduling
* the task.
*/
public int scheduleRefreshTask() {
if (id != -1)
Bukkit.getScheduler().cancelTask(id);
id = Bukkit.getScheduler().scheduleSyncRepeatingTask(plugin, () -> {
// code
}, 0, /* interval */ 1);
return id;
}
/**
* Called when player opens inventory.
*/
public void open() {
// ...
scheduleRefreshTask();
// ...
}
some code
Is it possible to update the title of a GUI without recreating the GUI?
oh cool this helps out quite a bit
maybe through an inventoryview
np
just change the interval to your delay
and put your code where the // code is
also the open() method is something i created you dont need it
it was just to demonstrate how it would be used
alright sick π
just call scheduleRefreshTask() when a player opens the gui
maybe through an InventoryView?
i dont know
alright cool thanks
Quite complicated. Its possible but involves nms, packets and reflections.
oh boy
ahh yeah, I could prob do a hacky way that gets the viewers and reopens the GUI for all of them with the new name
i recommend https://nekoyue.github.io/ForgeJavaDocs-NG/javadoc/1.18.1/ for minecraft javadocs
package index
probably the best ive found so far
im trying to avoid NMS , and all that
thanks for this tho
for getting viewers use Inventory.getViewers()
yeah alright cool thank you ima work on getting the refresh working
ok gl
thank you π
This was for 1.16:
public static void renameCurrentInv(final Player player, final String title, final Containers<?> containerType) {
final EntityPlayer entityPlayer = ((CraftPlayer) player).getHandle();
// FIXME active container
final Container current = entityPlayer.bV;
// FIXME current.windowId
final PacketPlayOutOpenWindow packet = new PacketPlayOutOpenWindow(current.j, containerType, new ChatMessage(title));
entityPlayer.b.sendPacket(packet);
}
oh nice
No reflections but it was still really tedious to find out
Hm i should translate this to moj mapped...
is it better to do a sync repeating task or an async repeating task?
Depends on what you're doing in the task
For 1.18 moj mapped
public static void renameCurrentInv(final Player player, final String title, final MenuType<?> containerType) {
final ServerPlayer entityPlayer = ((CraftPlayer) player).getHandle();
// FIXME active container
final AbstractContainerMenu current = entityPlayer.containerMenu;
// FIXME current.windowId
final ClientboundOpenScreenPacket packet = new ClientboundOpenScreenPacket(current.containerId, containerType, new TextComponent(title));
entityPlayer.connection.send(packet);
}
Bit i dont know why i added the FIXMEs back then...
for a task that repeats for as long as a player is inside of a GUI, it refreshes with every person that enters the GUI
Sounds like you shouldn't use a task for that
I mean if its a clock that is being updated for example...
Then there is not much of a choice
true
Its updating a GUI. thats it, it deletes the data inside of a GUI and readds it
Do you want the player to interact with the inventory?
Is the inventory purely virtual or does it contain actual ItemStacks?
You can make GUIs completely async and packet based but in most
cases you should be fine with just running a normal task as long as
the user has the inventory open.
alright cool im stay with the normal task then, and yeah it has item stacks. The player can interact with the items (interacting with a item brings up another GUI that doesn't update) But sync should be good
?paste
yo i made it version safe https://paste.md-5.net/futupinuxo.java
like a million extra lines just for reflection of one method
Hey I got a question I tried a couple ways to get a 50/50 chance but I'm not sure if this is the best way to do it.
The current way that I'm getting a 50/50 chance is:
Random random = new Random();
if (random.nextBoolean()) {
// Won (50% of the time)
} else {
// Won (50% of the time)
}
It seems to be a decent 50/50 chance but idk if there's a better way to
i see nothing wrong with this
just make sure you dont create a new random object every time
alright cool I thought so, but didn't know if there was a better practice of doing it
well, i guess you could use
ThreadLocalRandom.current().nextBoolean()
that might offer better performance, but i think that difference will be really small
I want to make an endpoint from a webhook, how can I achieve that?
you can also use something like
if (Math.random() < /* chance */ 0.5) { // 0.5 == 50%
// code if yes
} else {
// code if no
}
if you want a more flexible chance
What type of endpoint? What are you trying to do?
So basically I want to integrate it with payment gateway, so whenever someone donate it will execute a commands on the server.
Hm ok. There are several ways you could handle that. Either via a REST endpoint (http) or via a websocket.
Biggest concern in both cases should be security. How do you prevent someone from just sending the command on their own?
There is an unique key
https://whatever.com/endpoint/(unique key) or something like that.
In this case you can look into javas HttpServer class or HttpServlets.
However I have a few question to tell the server that there is a donation. What should I do If the server is offline, and because of that there will be no commands executed.
Store it somewhere
Should be persistent. Some sort of database maybe.
Btw you can also just use Kafka for producing/storing/consuming those events
Probably overkill
Store it and when the server starts, check every value that has not been executed so far
I mean when there is a new donation but the server is offline.
Have an application in the middle that receives the webhook message and stores it somewhere.
Then let your mc server poll those messages.
If you care that much about availability then you can use AWS. Maybe just an AWS Lambda function.
You pay for every 100 milliseconds the code runs. For such a purpose it should be really cheap.
Would be inconvenient for public plugin right?
absolutely
The donation service has very redundant data storage.
You can listen for the webhook and let your server store every message that has been computed already.
Then when the server starts, you get all messages from the donation service to make sure you didnt miss any while the server was offline.
Like getting all transaction made from the payment gateway?
wish I had those specs
If you know where to search you can get that for 40 bucks a month
- NMVe storage
can you do something like permissions: [a.b.c, a.b.c.d] on a command?
thing is the price, thats not cheap imo, everything over 20$ a month is pretty rough as I dont have a steady income rn
Try it and see?
lol
ah yes
What for would you need specs like that tho
Do you mean multiple permissions for one command?
running all my apiβs, utils and other stuff like nginx with all websites etc
im pretty bottlenecked with what I have rn
Because thats not possible as it would be ambiguous if the user needs one of them or all of them.
For specifically [a.b.c, a.b.c.d]
If a player has
a.b.c
then he also inherits
a.b.c.d
on default
So you define a.b.c.d as your command permission and both a.b.c and a.b.c.d would qualify for as a permission for this command
you can however check multiple permissions progrimatically, however you want
How Can I get plugin.yml version in code?
If you just want to have information from there:
PluginDescriptionFile descriptionFile = this.getDescription();
inside you JavaPlugin class
This is my new favorite link
Whenever someone asks a question that takes a few minutes to test on their end drop it
Ehh, I feel like this should almost always be the response.
It is helpful to be helpful, but by not being so helpful you train them to try before asking
But what if someone needs an idea on how to do something specific ... Try and see won't work since they can't try something they don't know π
Of course but when the question is "if I do x will it work?" just try it and see
Yeah sadly 89% of the questions would be try and see first ... And then come back with the error
Sometimes the answer is the question "what exactly are you trying to do" cause some people ask questions that are try it and see except they're leaving out key points as to why it's more complicated than that
They just don't know how to code sometimes
Whats the best way that I can have a GUI update for every player, but one of the items only updates for 1 person
I want to write eventlistener as a class which wiki should I refer to?
So like I have the whole GUI that updates, but I have statistics that need one players info. Every time a user enters the GUI right now the stats will be overridden with their stats. Is there a good way to make it so that the stats will stay the same no matter what person enters it? or would I have to make it so that its a per user inventory and make a inventory for every player on the server that tries to use that GUI
What about having a website that on 24/7 and everytime there is a donation, store it on mysql database and let the plugin access the database and do something about it.
yes
oh thanks
I have a question, I spawn a fake player via PacketPlayOutNamedEntitySpawn with a gameprofile that contains a name and now I want to set custom name visible to false via PacketPlayOutEntityMetadata but that doesn`t work so the content of the packet is just not applied
hi
i have an idea when i put a spider web to leave then all leave change to spiderweb
how to do this
Not as easy as you might think. Do you want to replace all leaves instantly or do you want them
to gradually change to webs? (over time)
I have a question: how can i use jackson to read yml files for my minecraft plugin. i want to make a system that when you press button a random block drops.
what
oh
wait
what do you mean by put a spider web to leave
Why do you want to use Jackson and not the configuration api from Spigot?
Which also works with .yml files
oh i didn't know that api existed. Im gonna do more research for that!
you can use this to load and save multiple yml configurations
Why is this not already a command
fuse ticks is how long it has been
so when fuse ticks is equal to maxfuseticks it explodes
just do setFuseTicks(0)
i think
i wrote a configuration wrapper
just put
public class ExamplePluginClass extends JavaPlugin {
final ConfigurationWrapper myCustomConfig = new ConfigurationWrapper(this, new File("myCustomConfig.yml"));
@Override
public void onEnable() {
// load config
myCustomConfig.trySaveDefault(false);
myCustomConfig.reload();
}
}
and put a file myCustomConfig.yml in your resources
those will be the defaults
if you dont want defaullts just remove myCustomConfig.trySaveDefault()
it also wraps all org.bukkit.configuration.Configuration methods
so you can do like
myCustomConfig.getString("hi");
?spoon
Spoonfeed a newbie for a day and they'll come back with more questions. Teach them to find their own answers and you'll both be better off: you won't get stuck answering the easy questions and they'll be much more productive than before.
i already wrote that for a library i was going to release publicly
also using the class is just a more convenient way to do it
i agree that you shouldnt spoon feed
but this is just a more convenient way to use the bukkit config api as its just a wrapper
oh lmfaoo
Hey, I'm' having an issue with a very simple plugin, it has something to do with casting to class. Here's my projects files (only 2 classes https://github.com/dev-stan/EasyTP), while executing the /tpa command I'm getting the error below, could someone please give me a hand with this issue? https://pastebin.com/N63fXAyF
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.
There is a lot wrong with this code than just the error
yeah
but im assuming you are trying to get the plugin
use dependency injection
thank you!
how so?
final Plugin plugin;
public MyClass(Plugin plugin) {
this.plugin = plugin;
}
ah, constructors
If two different people decide to tp to two different people at the same time to what happens?
if (command.getName().equalsIgnoreCase("tpaccept")) {
accepted = true;
}
if (command.getName().equalsIgnoreCase("tpdeny")) {
denied = true;
}
return false;
I assume it's not complete but you need to store the requests in a list of some kind
naming conventions, using one executor for multiple commands, using global variables which means that by running /tpaccept the whole server will be accepted
exactly
Oh right, thanks for pointing this out, it's just an early version :)
Just letting you know so the technical debt doesn't start piling up
alright
What about naming conventions? I'd like to make the code prettier if possible
follow camel case for class names
camel case = easytp -> EasyTp
and tpaCommand -> TpaCommand
?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.
that is javascript...?
Class names are CapitalCamelCase; methods and fields are lowerCamelCase. Also use boolean instead of Boolean. Use primitives where you can.
maybe
basically you cant initialize an array list using any synthetic sugar, especially not using [], also your arraylist doesnt have generics. make it ArrayList<String> instead
what do you mean
maybe
thank you!
this is for spigot plugin development, which uses java
or do you not know the difference between java and javascript
javascript, short as java
oh no
wait wat
ArrayList<String> players= (ArrayList<String>) Arrays.asList("player", "player1", "player2", "player3")
almost just use the ArrayList<>(Collection) constructor instead of casting
Hello, how can I fix this? No errors or any issues, but then I execute the command (e.g /clearchat) in server chat it just prints out that command!? ```public class ClearCommand implements CommandExecutor {
@Override
public boolean onCommand(final @NotNull CommandSender sender, final @NotNull Command cmd, final @NotNull String label, final String[] args) {
if (label.equalsIgnoreCase("clearchat")) {
final Player p = (Player) sender;
for (long i = 0; i < 100; i++) {
Bukkit.getOnlinePlayers().forEach(player -> player.sendMessage(" "));
}
Bukkit.getOnlinePlayers().forEach(player -> player.sendMessage("test."));
}
return true;
}
}My Main class: @Override
public void onEnable() {
Objects.requireNonNull(this.getCommand("clearchat")).setExecutor(this);
}In plugin.yml I did this tocommands:
clearchat:
usage: /clearchat```
you are setting the executor to "this"
while the executor is actually a class called ClearCommand
soo I just need to change this to - Objects.requireNonNull(this.getCommand("clearchat")).setExecutor(new ClearCommand);
that should do it
Ahh, I'm new at this, but still I'm stupid. Thank You!
it look great do you have a example?
Its to tell intellij to fuck off and stop giving me warnings !!!!!
You just need to perform a quick search for all connected tree blocks. Really simple shouldn't need an example.
The real gamer solution is to null check and throw out some warnings in the logger, not to throw an RTE up that kills your plugin
The gamer gamer solution is to create a checksum for your plugin.yml and check it during the runtime
The worst solution is to switch to Eclipse.
Hey! Eclipse has its merrits
like ...
...
Bottom text
I've got a small problem where I'm testing the API function of one of my plugins but a custom event isn't firing, I've done:
- registered the event in the onEnable() method,
- implemented Listener
- added the @EventHandler annotation
(in the main plugin)
- got a class extending event
- added
getHandlers()andgetHandlerList()methods - neither returning null
yet still, this won't print out to the console from the listener ...
PlayerFishEvent works, even though it's in the same class but I just can't wrap my head around why it wouldn't work.
Is there anything I've missed, I've been looking at the code for too long and am probably missing something very basic.
Thank you very much for reading :)
Did you invoke the event through PluginManager?
Got a pic of the event class also? Or well if you got everything on sth like gh would make it a lot easier following along your assertions
It's all completely synchronous, too ^
Also make sure you in fact export a new jar and clear eventual build caches
Most stuff is synchronous in some manner
Where's this line? Have you made sure it is running in the first place?
i want to make a system that when you press a button one of these blocks in the yml drops. but i cant find out how i can use information from my yml file. can someone help me?
Next step I'd take is to attach a debugger to the server and step through it line by line. I'm sure there's a good explanation for it. Here's the JetBrains wiki for it https://www.jetbrains.com/help/idea/attaching-to-local-process.html
Righty o, I'll give that a whirl then - thanks, it's appreciated π
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/plugin/java/JavaPlugin.html#getTextResource(java.lang.String)
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/configuration/file/YamlConfiguration.html#loadConfiguration(java.io.Reader)
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/configuration/MemorySection.html#getKeys(boolean)
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/Material.html#getMaterial(java.lang.String)
https://hub.spigotmc.org/javadocs/spigot/org/bukkit/inventory/ItemStack.html#<init>(org.bukkit.Material,int)
No problem
Is there a way to add a world to the worlds to load on startup, at the moment when I create a new world on startup using new WorldCreator() (In onEnable()) and people join pretty much as soon as the server opens, they get teleported to the world, but they will get stuck in a void until the world loads.
Is your load attribute in your plugin.yml set to STARTUP?
no, so you are saying it needs to be set to STARTUP for worlds which aren't the "3 default worlds" to load before server opens?
Its currently POSTWORLD
Set it to STARTUP. POSTWORLD will call your onEnable after the default worlds have finished loading up.
Ok I will try and see if that works, thank you
startup will result in null world, as it is before world was loaded. just keep in mind, i dont know what you guys doing tho
Ok, so learned a new thing, you can't create new worlds on startup
Really? I'm amazed lol
So how would I go about having the 3 default worlds (normal, nether, end) generate, and then load a pre-made world called "lobby" load before onEnable is called
You could always kick players for a certain period of time with a "the world is still loading" message
Seems dirty
Temporary fix
Mayhaps @sullen marlin has a god-tier configuration option lurking around?
Is that sarcastic or a genuine question?
Genuine question. Dude knows his shit
"it's not a mistake", β¨ITS A MASTERPIECEβ¨
How to check if a respawn anchor is loaded so it explodes in the overworld
it's not a bug, it's a βfeatureβ
Hey, I'm having a problem with one of my commands, for some reason when the player does /tpa it automatically teleports him to the other player as if the "if" statement didn't exist, any idea why this is happening? ```java
if (command.getName().equalsIgnoreCase("tpa")) {
playerout = (Player) sender;
playerin = Bukkit.getServer().getPlayer(args[0]);
playeroutloc = playerout.getLocation(); // Not sure if this will be useful
playerinloc = playerin.getLocation();
playerin.sendMessage(playerout.getName() + " want's to teleport to you");
playerout.sendMessage("You have requested to teleport to " + playerin.getName());
if (playerin.performCommand("tpaccept")) {
playerout.teleport(playerinloc);
playerout.sendMessage("You have been teleported to " + playerin);
playerin.sendMessage(playerout + " has been teleported to your location");
} else if (playerin.performCommand("tpdeny")) {
playerin.sendMessage("You have denied " + playerout + "'s teleport request");
} else {
return false;
}
}```
I think you should look at what performCommand does
What you really should do is block joining players in the AsyncPlayerPreLoginEvent
What do you mean by that? You can check for an anchor in the respawn event
@vague oracle
did you use custom nbt or use the ItemCraftEvent ? ore PrepareItemCraftEvent ?
Show us how you register your recipes. I really hope that you dont use any events for that.
What spigot version?
Its not. The video youve sent suggests that some plugin is tinkering with Inventory click or prepare item craft events.
did you test the config input `?
this exactly could be null
not past logs
print it out
EntityDamageByBlockEvent .getDamager() returns null when using an anchor in the overworld.
hypixel skyblock :?
Pls explain what you are trying to do
Get the actual player who damaged the target using an anchor
(PVP Server)
so for my event I want to be able to get the block that damaged the player so I can give a kill to the actual killer
So you want to detect the player that caused the respawn anchor to explode so you can credit him with a potential kill?
Yes
if (target.getHealth() - event.getFinalDamage() <= 0)
To check if they actually died
Ok so the anchor only explodes if a player right clicks it, correct?
Yes, if it has 1 or more charges
RespawnAnchor anchor = (RespawnAnchor) event.getClickedBlock().getBlockData();
if (anchor.getCharges() > 0) {
PlayerKillPlayer.lastBlockByPlayer.put(event.getClickedBlock(), player.getUniqueId());
}
I'm just wondering why it returns null and not the respawn anchor
First shape, then ingredients
Is there a way to have the blockplaceevent place the block but the item not being consumed? i currently set the itemstack to 1 received by e.getItemInHand() but that doesnt work
And the EntityDamageByBlockEvent returns null for getDamager() ?
yikes...
event.setCancelled(true);
event.getBlock().setType(player.getInventory().getItemInMainHand().getType());
Several ways:
Cancel the event and place the block yourself
or
Increment the ItemStack amount one tick after the block was placed
ah yes, i am ashamed i did not try that
I see a ton of problems right from the beginning.
Rotations are ignored for example (log)
and shulker boxes are not filled
yea sorry, just a quick solution
That they could figure out further
Hm im thinking of something like the BlockExplodeEvent but there is no clean solution i could think of rn
nah its fine, i only need this for a non rotatable block
Maybe it would
Nvm
Is there a entity list
declaration: package: org.bukkit.entity, enum: EntityType
of all entities that would take damage
like blockList()
define take damage
items take lava damage cause they burn up
armorstands turn into items when you punch them
Hey, can someone help me? I'm trying to build my plugin for java 8. But it's compiling to java 16:
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
why are you trying to build it for java 8
Are you building artifacts?
How do you compile?
Make sure u select both options to java 8
maven install
I only have 1 option
Spigot version?
How do people support 1.8 -> 1.18? I can't seem to be able to do it with my code as it's so complex
1.12.2
Which IDE do u use
Mostly has to do with materials
It's also world edit is the pain
Well idk about that
Never heard of a plugin that supports all versions using worldedit api
intellij IDEA Community Edition
A lot of plugins do it tbh
Which
I found the issue
I can't be the only person trying to support all versions of worldedit...
There prob is a way
But do u know any of them that do?
I literally wrote a comment the line above to explain it
he uses modules the thing I've not touched before π₯²
modules are the best thing I ever encountered in maven
Why not gradle?
Sometimes gradle is a pain to use
because I don't use gradle for my own stuff
Gradle just works though
I think maven is way easier to use and there's nothing that I'd need that it cannot do
is there any event that fires as long as a player sits inside a vehicle or minecart (that does not require the minecart to move)
maven just works too
Maven is a mess
no
5 lines per import vs 1 in gradle
so? it's not messy just because the syntax is different
I always convert maven projects to gradle so it will actually work
You must be doing something wrong if it doesn't work for you
Its just a complete mess
That's your opinion. imho gradle files are totally ugly
it invented it's own syntax, maven uses XML which everyone already knows
imho gradle files are totally ugly
So a one liner import is ugly?
this is ugly in my eyes:
dependencies({
compile($/org.spigotmc:spigot-api:1.8.8-R0.1-SNAPSHOT/$)
compile($/com.github.ElgarL:groupmanager:2.9/$)
compile(group: $/org.springframework.boot/$, name: $/spring-boot-gradle-plugin/$, version: $/2.4.2/$)
compile(group: $/com.zaxxer/$, name: $/HikariCP/$ ,version: "4.0.3")
testCompile(group: "junit", name: "junit", version: "4.12")
})
that's just poorly laid out
this is well structured in my eyes
<dependency>
<groupId>de.jeff_media</groupId>
<artifactId>MorePersistentDataTypes</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.17.1-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>de.jeff_media</groupId>
<artifactId>SpigotUpdateChecker</artifactId>
<version>1.3.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>de.jeff_media</groupId>
<artifactId>Stepsister</artifactId>
<version>10.0.0</version>
<scope>compile</scope>
</dependency>
that is a mess
compileOnly 'com.sk89q.worldedit:worldedit-bukkit:7.2.8-SNAPSHOT'
I don't see why fewer lines should automatically be better
this takes me a second to detect it's worldedit-bukkit
that is perfectly fine where as you'd have like 5 lines
because it's mixed together with the group id, the version and the scope in one line
but tbh I don't care whether you like maven or not, this is #help-development and not #general
oh just one more thing
commandManager.getCommandCompletions().registerCompletion("items", new CommandCompletions.CommandCompletionHandler<BukkitCommandCompletionContext>() {@Override public Collection<String> getCompletions(BukkitCommandCompletionContext context) throws InvalidCommandArgument { return recipeManager.getItems().keySet();}});
commandManager.getCommandCompletions().registerCompletion("items", new CommandCompletions.CommandCompletionHandler<BukkitCommandCompletionContext>() {
@Override
public Collection<String> getCompletions(BukkitCommandCompletionContext context) throws InvalidCommandArgument {
return recipeManager.getItems().keySet();
}
});
first one is waaay better because it's one line, right? lol
6 looks better
what am i looking at
but that's java code not groovy...?
overriding tabcompletions?
it was just an example for less lines <> more lines
long class names
tip: if you are using intellij, they probably have a java <-> groovy converter (like java <-> kotlin)
new CommandCompletions.CommandCompletionHandler<BukkitCommandCompletionContext>
it's ACF
a- what
can someone tell me why this ^ only compiles my java classes but no kotlin stuff?
brr some of the code i made
[16:05:41 ERROR]: Could not load 'plugins/RaidKingdomDSRV-1.0 (1).jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.UnsupportedClassVersionError: me/branchyz/LostKingdomDSRV/LostKingdomDSRV has been compiled by a more recent version of the Java Runtime (class file version 60.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:131) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:329) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:251) ~[patched_1.12.2.jar:git-Paper-1618]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.loadPlugins(CraftServer.java:318) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:222) ~[patched_1.12.2.jar:git-Paper-1618]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:616) ~[patched_1.12.2.jar:git-Paper-1618]
at java.lang.Thread.run(Thread.java:748) [?:1.8.0_312]
Caused by: java.lang.UnsupportedClassVersionError: me/branchyz/LostKingdomDSRV/LostKingdomDSRV has been compiled by a more recent version of the Java Runtime (class file version 60.0), this version of the Java Runtime only recognizes class file versions up to 52.0
... ... ... ... ... ... ...
I'm getting this error when it's trying to load the plugin. The java version is 8...
ah
you compiled it using java 16 but try to run it on java 8
change the java version of your plugin
What the fuck
exactly
The plugin version is also java 8, Decompile:
https://i.imgur.com/dTwbYks.png
It's not
say i am on a bungee, and i have a server called "srv1" and "srv2", can "srv1" know its name without needing the bungee to tell it?
no
not that I know. AFAIK bungee only sends it on some channel if some bungee plugin does that
oh there is
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.
https://www.spigotmc.org/wiki/bukkit-bungee-plugin-messaging-channel/#the-bungeecord-plugin-channel scroll down until "GetServer"
yeah that's fine
i can just request on startup and store it
not like the server's name is gonna change or smt
It's just java 8 right?
also another question, does bungee send back the subchannel? say i send on "GetServer" do i receive "GetServer" back as a subchannel?
But i still get this error... :/
Try running clean then package again?
^
Ok
when you do stuff like this:
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Subchannel");
out.writeUTF("Argument");
// If you don't care about the player
// Player player = Iterables.getFirst(Bukkit.getOnlinePlayers(), null);
// Else, specify them
Player player = Bukkit.getPlayerExact("Example");
player.sendPluginMessage(this, "BungeeCord", out.toByteArray());
you can directly read the data from out
wait, does spigot 1.12.2 support persistent data containers and tilestates? Because all the imports broke after the clean...
No. 1.12.2 is unsupported
PDC is 1.14.1+
and Chunk PDC is 1.16.3+
yes i know i know
i have a question tho
whats the method to place item on item frame entity
Something was wrong with your maven either you didn't refresh it or a newer spigot was stuck in the cache. Either or when you ran the clean it removed it so your problem should be fixed (barring you're now stuck unable to use persistentdatacontainer)
ItemFrame#setItem
if i send to the bungee channel, the "GetServer" request (default bungee), will i get back "GetServer" as a subchannel (to differentiate between requests?)
my item frame is currently an entity
so like
then cast it to ItemFrame
Cast it
how lol
ItemFrame itemFrame = (ItemFrame) entity;
lol
Google "java how to cast"
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("GetServer");
```In the listener do i get the `GetServer` as first UTF then server name or just server name?
._.
https://www.baeldung.com/java-type-casting
if you're on java14+:
if(entity instanceof ItemFrame itemFrame) {
itemFrame.setItem(...);
}
ObjectClassYouWant thingy = (ObjectClassYouWant) otherThingy;
glass.addUnsafeEnchantment(Enchantment.KNOCKBACK, 1000);
glassMeta.setDisplayName(" ");
glass.setItemMeta(glassMeta);
if(sender instanceof Player){
for(int i=0; i <= 8; i++){
genListInv.setItem(i, glass);
}
p.openInventory(genListInv);
}```
Java 16. It was a preview feature in 14.
I try this and it wont enchant by glass, and clue as to what the problem is ?
is this the case or not
why are you using addUnsafeEnchantment?
you can just use addEnchantment
also, you are casting sender to player before checking if they are a player, why are you checking then?
should still work in 1.14, no? anyway, noone uses java 14 as of today anyway π
Yes, but on startup you'd have to define some flag which is annoying
you enchant the item itself, then overwrite it's meta so the enchant is gone again
a great idea
enchant the item before you get the ItemMeta, or enchant it AFTER you've set the meta back to the item
Is it a good idea to make/use a locale file using the approach shown here https://www.spigotmc.org/wiki/config-files/ making it as a custom config? Or is there a better approach?
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
your main class has a method called "getConfig()" use it
yeah that's for config but I want a side file as messages.yml
So I can have messages.yml and config.yml
you can create a new yamlconfiguration
Configuration myOtherConfig = new YamlConfiguration() and some other stuff iirc
wops forgot new there
waay to used to kt
any tutorials or something for that? xd
idk what would it be the "other stuff" lol
its literally like 3 lines of code
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
oh lol
XD
@vocal cloud
creating files?
is that a yes then? lmao
Well it's not my fault I tab in and out
Basically I just want to work with a locale file as lots of other plugins do to have customizable messages but idk if the correct approach is using a custom config file as my locale file
how to get the entity a player is looking at?
i'm doing it like thishttps://github.com/FourteenBrush/MagmaBuildNetwork/blob/main/src/main/java/io/github/FourteenBrush/MagmaBuildNetwork/utils/enums/Lang.java
ty will check it out
you dont have to use an enum it was just the easiest way in my case
Traditionally locales are done with JSON. You could do it with YAML as well though.
its easier with yaml
glassMeta.addEnchant(Enchantment.DURABILITY, 1, false);```
wut? where? every plugin I've seen use yaml locales xd
Why would this produce a Nullpointer?
Minecraft does it with JSON files for example
meh i miss the c# @"\take this " text\."
oh yeah but in the plugin context I've never seen it
json file would be possible too just change the lang constructor to use a json file in my example
It uses properties...
yeah because server admins loooove json
Minecraft no longer uses properties anywhere afaik
because they aren't meant to be edited by anyone
Lang files are replaced with JSON now.
maybe something to consider
imho EVERYTHING that's configurable should not be done in json because it's so easy to mess up the syntax
just use yaml for translations
TOML is the way to go π
if i'm not using (de)serialisation, is gson something?
agreed, json gets confused and even more if you're not used to it
DOCX >>>> Any type file
yeah and spigot.yml, paper.yml, etc are all yaml anyway so every admin is expected to know how it works π
hello, I'm trying to implements ProtocolLib with maven but my var protocolManager is null and I don't know why:```java
@Override
public void onLoad(){
instance = this;
protocolManager = ProtocolLibrary.getProtocolManager();
}```
Yes:
- The maven dependency is correctly configured
- The jar is installed on the server
- My plugin.yml has ProtocolLib as dependence
wait for onEnable
why that tho
all plugins first call onLoad, then all plugins call onEnable
onLoad -> dependencies -> onEnable ??
A, B, C, D :)
dependencies will be loaded before onEnable
A.onLoad
C.onLoad
B.onLoad
D.onLoad
A.onEnable
C.onEnable
B.onEnable
D.onEnable
holly how did you write all that so quick? XD