#development
1 messages Β· Page 130 of 1
PlayerInventory#removeItem(itemStack, items) should work
hm i'll try it out, ty
@NotNull
HashMap<Integer,ItemStack> removeItem(@NotNull ItemStack... items)
throws IllegalArgumentException```
Removes the given ItemStacks from the inventory.
It will try to remove 'as much as possible' from the types and amounts you give as arguments.
The returned HashMap contains what it couldn't remove, where the key is the index of the parameter, and the value is the ItemStack at that index of the varargs parameter. If all the given ItemStacks are removed, it will return an empty HashMap.
It is known that in some implementations this method will also set the inputted argument amount to the number of that item not removed from slots.
items - The ItemStacks to remove
IllegalArgumentException - if items is null
A HashMap containing items that couldn't be removed.
Does anyone know how to make a right click event where someone right clicks there sword and teleports x amount of blocks?
Use the interaction event? check if the item right clicked is a sword, grab the location and randomly change the location by offsetting it from the original?
Could you make that a little more in code language sorry haha!
I'm not trying to spoonfeed you the code.
Use PlayerInteractEvent -> check if player#getItem().getType() is the sword -> Use player#getLocation() to get the current location and randomly determine if you are simply going to change the x, or will do the others -> Set the player's location to the clone of the player's original location and add the offset to it.
ohhh okay cheers that makes sense
It's based on the latest library by the way, but you'd also need to check if they have a item that isn't air.
okay cool
when using a factory, what is the proper way to deal with enums where you have "subtypes"? for example i have:
is there a better way to do the ARRAY_X enums
i don't want to have to write a new line for every ARRAY_X type if possible, and my ArrayLogger is a generic class parameterised by this X
thats not really an appropriate time to use an enum
how come?
is this a bad idea then
Probably
which part? this is new
I'd assume the entire thing from what I've been reading :3
do you really need a factory here
well it's a cleaner way of wrapping all the loggers together i guess
no
and im initialising them from a config file
so i can do something like
MyEnum.valueOf("Foo")
do you know the shape of the data from the config file
use a dao
ok but even if have a data class like
data class loggerValue(type: LoggerType, name: String, sampleRate: Long)
```how does that make it easier to actually instantiate the loggers
unless i have some factory that can accept type and return an object of the type of logger i want
or did you mean something different
How does one get a list of ConfigurationSections in spigot's config API?
eg.
- test: 1
test2: 2
- test: 3
test4: 4
I'd want to serialize that into a list of test and test2
ConfigurationSection#getList doesn't allow for a custom object
What if you use ConfigurationSection#getKeys(false) and then just get the configurationsection using ConfigurationSection#getConfigurationSection() and add the configurationsection to a list?
but it's a list, not a object
I could be wrong here, but I assumed getKeys would get me the keys of an object
ow yeah
let me find out
idk if its possible with spigot's yaml stuff. I know its possible with libs like ConfigMe tho
wait
@hard wigeon don't you just use getList?
oh you said it doesn't allow custom objects?
you sure?
ah
for what?
i appreciate the help but im not understanding what you are suggesting
An easy method is by using YAML or JSON
SnakeYAML is built inside of the Spigot API, so that's a straightforward option.
okok
ok did you have a good tutorial for JSon ? I can't find something simple :/ for me to understand
just last question, mysql is easy ?
It's neither easy nor hard. It's a good option in some circumstances.
public class Main extends JavaPlugin {
private Connection connection;
@Override
public void onEnable() {
System.out.println("ON");
try {
Connection con = getConnection();
assert con != null;
PreparedStatement posted = con.prepareStatement("INSERT INTO users (first_name, last_name, num_points) " + "VALUES ('ThΓ©o', 'test', 1)");
posted.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/server_test";
String username = "root";
String pasword = "";
Class.forName(driver);
Connection conn = (Connection) DriverManager.getConnection(url,username,pasword);
System.out.println("Connected");
Statement st = conn.createStatement();
return conn;
}catch (Exception e){System.out.println(e);}
return null;
}
}
ok its work
fiouf
it's not very clean but it works
I'm no Kotlin expert but I'm fairly sure all default parameters must go at the end, after mandatory ones
alternatively you could do blah("blah", sampleRate = 123)
not sure if that would work
Can somebody pls help me kill my bot that's running through a raspberry pi?
I forgot the command π₯²
slam slam, then no more bot
Right
Or pi π
I guess I'm just slow in the head
still experiencing the issue?
Sorry I should've clarified, I wanted to end the screen for my bot
But the bot never actually started
The command I'm using to try and start the bot is screen java -jar **BotName**.jar
To end a terminal instance, have you tried CTRL + D, there will be no warnings attached.
screen -r id
I'm pretty positive, it's not running is because you provided the screen argument in front of java command.
as usually on a screen you'd run for example: java --version to see what sdk you are running.
Hm that's weird, I remember using this exact command a few months back and it worked fine. I'll try that also, thanks again!
How do I find the id?
screen -list
screen -S screen_name -X quit to kill it
Ok that's a lot of information lol let me write this down somewhere
and ctrl A -> D (without ctrl) to exit without terminating screen
Possibly you meant sudo instead of screen to run it?
Possibly...
Sorry, give me a second to try all these new commands and give feedback π
For example, you cd into the folder with the jar, and then run sudo java -jar BotName.jar
How do I cd into a specific folder?
I tried cd home/pi as well as cd home\pi which is my bot's folder
Ah
Nevermind
Alright so far I should be good, thanks all!
Ah wait a minute, it seems I'm unable to type any further commands after starting my bot
It just sends me to an empty line
Which means I can't exit the terminal without terminating
anyone know why gradle might be giving me
Error: Could not find or load main class telemetryapp.TelAppKt
Caused by: java.lang.ClassNotFoundException: telemetryapp.TelAppKt
```i literally have `src/main/java/telemetryapp/TelApp.kt`
. is not a valid class/package identifier afaik
mistype
a
i tried adding
sourceSets {
main.java.srcDirs = []
main.kotlin.srcDirs = ['src/main/java', 'src/main/kotlin']
main.resources.srcDirs = ['src/main/resources']
}
```to `build.gradle.` but doesnt work still
ctrl a -> d (without ctrl)
thats how you exit a screen without terminating
not sure if theres another way to exit
how would I send someone to jail when coding a plugin
I'm trying to edit this plugin so it send a player to jail rather then setting their gamemode to spectator when they get killed
eliminate(Player player, Player killer) {
player.setGameMode(GameMode.SPECTATOR);
player.sendMessage(ChatColor.RED + "You have been eliminated!");
InventoryUtils.giveHeadItem(killer, player);
addElimination(player);
}
edit: how do I ban someone
d;spigot BanList#addEntry
@Nullable
BanEntry addBan(@NotNull String target, @Nullable String reason, @Nullable Date expires, @Nullable String source)```
Adds a ban to the this list. If a previous ban exists, this will update the previous entry.
target - the target of the ban
reason - reason for the ban, null indicates implementation default
expires - date for the ban's expiration (unban), or null to imply forever
source - source of the ban, null indicates implementation default
the entry for the newly created ban, or the entry for the (updated) previous ban
@icy thistle
I'm using IntelliJ IDEA how do I compile a plugin into a .jar file its been a while since I've done this
Use a build tool like maven / gradle
I have plugin running the command jail playername
however the server says Player not found. when I use player.getDisplayName()
but it works when I manually run the commands
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "jail " + player.getDisplayName() + " dead");
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "unjail " + player.getDisplayName());
[20:51:30 INFO]: CONSOLE issued server command: /jail TCubed3 dead
[20:51:30 INFO]: Error: Player not found.
[20:51:34 INFO]: jaredy00 issued server command: /jail TCubed3 dead
[20:51:38 INFO]: CONSOLE issued server command: /unjail TCubed3
[20:51:38 INFO]: Error: Player not found.
[20:51:44 INFO]: jaredy00 issued server command: /unjail TCubed3
player.getName()
whats the difference
yes
misread
TCubed3
with the d
Yeah, typo
ok then yes
Hm
I was running the command ingame manually as well to test
and it worked ingame
/jail TCubed3 dead?
I'm using essentials jail command
The command syntax is /jail <jail> <player> <duration> (reason) afaik
duration and reason are both optional
for whatever reason changing it to player.getName() worked
This still isn't the bot channel
Hi, so I want to make a GUI Inventory, I have the inventory made, but not sure how to remove the players from moving items in it/adding commands to a head that teleports you to a gamemode.
would highly suggest using a library for this sort of thing
https://mf.mattstudios.me/triumph-gui/introduction
makes things 100 times easier
To answer your question otherwise, you would wanna look for InventoryClickEvent, check if its the right inventory by name or smth and then handle your options
it will get complex quite quick which is why i would just use the library
sus
Umm, I have installed XAMPP with PHP 8.1.4 but when I check my php version using php -v the version is still 8.0.3, it should be 8.1.4. I uninstalled XAMPP that were using PHP 8.0.3 and I install it again with the newest PHP version.
i installed xampp 4 or 5 years ago, never updated it. still working
Some of my project require newest version of PHP and I have tried to only update the php but I ran into some errors and then I decided to reinstall the xampp.
my understanding of suspend fun was that it would wait, but intellij is telling me i dont need suspend
It waits with both suspend and without
What suspend does it lets kotlin break down the method call to call the continuation from its result rather than blocking the current thread
Reduces chances of task starvation
i read that i'm not meant to mark it as suspend unless forced to, so best to remove that and keep the rest as is?
i wasn't sure if it's a good idea to have a coroutine inside each of these that deals with the redis
probably not necessary right
suspend ussually means you are performing some operation with idle time such as IO
Thatβs unnecessary. I would go with try {} catch (Exception whoCares) {}
it's too granular and descriptive?
My way?
no what i did
How are messages valued?
E][
so true
So I'm looking through the jda docs right
so true
right
left
And I'm trying to get some slash commands running, and I see that you need to add jda.upsertCommand("ping", "Calculate ping of the bot").queue(); in your main method for it to work. So I'm wondering if the method was changed or smth
My bad I was caught up in a convo didn't get to finish
Since I can't use that method
Doesn't seem to be recognized
π€ interesting, are you sure jda is a JDA instance (and other JDA methods show)? and that you're using the latest version? (4.4.0_352 or 5.0.0-alpha.9 if you're on v5)
Ah, you know that would explain it. I'd need to create a JDA instance, but what should I initialize it to?
I already have a JDABuilder atm
wdym?
I don't have a JDA instance atm, the code I pasted above was right from the docs
JDABuilder#build
I mistaked their jda for a JDABuilder
wym?
JDA jda = JDABuilder.createDefault("token").build();
So I don't need a JDABuilder?
u need to build it
as seen here
JDA jda = JDABuilder.createDefault(Constant.token) // should be TOKEN btw
.setActivity(etc)
.setStatus(etc)
.build();
``` π
Why should it be TOKEN
Oh okay
I'll change that
Seems like there isn't a setActivity() method though
Wait
I spoke too soon
How can I find the name of the screen I'm on atm?
For termius
screen -ls - it should say Attached
It says detached π₯²
I suppose it doesn't matter right? I was only trying to kill it
Well, how do I reattach the screen?
screen -R NAME -> Creates a new screen
screen -r NAME -> Resumes screen
screen -X -S NAME kill -> Delete screen
ctrl + a -> d -> Close screen
I appreciate it, lemme copy paste this to the notepad π
This way, I won't ask the same question twice anymore
ya bet
Is killing a screen the same as deleting a screen?
yes
If so, why did you recommend I use screen -S screen_name -X quit to kill a screen earlier?
uhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
google π₯²
kill
this was from piggy
i think
nice
All is good ||so far||, so thank you!
I'm quite inexperienced with Gson, so excuse if this is a stupid question, but how would a Java class need to look like if I want to deserialize this JSON input to one?
{
"file_version": 1,
"entry_1": {
"major": "1.x",
"version": "1.0.0"
},
"entry_2": {
"major": "1.x",
"version": "1.1.0"
},
"entry_3": {
"major": "2.x",
"version": "2.0.0"
}
}
Some notes:
entry_ncan be any String, not justentry_n- There can be any amount of
entry_nentries in the JSON. file_versionwill always be named like that and always has a whole number (no decimals).majorandversionwill always return String and will always be named like this.
So... Does Gson allow this kind of deserialization?
probably need to add an array for the entries
you have to know the schema you want to deserialize
so it would look like json { "file_version": 1, "entries": [ "entry_1": { "major": "1.x", "version": "1.0.0" }, "entry_2": { "major": "1.x", "version": "1.1.0" }, "entry_3": { "major": "2.x", "version": "2.0.0" } ] }
then you would need an object for entries
err, for the entries just
"entries": [
{
"major": "...",
"version": "..."
},
{
...
}
]
otherwise it would need to be an object
I think he wants the class structure to convert from gson to a class (and back).
yeah but if you have each entry separately rather than in an array then you would need
class Thing {
int fileVersion;
Version entry1;
Version entry2;
Version entry3;
Version entry3;
...
}
one class for each # of entries
Or a map
Yeah, bottom line is they need to be in a collection of sorts
public class <class> {
int fileVersion;
Map<String, ObjectClass> entries;
}
public class ObjectClass {
String major;
String version;
}
``` or something.
I want to rotate a shape made from particles, in this case a double helix. I have the list of vectors representing the helix, and it works fine. However, I want it to point in the direction the player is looking. I do this by getting the players yaw and pitch and feed it into this rotate function. All input values are correct, however my math is so off, I tried following a guide but it did not go any better. The only thing that actually works is the pitch while facing south. I spawn the particles like this:
World w = player.getWorld();
for (Vector v : shape.getVectors()) {
w.spawnParticle(Particle.SCRAPE, location.add(v.getX(), v.getY(), v.getZ()), 10);
//Revert back to the original location values
location.subtract(v.getX(), v.getY(), v.getZ());
}
Here is my code for rotating the helix: https://paste.helpch.at/terepasufu.cpp
The helix is pre-calculated and stored in HELIX.getShape()
I copied parts of my actual code to the paste as I have a lot more and only need help with this part and want to keep the code here to a minimum. So if there are any misspelled variable names or missing parenthesis, that is why. The other code does not interfere with this in any way and only handles other shapes and their parameters.
hello ! how do I run a MySql query to find if a column contains a character string.
Like this:
If Swaford_ exist in column "Owner" in table "Town"
I tried that :
"SELECT * FROM town WHERE owner LIKE '"+ sender.getName()+ "'", "owner"
public void readData(String sqlRequest, String getResultString){
try {
Connection con = getConnection();
assert con != null;
PreparedStatement statement = con.prepareStatement(sqlRequest);
ResultSet result = statement.executeQuery();
while (result.next()){
System.out.println(result.getString(getResultString));
}
}catch (Exception e){System.out.println(e);}
}
public void readData(String sqlRequest){
try {
Connection con = getConnection();
assert con != null;
PreparedStatement statement = con.prepareStatement("SELECT Owner FROM town WHERE Owner='Swaford_'");
ResultSet result = statement.executeQuery();
while (result.next()){
System.out.println(result.getString("Owner"));
}
}catch (Exception e){System.out.println(e);}
If you want to select the row of the owner, it will be something like
SELECT * FROM TABLE_NAME WHERE owner = 'NAME';
I tried
dosen't work
i dont understand
Could you show me the error?
no error :/
oh fuck me
lol i am executing a function before the command
sry
mb
x)
Hi, i've got a problem, i search to get the ingredient's list of a craft for a GUI that show the item's craft in this GUi, but i don't know how. Sorry for my bad English
public static void createItemCraftGUI(Player player, ItemStack item, ItemMeta meta) {
itemCraftGUi = Bukkit.createInventory(null, InventoryType.WORKBENCH, "Craft " + item.getItemMeta().getDisplayName());
List<ItemStack> itemList = new ArrayList<>();
for(Recipe recipe : Bukkit.getServer().getRecipesFor(item)) {
if (recipe instanceof ShapedRecipe) {
ShapedRecipe shaped = (ShapedRecipe) recipe;
itemList.add(Bukkit.getServer().getRecipesFor(item));
for (int i = 0; i < itemList.size(); i++) {
itemCraftGUi.setItem(i, (ItemStack) Bukkit.getServer().getRecipesFor(item).get(i));
}
}
}
player.openInventory(itemCraftGUi);
}
I know they are error but i just search how can i get ingredient list
Why are you getting the recipe three times when you already have it?
I don't know i search many solution, i want to get the necessary's list of an item to be craft
public static void createItemCraftGUI(Player player, ItemStack item, ItemMeta meta) {
itemCraftGUi = Bukkit.createInventory(null, InventoryType.WORKBENCH, "Craft " + item.getItemMeta().getDisplayName());
for(Recipe recipe : Bukkit.getServer().getRecipesFor(item)) {
if (recipe instanceof ShapedRecipe) {
ShapedRecipe shaped = (ShapedRecipe) recipe;
int slot = 0;
for(Entry<Character, ItemStack> entry : shaped.getIngredientMap().entrySet()) {
itemCraftGUI.setItem(slot, entry.getValue())
slot++;
}
break;
}
}
player.openInventory(itemCraftGUi);
}
``` Or something like this.
hey so im currently working on creating a prefix plugin for my server i have textComponents working however i cant seem to workout how to remove the default username from the chat messages, how would i do this?
Thanks, i look at your code and i think it's good but i've got an error
" foreach not applicable to type 'java.util.@org.jetbrains.annotations.NotNull Map<java.lang.Character,org.bukkit.inventory.ItemStack>' "
I don't have an IDE open adjust the code accordingly.
Also add a null check before setting the item.
.entrySet()
^^^
Owww that work but i've got an another problem now items are not in order
add .png
Also let me see your code
if slot++; is in the null check take it out.
Debug the ingredientmap. I thought it had a char for every slot.
Sorry but i don't know how can i debug the ingredientmap...
just add a message output in the for loop and as the string put the key and value.
player.sendMessage(entry + " : " + shaped.getIngredientMap().entrySet());
Like this ?
nope entry.getKey() + " | " + entry.getValue()
Ok sorry to take your time
Let me see the code with the debug
add slot to the debug
put the debug before slot++
OWWWWW YES
Thanks
it work
You're the king
I love you
Also there can be multiple recipes for the same itemstack so when you want you can animate the recipe. (I think essentials does this with /recipe)
Yes good idea but normally i just use this GUI to see my item's craft, enchanting table was for example.
I've got a problem
I've got multiple craft for cobblestone but with itemeta different
Cobblestone Tier I, Tier II, Tier III,... like compressed cobblestone
But
I think when i use Recipe recipe : Bukkit.getServer().getRecipesFor(item) , it's return the bad recipe
You gotta account for that.
Modify your code anc check if its the recipe you want to display
Sorry but i don't know how...
I've got an idea, can i just get the recipe with the Namespacedkey of the craft
https://imgur.com/h7J7JrI.png
yeap but like I said the items can still have multiple recipes.
Yes i know but that's not my actually problem, my problem is that when i want to see the craft of my cobblestone tier 1, the gui show me the craft of my cobblestone tier 4 because it is the last in my init method of craft.
https://imgur.com/oWXqA8Y.png
Well then again... you have to code accordingly lol. Especially for custom items you have to check the recipe.
Okay, big thanks
π
i'm come back. I created database on my server and connect my plugin with this. When i uss Laragon and setup a local data base, its perfect work.
[17:44:35] [Server thread/INFO]: The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
[17:44:35] [Server thread/WARN]: java.lang.NullPointerException
[17:44:35] [Server thread/WARN]: at ch.swaford.ashdale.MySqlClientManager.insertData(MySqlClientManager.java:40)
[17:44:35] [Server thread/WARN]: at ch.swaford.ashdale.commands.CommandTownCreate.onCommand(CommandTownCreate.java:38)
[17:44:35] [Server thread/WARN]: at org.bukkit.command.PluginCommand.execute(PluginCommand.java:45)
[17:44:35] [Server thread/WARN]: at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:149)
[17:44:35] [Server thread/WARN]: at org.bukkit.craftbukkit.v1_16_R3.CraftServer.dispatchCommand(CraftServer.java:761)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PlayerConnection.handleCommand(PlayerConnection.java:1936)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PlayerConnection.c(PlayerConnection.java:1779)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PlayerConnection.a(PlayerConnection.java:1732)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PacketPlayInChat.a(PacketPlayInChat.java:49)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PacketPlayInChat.a(PacketPlayInChat.java:1)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.PlayerConnectionUtils.lambda$0(PlayerConnectionUtils.java:28)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.TickTask.run(SourceFile:18)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.IAsyncTaskHandler.executeTask(SourceFile:144)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.IAsyncTaskHandlerReentrant.executeTask(SourceFile:23)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.IAsyncTaskHandler.executeNext(SourceFile:118)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.MinecraftServer.bb(MinecraftServer.java:1061)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.MinecraftServer.executeNext(MinecraftServer.java:1054)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.IAsyncTaskHandler.awaitTasks(SourceFile:127)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.MinecraftServer.sleepForTick(MinecraftServer.java:1038)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.MinecraftServer.w(MinecraftServer.java:970)
[17:44:35] [Server thread/WARN]: at net.minecraft.server.v1_16_R3.MinecraftServer.lambda$0(MinecraftServer.java:273)
[17:44:35] [Server thread/WARN]: at java.lang.Thread.run(Unknown Source)
String url = "jdbc:mysql://hihihiihihihihihi:3306/minecraft";
and my mysql service is running
hey, i am trying to detect a packet with protocollib but i get the following error: https://paste.razerstorm.be/iduwigopof.sql
(protocolLib is installed)
(this error pops up at startup/reload)
This is the code i tried (in the onEnable):
ProtocolManager manager = ProtocolLibrary.getProtocolManager();
if(getServer().getPluginManager().getPlugin("ProtocolLib") != null ){
manager.addPacketListener(new PacketAdapter(this, ListenerPriority.NORMAL, PacketType.Play.Client.POSITION) {
@Override
public void onPacketReceiving(PacketEvent e) {
//handlePing(e.getPacket().getServerPings().read(0));
}
});
}else{
getLogger().severe("ProtocolLib is niet geinstalleerd op deze server!");
}```
And this is my gradle import:
```gradle
maven {
url = "https://repo.dmulloy2.net/repository/public/"
}```
```gradle
compileOnly 'com.comphenix.protocol:ProtocolLib:4.7.0'
anyone that knows how to solve the error?
Is the plugin version 4.7.0?
its was at 4.8.0 but after changing it its still the same error
'm come back. I created database on my server and connect my plugin with this. When i uss Laragon and setup a local data base, its perfect work.
[17:44:35] [Server thread/INFO]: The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
Where? and is this development related?
Idk where to write
If someone send gifs a see links
Where?
On every server
Discord?
Yes
okay let's go to #off-topic
Hi, I wanted to code a plugin which gives every player a random item which he has to collect to get a reward. So I made a hashmap<UUID, Material> but every time I get to the point if(forceItem.containsKey(uuid)) it doesnΒ΄t do the rest of the event though it has my UUID with a random material Saved in the hashmap
?paste
Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
β’ HelpChat Paste - How To Use
Have you tried any debug messages?
Yes because of that I know which line of code the problem is
so let's add some more
logger forceItem.containsKey(uuid)
loop map and log each uuid
log uuid
Does it proceed to if(item != null)?
no it only goes till if(forceItem.containsKey(uuid))
what do you mean with logger forceItem.containsKey(uuid)? like after the if?
log it
log all those values
Bukkit.getLogger().info(forceItem.containsKey(uuid)+"");
or however you want to do your debug message
should be false based on previous debugging, but always good to see your values
that is false the other 2 didnt send anything
no there just wasnt a message
where did you put them
@EventHandler public void onInventoryClick(InventoryClickEvent e) { Inventory inv = e.getClickedInventory(); Player p = (Player) e.getWhoClicked(); UUID uuid = p.getUniqueId(); p.sendMessage(uuid); for(UUID uuid1 : forceItem.keySet()) { p.sendMessage(uuid1); } Bukkit.getLogger().info(forceItem.containsKey(uuid) + ""); if(forceItem.containsKey(uuid)) { p.sendMessage("Player found"); Material getForceItem = forceItem.get(uuid); if (inv != null && inv.contains(getForceItem)) { giveReward(p); p.sendMessage("reward"); } } }
?codeblocks
Use codeblocks for formatting code or configuration files:
```<language name>
<your code here>
```
For example:
```yaml
test:
- βhiβ
- βthereβ
```
Produces:
test:
- βhiβ
- βthereβ```
Try logging the uuid instead
and maybe log the player
p.sendMessage(uuid); not even this sent to the player?
it didnt but now it worked
ah
and are you sure you set the item in the map
how did you do that?
oh i see the command, did you debug that?
Yes Java public void setForceItem(Player p) { setForbidden(forbidden); List<Material> items = new ArrayList(Arrays.asList(Material.values())); items.removeIf((material) -> {return !material.isItem();}); items.removeIf((material) -> {return forbidden.contains(material);}); int randomNumber = random.nextInt(items.size()); Material mat = items.get(randomNumber); forceItem.put(p.getUniqueId(), mat); p.sendMessage("Β§4Manhunt Β§8| Β§7" + mat); p.sendMessage(forceItem.toString()); if(p.getInventory().contains(mat)) { giveReward(p); }
try debugging the command and/or the setForceItem method
setForceItem is already debugged because of p.sendMessage("Β§4Manhunt Β§8| Β§7" + mat); right?
and you get that message when you run the command?
yes
instead of the forceitem.tostring try looping the keyset
log that and see
because that would be right after adding it...
I am the only one added so its only one uuid
ok wait
we're missing a message here I realize
we should have player uuid:
forceitems uuids:
player:
contains:
so either forceitem is empty here
or we missed somethin
yeah because i only wrote the command and not did the event
no, here
What is the code for this
is command just the label?
Bukkit.getLogger().info(uuid + "");
}```
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
for(Player p : Bukkit.getOnlinePlayers()) {
setForceItem(p);
Bukkit.getLogger().info("command");
}
return false;
}```
Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
β’ HelpChat Paste - How To Use
Any reason why getCommand("command").setAliases(Arrays.asList("alias_1", "alias_2")) wouldn't work?
Like if I type the aliases the command doesn't run.
command executor?
yes
what it look like
have you checked the actual cmd.getName() value
in the past, when I type an alias it goes through as the name
no idea why
yeah outputs command
ooft
[20:24:45 INFO]: sfi | 541c6d78-b2c5-4125-ad36-70c272e844e2
[20:24:45 INFO]: cmd | 541c6d78-b2c5-4125-ad36-70c272e844e2
[20:24:51 INFO]: pUuid: 541c6d78-b2c5-4125-ad36-70c272e844e2
[20:24:51 INFO]: player: CraftPlayer{name=Sensaicraft}
[20:24:51 INFO]: event | false
Wait, this public void setForceItem(Player p) and public HashMap<UUID, Material> forceItem = new HashMap<>(); are both non static. Are you making a new object every time you add a player?
Might that be why?
he never makes a new map though that I see
Adding to the Sensaicraft discussion
and in the command you can see the value(s)
Well i creates a new one with every object
and if they make one every time they add a player
it wont add
to the same map as the listener one
try making them static
I cant come up with anything better
ok i will try it
actually it doesn't output when I type the aliases
I don't get why you see the values in the onCommand method though
aha
does it run at all
the executor
nope
hmm, I wonder if you have to update something else after setting aliases. commands are confusing to me
If I add the aliases directly to the plugin.yml they work.
if(forceItem.containsKey(uuid)) worked now but it still didnΒ΄t gave a reward so if (inv != null && inv.contains(getForceItem)) { giveReward(p); p.sendMessage("reward"); } didnΒ΄t work
Hold on, I'll try re-write it. spoon feed :>
try containsAtleast(getForceItem, 1); Otherwise debug the item and the if statement
when I download source code for a plugin project how do I know how to compile it so it works the way intended
same for java version used
So it looks like I need to mess with the command map because setAliases doesn't do anything after registering the commandπ€¦
ya... figured it was something weird like that
Try this, I have not tested it so unsure if it works as you want it to, also I don't have your other classes like OpLoot. But give it a go https://paste.helpch.at/vorikelaye.java
public void setBaseAliases() {
if(!getConfig().isSet("Commands.Base_Aliases")) return;
CommandMap commandMap = null;
try {
final Field f = Bukkit.getServer().getClass().getDeclaredField("commandMap");
f.setAccessible(true);
commandMap = (CommandMap) f.get(Bukkit.getServer());
Command cmd = commandMap.getCommand("command");
cmd.unregister(commandMap);
cmd.setAliases(getConfig().getStringList("Commands.Base_Aliases"));
commandMap.register("command", cmd);
} catch (Exception e) {
e.printStackTrace();
}
}
I made your optimisations in my code but it doesnΒ΄t function
Did you Copy paste or change it yourself?
I changed it my self but kept an eye on the problems tab and there was nothing
Try just copy pasting it, see what happens. I'm not saying you have, but you could've missed something
uh any ideas why I could be getting this?
Error:
Caused by: java.lang.ClassCastException: class java.util.UUID cannot be cast to class java.lang.String (java.util.UUID and java.lang.String are in module java.base of loader 'bootstrap')```
Line of the issue:
```JAVA
public boolean isOwnerOfClan(UUID uuid, @Nullable String clanId) {
return db.getString("clans." + clanId + ".owner").equals(uuid.toString());
}
specifically, the issue seems to be uuid.toString()?
like, is it normal that I can't cast it to a string?
UUID.toString() works fine. There should be no problems with it. I can't see anything wrong
You can't cast it though
This UUID.toString() is fine, (String) UUID is not
aby chance your db stores it as a UUID instead of a String?
that's a quite big change yes.
okay no
it's a string
String.valueOf(uuid) that's how I store it
unless... okay found the issue
THANK YOU π It works now
ty guys
Nice! Happy to help! π
Still need help with this if anyone can take a look :))
Hi would anyone be able to help me why I am receiving a null here? :
java.lang.NullPointerException
at me.fiftyone.bungee.core.CoreListener.serverSwitch(CoreListener.java:98)
What I am trying to do is for a player to be sent a title when switching servers
Here is the code:
final Title t = ProxyServer.getInstance().createTitle();
String sectorMsg = StringUtils.replace(Bungee.getInst().getApi().getGeneralConfig().SECTOR_CHANGE, "%old-sector%", e.getFrom().getName());
sectorMsg = StringUtils.replace(sectorMsg, "%new-sector%", newSectorName);
t.subTitle(TextComponent.fromLegacyText(sectorMsg)); <--- This is the line 98
t.fadeIn(1);
t.fadeOut(20);
t.stay(40);
t.send(player);
whats the caused by text?
in the stacktrace
cause it will say what was null
?paste
Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
β’ HelpChat Paste - How To Use
It's really weird because it doesn't tell me what is null just tells where which line
This is the full error:
im going to take a guess and say its saying that sectorMsg is null
are you sure its not null?
what is sectorMsg? (what does it print?)
do a sysout or the bungee equivalent of plugin.getlogger.info or whatever its called
Omg guys never mind I made an oopsie thanks for your help tho
I forgot to delete my config and the new line for .getGeneralConfig().SECTOR_CHANGE didn't generate
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'linkedaccounts (name,uuid,token) VALUES ('not_Nuggets','0488d5c5-ebc9-38c9-90...' at line 1
this is the new error sorry
public static void createPlayer(Player player, String token) {
try {
UUID uuid = player.getUniqueId();
if(!exists(uuid)) {
PreparedStatement ps2 = plugin.sql.getConnection().prepareStatement("INSERT IGNORE INFO linkedaccounts"
+ " (name,uuid,token) VALUES (?,?,?)");
ps2.setString(1, player.getName());
ps2.setString(2, uuid.toString());
ps2.setString(3, token);
ps2.executeUpdate();
}
} catch(SQLException e) {
e.printStackTrace();
}```
yea
Your issue is likely that IGNORE INFO part
You could likely just do INSERT INTO linkedaccounts
Do you mean INSERT INFO in the
Instead of INSERT INTO
this is what i do to recreate your table and it works
so INSERT INTO linkedaccounts (name, uuid, token) VALUES (?, ?, ?)
Also how did you uh get to see the table like that
yea what app is that
when testing SQL stuff i use https://sqliteonline.com
SQL OnLine - (Test DB): SQLite, MariaDB / MySQL, PostgreSQL, MS SQL Server. User-friendly interface for data science. No registration for start, No DownLoad, No Install. Online test SQL script. Online Open/Save SQLite file. Online view all table DB. Fiddle link SQL text and DB file. SQL Test, SQLite in Browser, Data for World, online sql compile...
my dark mode extension is making the colours kinda wonk but yeah i use it a ton
Looks great, ty
Okay;
im learning NMS and I found this example on the web, and I changed some stuff.
public class BigWither extends EntityWither {
public BigWither(Location loc){
super(EntityTypes.aZ, ((CraftWorld) loc.getWorld()).getHandle());
this.b(loc.getX(), loc.getY(), loc.getZ());
this.r(false);
this.n(true);
this.a(new ChatComponentText(ChatColor.GREEN + "MyEntity"));
}
}
First, what do I return?
Second, when I call it up, do I do this?
connection.a(new PacketPlayOutSpawnEntity(BigWither));
again with the SQL nonsense
"PreparedStatement ps = plugin.sql.getConnection().prepareStatement("SELECT name FROM linkedaccounts where token=?");"
this line is producing a nullpointerexception. I already checked, and the argument I giving for token isn't null.
where wasnt capital
xd
wawit nvm
Either plugin, sql, or connection is null
Showing us the entire class would help
testFunction(Array<MyObject>::class.java)
fun <T> testFunction(t:T):T{
return getDataFromRestAPI("url", T::class.java)
}``` How come testFunctions returning a `Class<Array<MyObject>>>` and not just an `Array<MyObject>`
You're passing Array<MyObject>::class.java, testFunction expects a T instance, not a Class<T>
Anyone can recommend best way to fill in empty slots in a GUI?
Is it possible to add a nbt to a spawned entity?
How can I change the metadata of an outgoing spawn entity packet with protocol lib?
yes
ty
Okay so i tried adding an nbt tag to a entity with this code:
Entity huisdier = p.getWorld().spawnEntity(p.getLocation(), EntityType.WOLF);
huisdier.setCustomNameVisible(true);
huisdier.setCustomName(Util.chat("&cGerda"));
NBTEditor.set( huisdier, "hond", "ddgpets" );```
but it won't work, this is the code where i check for the nbt:
```java
if(NBTEditor.contains(e.getEntity(), "ddgpets")) {
Bukkit.broadcastMessage("Test 2");
e.setCancelled(true);
}
So how would I pass it a T instancE? I /havent used generics before lol
testFunction(arrayOf<MyObject>()) or however you create arrays in kotlin
i need help with some batch, for some reason setlocal EnableDelayedExpansion is making it so that when the 2nd call command is ran, it goes back to the directory where the called file is:
Specific Export.bat:bat call backend\specific.bat call "%~dp0backend\export.bat" false
specific.bat: https://paste.srnyx.xyz/acojemavol.bat
example: specific.bat makes it go to modpack/OO/1.18.2. then, when it does call "%~dp0backend\export.bat" false, it goes back to modpack/Tools (which is where Specific Export.bat is)
when i remove setlocal EnableDelayedExpansion in specific.bat it works, but i need it in order for other parts of the script to work
ok i think i fixed it
i had to put setlocal EnableDelayedExpansion in Specifix Export.bat (before call backend\specific.bat) for some reason
tbh i just used a for loop
with a switchcase for all buttons and default was glass panes
is there a way to change the name fo a item you have in your invertory? with spigot or just with a minecraft command?
hey how can i "compound command"
like this :
/towncreate <args> -> /town create <args>
Could anyone help me so im Using Deluxechat premium But i use it in a faction server but now the ranks dont have the right color and YOu cant see the faction name anymore?
spigot
yes
how?
thanks can i ask you questions if i cant figure it out?
sure
do you have code where you did this?
player.getInventory.getItem or something like this
im really stuck this is what I got rn i dont know what to do and i cant find good info on internet
Item meta = player.getInventory().getItem(Material.GOLD_BLOCK);
that wont work on every end lol
you might just want to take a look at the documentation
ItemStack itemStack = new ItemStack(Material.IRON_SWORD); this doesnt give me a iron sword? what did i do wrong
not sharing the rest of the code
lol
its on player movement
@EventHandler
public void onMove(PlayerMoveEvent e) {
ItemStack itemStack = new ItemStack(Material.IRON_SWORD);
}
Well, you are creating an iron sword item, but you aren't doing anything with it
If you want to add it to the player's inventory, get the player from the event, get their inventory and add the item, should be something like so event. getPlayer().getInventory().addItem(item)
Be aware that the move event is called on every single tiny movement so you're going to fill that quickly
@EventHandler
public void onMove(PlayerMoveEvent e) {
ItemStack itemStack = new ItemStack(Material.GOLD_BLOCK);
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(MyFirstPlugin.balance.toString());
meta.setLore(Arrays.asList("line 1", "line2"));
itemStack.setItemMeta(meta);
if (balance_int == 1) {
e.getPlayer().getInventory().addItem(itemStack);
balance_int = balance_int-1;
}
}
@grim oasis here
and MyFirstPLugin has ```java
public static Integer balance;
send the class in a paste
you mean this
public class MyFirstPlugin extends JavaPlugin {
the entire class that contains this method
because it says there is an NPE on line 96
public class Events implements Listener {
the entire class
sorry uhhm what do you mean with that
all the text
a class is a single file
i read the entry class
this is only the definition of a class
where the other } is located, is where the class stops
so... at the bottom
Hello there, is there a solution for taking the entity player is looking at without using 50 lines where we check every mobs around the player ?
its to big
Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
β’ HelpChat Paste - How To Use
can you run the server again to get the updated error
ooh, but I see your issue actually
It looks like you get the item meta of a fresh itemstack
Which, the item stack probably won't have
so what should i do?
fs do this
and then we can go from there
cause I could be right, could be wrong
could be this MyFirstPlugin.balance.toString()
π€·ββοΈ
yep looks like it's this
Can you send the MyFirstPlugin class?
im a beginer
ye π
meta.setDisplayName(MyFirstPlugin.balance.toString());
it allready is
what is?
Well you never initialized balance
looks like balance is uninitalized, no value is ever set.
if balance was an int it would initialize as 0 (instead of Integer)
ya, it's a bit odd
also static abuse very much
but, beginner code
what do you mean by intialize
public static Integer amount = 1;
you initialized amount here to 1
public static Integer balance;
balance is never initialized
oh
same with playerWhoBoughtTheShop
basically, you defined balance as an Integer type, but never initialized the value
what do you mean with global?
your balance variable in your main class
i can see that
but its fine rigth?
Β―_(γ)_/Β―
If youβre happy with any outcome then itβs fine π
so now i wanna change the meta of the item while your holding it
how do i do that>
ItemMeta meta = item.getItemMeta();
meta.whatever
meta.somethingelse
item.setItemMeta(meta);
the meta is already defined since you are doing item.getItemMeta()
whatever and somethingelse is just placeholders for whatever meta you want to modify
ItemStack itemStack = new ItemStack(Material.GOLD_BLOCK);
ItemMeta meta = itemStack.getItemMeta();
meta.setDisplayName(MyFirstPlugin.balance.toString());
meta.setLore(Arrays.asList("line 1", "line2"));
itemStack.setItemMeta(meta);
if (balance_int == 1) {
e.getPlayer().getInventory().addItem(itemStack);
balance_int = balance_int-1;
}
where should i put it? after the player got the item?
i really dont understand this could you just put it in for me?
i dont know where you even want this
uhg
idk?
so i want that the name of the item changes in your inveroty
and I firstly did it by clearing the item and then replacing it
but thats not clean cz you will see the item popping out and in to your invertory first of all
how do i do that>
p.getinventory.setitem(slot,itemstack);
The home of Spigot a high performance, no lag customized CraftBukkit Minecraft server API, and BungeeCord, the cloud server proxy.
ty
the uuid changes if you change your nickname ?
nope, that's the whole point of UUIDs
unless you use online-mode=false (and not have a proxy to take care of authentication) which β οΈ
are you using the java plugin
uhm is this params supposed to be the identifier?
I'm assuming it's because of that project block down there, what are you even doing there? 
I have never seen that being used like that, but anyways, the project would be considered differently, so the plugin you're applying above doesn't apply to the specific project
That is very cursed
yes
I think I forgot the java plugin lmao
For real though, what are you doing with that project block down there?
I dont know much of the kotlin DSL, but my mind thought that would make the module depend on that
probably wrong
Well if you want a module to depend on those you'd create the module and put that inside its own build.gradle
yeah ty
ty. Also, in the return, Does the ChatColor apply for everything after the text? For example, the name of the player?
does the BukkitScheduler run asynchronous tasks in order, or is it unpredictable?
i.e if I run task A async, then run task B async, can I expect A to run and finish before B is started? or should I make my own single thread executor instead
are they not unpredictable by their asynchronous nature
i guess i'm asking if it uses a single thread to execute tasks async or several
Yes
you can still have tasks run in order asynchronously, if they're all run on the same separate thread
you can look at implementation
but its probably using some threadpool
or just do
runAsync{
//sometask
//someothertaskthatneedstobecalledasync()
}
where thread pool is equivalent to your cpu cores number
could someone explain this to me please
val arrayType = object : TypeToken<ArrayList<T>>() {}.type
Does anybody have a maven repo with Paper Server version on it? (not the API, but the actual server with net.minecraft.server)
there is no publishable server jar
for internals you need to use paperweight-userdev gradle plugin, check this usage example plugin https://github.com/PaperMC/paperweight-test-plugin
Damn. The project owner is using maven so I can't use it
that creates a new anonymous subclass of TypeToken<T> to capture the generic type
it's working around type erasure
thanks
how can i delete two entries from a list where only two parameters match
What can I do about this?
[01:38:32] [Server thread/ERROR]: Could not load 'plugins/Core.jar' in folder 'plugins'
org.bukkit.plugin.InvalidPluginException: java.lang.UnsupportedClassVersionError: me/fiftyone/core/Main has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 55.0```
Tried doing what people said online about changing compiler compliance level but still nothing changes throws the same error
Change the java version of your server to at least the same version as the plugin or above.
Issue is when I change java version of my Linux server from 11 to 17 so it can run the "file version 61.0" my server no longer wants to start no logs or anything
I am running 1.16.5
Are you on shared hosting?
Don't think so I have a VPS server bought from OVH
I have Java 11 and Java 17 installed onto it
And I can change the versions using sudo update-alternatives --config java
If i change the version to 11 the server starts up perfectly fine but throws that error that I showed above
If I switch to 17 to try make that error go away my server doesnt start at all
Well I don't know the details on configuring java version on linux, but usually you only want to change the java version on the startup parameters of the minecraft server.
How do i change those?
Whats the parameters
You mean something like : "C:\Program Files\Java\jre1.8.0_311\bin\javaw.exe" -Xmx2048M -Xms2048M -jar forge-1.16.5-36.2.20.jar
pause
?
To start the minecraft server do you have to run something like java -jar server.jar or something.
Yeah that part
Change this "C:\Program Files\Java\jre1.8.0_311\bin\javaw.exe" to your java 17 path
And use java.exe, not javaw.exe
Could it be because the Java 17 isnt a jdk?
I have just noticed my Java 11 is like this /usr/lib/jvm/java-11-openjdk-amd64/bin/java
The Java 17 appears to be like this /usr/lib/jvm/java-17-oracle/bin/java
Says oracle
Well that depends on your installation folder.
I download my java 17 from this site https://adoptium.net/
Yes it's different on linux however, im not running my server locally unfortunately :/
Hmm ok 1.16.5 will not even run on java 17 so now i'm completely confused how to run this plugin now :/
yes it will lol
idk then it just won't let me start my server using Java 17 is there any other way to just make the plugin use the class version 55.0
55 is java 11 iirc
You could set the target of your project to 11
But for future reference, you have to run buildtools with the version of java that you are wanting
That will give you the server jar in the versino that you need
Ah my issue might be that I didnt use BuildTools 
or just use Paper lmao
Is running a minecraft server on linux vps are the same as running minecraft server on your computer, or am I mistaken?
For a vps you're usually ssh'ing in
Which means you don't have a gui besides the terminal
fundamentally it's the same
but yeah ^ managing it is very different on windows vs linux
you will also want to expose your server to the public when it's on your vps while you might not need to on your pc if you only want to run it locally
Ah okay, but to transfer file you usually use ftp client right?
And to start the minecraft server you'll run the command just like in Windows localhost
so I've created a discord bot inside of my plugin, and I need to get the plugin instance for my sql instance.
However, whenever I do the usual MainClass plugin;
blah blah
it returns null
DiscordLinkRoles plugin;
public DiscordLinkCommand(DiscordLinkRoles plugin) {
this.plugin = plugin;
}```
I need to access "plugin.sql"
that being public MySQL sql;
indeed
How are you initializing it
wdym. sorry if I seem dumb, its cuz I am but its also 5am
Where are you calling the constructor for DiscordLinkCommand
ohh
in my Bot.java class
bot = JDABuilder.createDefault(token)
.addEventListeners(new DiscordLinkCommand(plugin))
.build();```
the error says its occuring on this line
PreparedStatement ps = plugin.sql.getConnection().prepareStatement("SELECT name FROM linkedaccounts WHERE token=?");```
and so I checked if plugin was null with a simple if(plugin == null) {
print that its null }
and it said it was null
Show me where that plugin var gets initialized
@hoary citrus
getCommand("worldinfo").setExecutor(new WorldCommand(this));
like this bit i think he means
well thats what I showed, I also showed where plugin gets initialized in the event listener
No, that's a different plugin variable
You should me inside the DiscordLinkCommand class
I showed you the one inside the discordlinkcommand class
But where in the class that does this is plugin initialized
DiscordLinkRoles plugin;
public DiscordLinkCommand(DiscordLinkRoles plugin) {
this.plugin = plugin;
}```
and my bot class, whcih is the one with the code you just replied too,
initializes it like so
public Bot(DiscordLinkRoles plugin) {
Bot.plugin = plugin;
}```
public static JDA bot;
public static DiscordLinkRoles plugin;
public Bot(DiscordLinkRoles plugin) {
Bot.plugin = plugin;
}
public static void discordBot() throws LoginException {
bot = JDABuilder.createDefault(token)
.addEventListeners(new DiscordLinkCommand(plugin))
.build();
}```
And where is Bot.discordBot() called?
in my main class
Show it
ry {
Bot.discordBot();
} catch (LoginException e) {
e.printStackTrace();
}```
Show more
apparently I cant
public static MySQL sql;
public SQLGetter data;
@Override
public void onEnable() {
sql = new MySQL();
this.data = new SQLGetter(this);
try {
sql.connect();
} catch(ClassNotFoundException | SQLException e) {
Bukkit.getLogger().info("DB ISNT CONNECTED idiot!");
}
if(sql.isConnected()) {
Bukkit.getLogger().info("DB IS CONNECTED. GOOD JOB");
data.createTable();
}
getCommand("test").setExecutor(new TestCommand());
getCommand("linkaccount").setExecutor(new DiscordLink());
try {
Bot.discordBot();
} catch (LoginException e) {
e.printStackTrace();
}
}```
where do I need to pass it through?
So Bot.plugin never receives an instance of your plugin
I just made the sql instance in my main class static
and made a local variable in the event listener
fixes the issue :p
You could have just passed the plugin instance through Bot's static method too
Would have been better probably
Too much static going on
Is there anyway to mimic the effects of Bukkit.hidePlayer without removing their name from tabcomplete and tablist?
Invisibility potion is the only that I can think of xd.
Maybe some packets too.
Packets and a custom tab would work
Or Bukkit.hiseplayer and send the packet for tab to the player still
?learn-java
Online Courses:
Online courses are also great for learning java. Some websites that offer them are:
- Coursera - Free unless you want a certificate
- PluralSight - Great courses from what I've seen. Mostly Paid
- Udemy - Never used them myself but they seem to all or at least most be paid.
My first ever course was one from Coursera. - I can say it was pretty good at introducing me to the programming world as a whole not just java.
Oracle Docs:
Oracle docs can help a lot at learning and understanding java:
- Start with this,
- Breeze through this (skipping stuff that doesn't seem relevant like bitwise operators),
- Hit this.
They're the first three from this larger thing which you should definitely go through overall. But those three should be enough for slightly better understanding of what is happening here without feeling like a huge time sink.
That one is a small part of this larger site wherein "Essential Java Classes" and "Collections" also have good useful stuff
Other services:
Some other cool services that will help you learn java are:
As you can see there are plenty of good ways to learn as long as you're willing to invest the time. Have fun learning!
Dependency Injection
Dependency Injection is a way of providing objects with the objects they need ("dependencies"). This is usually done with a constructor, but can also be done for individual methods
Read more here: https://en.m.wikipedia.org/wiki/Dependency_injection
Dependency Injection in Java:
https://paste.helpch.at/yijawupoju.java
Dependency Injection in Kotlin:
https://paste.helpch.at/esogakutod.kt
Do schedulers get stopped when the owning plugin disables?
i believe so
cool
hey i can't test if my arguments is null or not
if(args[0] != null){
etc....
}
if my argument 0 is empty, my server return this error :
You need to check args length to see if it exists
so if (args[0] != null) would be if (args.length == 0)
How does someone create a new itemmeta for an item if getItemMeta() returns null
Can you explain what you are doing in code or put it in a paste?
Essentially, when the player picks up an item, i want to edit the itemmeta. However, trying to do so will spit out a nullpointer, halting the entire process of editting the itemmeta and giving the item to the player.
@graceful juniper So I presume you are using 1.18, and using the event EntityPickUpItemEvent (https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/entity/EntityPickupItemEvent.html#getItem()).
I can't really write up a example right now, so hopefully someone else can help but that event should work fine for getting a item's meta but you'd just need to make sure it's the correct item and entity.
ItemMeta meta = new ItemStack(Material.IRON_SWORD).getItemMeta()```
and then from there you can edit meta to whatever you want it to be, and then set the desired item's ItemMeta to the variable.
not sure if this is what you're looking for
Sorry I didnt specify, I am using 1.16.5 (im comfortable with this and most of my personal projects are on this version).
I am indeed using EntityPickUpItemEvent which allows me to grab the material and use my own extension of ItemStack.
Currently my personal extension of ItemStack is just exactly what ItemStack does but does it's own code to add information into the item via the ItemMeta.
This is what my extension does. It only does this.
private void init() {
ItemMeta meta = getItemMeta();
meta.setDisplayName(material.getRarity().getColour() + material.getName());
List<String> lore = new ArrayList<>();
lore.add(" ");
lore.add(material.getRarity().getColour() + material.getRarity().getName());
meta.setLore(lore);
meta.getPersistentDataContainer().set(material.getKey(), PersistentDataType.STRING, material.getKey().getKey());
meta.getPersistentDataContainer().set(material.getRarity().getKey(), PersistentDataType.STRING, material.getRarity().getKey().getKey());
setItemMeta(meta);
}
Removing this piece of code makes it work perfectly. It's just the ItemMeta which isn't correct
replace ItemMeta meta = getItemMeta(); with
if (this.hasItemMeta()) {
ItemMeta meta = getItemMeta();
} else {
ItemMeta meta = new ItemStack(Material.IRON_SWORD).getItemMeta();
}
this way you're checking if the item has meta, and if it doesn't then you're creating a new one
I will have a go, I will reply further if I have more issues. Thank you :D
no problem!
@inner jolt
Quick question
Would this essentially work as the same:
ItemMeta meta = hasItemMeta() ? getItemMeta() : new ItemStack(this.material.getMaterial()).getItemMeta();
Yeah pretty much
i don't think that a new itemstack with the material is guaranteed to have an itemmeta though
which is why i normally generate it using an iron sword
Are you able to use itemmeta from another type of material?
I've done it in the past without any issues, but I'm not sure if it's the best solution
Awesome! Good luck on your code π
You too!
how important is the single responsibility principle? for example I have a method deserialiseAndSet(value: String) which takes a serialised value for the object and then updates the value of the object to that value
if it's important, this is a guaranteed method provided by the interface that all objects of this type implement
there's no real application for just a deserialise() method outside of this, and it would also mean I'd need to parameterise my interface w generics since the return value would have to be different for each class
the design certainly won't scale very well
and it is a bad practice to be bundling that much logic together
However if it's not public code then you can take the risk of later suffering if you're feeling lazy
If you intend to publish / share the code you should absolutely be following the design principles more strictly
in what way?
I'm struggling to figure out a cleaner way of doing it
imo it feels better to couple the logic rather than parameterise the interface
especially when a lot of the time that parameter will just be *
you're coupling deserialization logic with object mapping, and whatever else the target class does - the better option imo would be a Deserializer interface that can generate a Map, then you do object mapping, and then all that logic is done somewhere away from the models in a service class or something
But I don't know the full context so that might be completely inapplicable
yeah well I think you should consider using a reflective inverted bimap implementation as your current system should declare an interface with a more clearly defined contract and you should really be splitting your 4 line method into 8 different classes for the Single responsibility Liskov principle which you learn about in Section 7 of Advanced Java course
True!
I'm confused what Map I would be generating?
To represent the deserialized output
Which can then be loaded into the object attributes
This tbh
It is quite hard to give proper architectural advice when all the information I have is 1 method though
I have classes that overload Mutable types like MutableLong, in order to set the value in a Redis DB whenever the underlying value of the mutable type is changed, e.g. I have a LongLogger.
these all implement the MyLogger interface which guarantees the deserialiseAndSet() method as well as serialise(). we're serialising to and from strings as that is what is stored in redis
I have an API that can update the value of any of these loggers by it's name. it accepts a serialised string. there's a map of them so I can just use the key to get the logger, and then since it's a map like Map<String, MyLogger> I can just do myLogger.deserialiseAndSet(value) without having to know what type of logger it is
the deserialised output is just of the type of the logger, e.g. Double for DoubleLogger
that's why I would have to parameterise the interface like MyLogger<T> so I can guarantee the method fun deserialise(value: String): T if I were to decouple the logic
Is it someone get memory leaks in IntelliJ IDEA 2021.3.2 when use suggestions with Material class (I have increasing ram several times)?
now it use 8Gb and it need even more (I have 55% more ram to use, but should not need all ram for it self).
I know that you can make package private classes by declaring it without public, is there any way to make smth like "project private"? Meaning it can be accessed by classes from the current project but not other projects.
not in java no
that's what java modules are for :)
AH YES
Oh how I HATE Gradle
this piece of shit seriously shouldn't be used at all
Never saw any software so bad with dependencies
What the heck is that formatting
IntelliJ is the one that colors it tho
unless it's giving compilation errors
then u prob need to check build.gradle(.kts) π

fucking lmao
read guides and learn how to use tooling
ask for help with tooling
complain and blame tooling for user errors
The build.gradle file is perfectly fine as I used that project like half a year ago and didn't change a thing
I never have those issues using maven, yet people always say Gradle is better
I really don't care. The project is dead anyway
Apparently you do
yeah it doesn't look like you don't care lol
I just wanted to share my hate for Intelij + Gradle acting horrible
gradle works perfectly fine if you know what you're doing
like, y'know, how everything is
@EventHandler
public void onInventoryClick(InventoryClickEvent e) {
if (e.getView().getTitle().equals(ChatColor.AQUA + "Auction House")) e.setCancelled(true);
}
@EventHandler
public void onInventoryDrag(InventoryDragEvent e) {
if (e.getView().getTitle().equals(ChatColor.AQUA + "Auction House")) e.setCancelled(true);
}
The player is able to use "F" in order to move the item from the inventory into their offhand. The item is duplicated, with one copy going into the Player's offhand and theo ther staying in the inventory. Is there a way to fix this?
If the player is in creative that is an issue, MC doesn't validate the inventory in creative, if they are in survival or adventure then the item is a ghost item and disappears after
And also, comparing inventory titles is not a good idea to verify if the inventory is the correct one
Ah alright, thank you
i've only been testing it in creative
What do you suggest for inventory verification?
Either comparing inventories directly or using a custom InventoryHolder
Got it, thank you
from my understanding, the only broken part is the integration for groovy gradle, which sucks - but kts exist π
do you learn all of this with practice or do you just read through the docs when you have time
Experience and practice
Is there any way to get an item name like potion item names? Say like Potion of Swiftness etc.
Because I am trying to read potions from a file and don't know how I would set the name
Ikr
Paste Services
When asking for help with a config/menu/code issue please use our paste bin:
(we prefer it over pastebin.com)
β’ HelpChat Paste - How To Use
ItemMeta#setDisplayname("Β§fPotion of Swiftness")

I belive thats client side
Iirc you can get it from the server, paper exposes it I think, spigot doesn't
d;paper ItemMeta#getLocalizedName
@Deprecated @NotNull
@NotNull String getLocalizedName()```
Gets the localized display name that is set.
Plugins should check that hasLocalizedName() returns true before calling this method.
Use displayName() and cast it to a TranslatableComponent. No longer used by the client.
the localized name that is set
@NotNull
public Component displayName()```
Get the formatted display name of the ItemStack.
display name of the ItemStack
ItemStack#displayName and ItemMeta#displayName return different components⦠whoever thought it was a good idea to name them the same thing needs to reevaluate their choices 
How come lol
ItemMeta is basically the item's NBT, so that one returns the display.Name NBT path
stoopid who did that
ItemStack#displayName returns what the game uses for when like e.g. you kill someone with a renamed item, it puts it in [] (actually it puts the NBT display name as argument for a translation entry, that renders to []) and adds the item hover event
The naming? Yes. The methods themselves? Not really
who needs the ItemStack#displayName method?
I've used it one time so there definitely is use for it
and that's the most useful alternative to "chat item" things like [i] or whatever
ah
it's quite niche still
Lol
"lol"?π€¨
hello to everyone who needs a developer of servers and assemblies
uncool status dude
My IDE is telling me this new Random().nextDouble(someDouble); is not valid. Why?
The method nextDouble() in the type Random is not applicable for the arguments (double)
d;jdk Random#nextDouble
default double nextDouble()```
Returns a pseudorandom double value between zero (inclusive) and one (exclusive).
a pseudorandom double value between zero (inclusive) and one (exclusive)
I find this tho double java.util.random.RandomGenerator.nextDouble(double bound). The description is: Returns a pseudorandomly chosen double value between zero(inclusive) and the specified bound (exclusive).
When I inspect it
I meant that
I changed it
Sorry, did it wrong the first time
That is the reason I am confused. There is a function that takes in a double as a bound
You won't be able to upload images here directly to avoid spam, so please use https://imgur.com/upload to upload images/screenshots.
You can also use a screenshot service like gyazo or jinx and post those links here.
Here: https://imgur.com/a/dBsJKFe. I can't screenshot what the error says when I hover over the .nextDouble() but it tells me this The method nextDouble() in the type Random is not applicable for the arguments (double)
If it wasn't clear, this.odds is a double
how are you trying to compile this? maven/gradle or what?



