How to separate my plugin into multiple classes - java

I use java and paper plugin. I made this myself, but it doesn't work well.
source code
package com;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
public class [[mainclassname]] extends JavaPlugin implements Listener {
public void onEnable() {
getLogger().warning("Server started.");
testing test = new testing(); // An error occurred that starts from here.
test.onEnable();
getLogger().info("Nice try!"); // check point
}
}
class testing extends JavaPlugin {
public void onEnable() {
getLogger().warning("Hello!");
}
}
build successful.
error : Error occurred while enabling [pluginname] (Is it up to date?)
java.lang.IllegalArgumentException: Plugin already initialized!

The PluginAlreadyInitialized error occours when the .jar file contains more than one subclass of JavaPlugin class.
From here.

Related

Java Discord Bot

I am currently creating a bot for Discord. So far, I have got the bot up, and have it "Online" in my server. I created a custom command named !yata that displays a motivational message after being input. Is there a reason as to why my bot will not pick up commands? When I type in !yata it does not run the command.
Buki.java
package Buki;
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
public class Buki {
public static JDA jda;
public static String prefix = "!";
//Main method
public static void main(String[] args) throws LoginException {
JDA jda = JDABuilder.createDefault("bot token").build();
jda.addEventListener(new Commands());
}
}
Commands.java
package Buki;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Commands extends ListenerAdapter {
public void onGuildMessageReceived(MessageReceivedEvent e) {
String[] message = e.getMessage().getContentRaw().split(" ");
if (message[0].equalsIgnoreCase("!yata")) {
e.getChannel().sendTyping().queue();
e.getChannel().sendMessage("The road of a ninja is long!").queue();
}
else {
}
}
}
First of all, your codes are so weird!
How could the event be called MessageReceivedEvent, meanwhile, the method called onGuildMessageReceivedEvent, JDA already renamed the methods! and second you didn't use the GatewayIntent.GUILD_MESSAGES, so basically, it going to be like this:
JDABuilder jda = JDABuilder.create(token, GatewayIntent.GUILD_MESSAGES);
and third, think is I see you using JDA, not JDABuilder which is wrong, I recommended you to check what version of JDA you use and use the last one!
public void onGuildMessageReceived(MessageReceivedEvent e)
needed to be changed to
public void onMessageReceivedEvent(MessageReceivedEvent e).
"Guild" was not required in this method's name.

Block place event isn't working Minecraft Plugin Java

I am trying to make a plugin and for some reason my onBlockPlace event does not work. Here is my code:
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
public class test implements Listener {
#EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
System.out.println("Test!");
player.sendMessage("Test");
}
}
Am I missing something? Please help.
It looks like you already have all the stuff necessary in the listener class. So in your plugin class (the class that extends JavaPlugin) you'll want to use this function. I'll explain the steps but it'll be a mess so you can understand what the code is doing.
Create a new instance of your listener using Listener listener = new test();
Get the server's plugin manager
PluginManager manager = getServer.getPluginManager();
Register the listener with the plugin manager manager.registerEvents(listener, this);

Welcome Listener Does Not Work(Java Discord JDA)

I'm trying to make my bot welcome someone whenever someone joins but I can't seem to get it to work. For example(this will appear in an embed by the way):
#Jason joined. You must construct additional pylons.
Can someone help me edit my code so it works please?
Here's my Main code:
import Events.*;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import javax.security.auth.login.LoginException;
public class Main {
public static void main(String[] args) throws LoginException {
JDABuilder jda = JDABuilder.createDefault("I imported key here");
jda.setActivity(Activity.watching("baldness"));
jda.addEventListeners(new Help());
jda.addEventListeners(new PingPong());
jda.addEventListeners(new Clear());
jda.addEventListeners(new Welcome());
jda.build();
}
}
and Here's my Welcome code:
package Events;
import java.util.Random;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class Welcome extends ListenerAdapter {
public class GuildMemberJoin extends ListenerAdapter {
String[] messages = {
"[member] joined. You must construct additional pylons.",
"Never gonna give [member] up. Never let [member] down!",
"Hey! Listen! [member] has joined!",
"Ha! [member] has joined! You activated my trap card!",
"We've been expecting you, [member].",
"It's dangerous to go alone, take [member]!",
"Swoooosh. [member] just landed.",
"Brace yourselves. [member] just joined the server.",
"A wild [member] appeared."
};
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Random rand = new Random();
int number = rand.nextInt(messages.length);
EmbedBuilder join = new EmbedBuilder();
join.setColor(0x66d8ff);
join.setDescription(messages[number].replace("[member]", event.getMember().getAsMention()));
event.getGuild().getDefaultChannel().sendMessage(join.build()).queue();
}
}
}
The documentation fo GuildMemberJoinEvent clearly states:
Requirements
This event requires the GUILD_MEMBERS intent to be enabled.
createDefault(String) and createLight(String) disable this by default!
So you must enable the intent. Read more in the wiki guide Gateway Intents and Member Cache Policy
Additionally, you have a nested class for no reason which means you register the enclosing class as a listener but not the nested class that actually implements it.
Better:
public class Welcome extends ListenerAdapter {
#Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
...
}
}

/me in minecraft isnt disabled by the plugin I wrote

So in my server /me is an enabled command. I wanted to disable this because I don't want people to be able to do this.
I'm learning java, so I decided to code something that disabled /me myself.
So I wrote the following code:
package com.ste999.disableme;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class Main extends JavaPlugin implements Listener
#Override
public void onEnable() {
getLogger().info("disable me enabled");
PluginManager pm = this.getServer().getPluginManager();
pm.registerEvents(this, (this));
}
#Override
public void onDisable() {
getLogger().info("disable me disabled");
}
#EventHandler
public void OnMe(AsyncPlayerChatEvent event)
{
Player p = event.getPlayer();
if(!p.hasPermission("ste999.me")) {
if (event.getMessage().startsWith("/me")) {
event.setCancelled(true);
p.sendMessage("§4Dont me me!");
}
}
}
}
with the following plugin.yml file:
name: Disable_Me
main: com.ste999.disableme.Main
version: 1.0
load: startup
description: this is should disable me
commands:
Now if someone without op would run /me hello it shouldn't output to the chat and the user should get a message like Dont me me!
But it doesn't. the user is still able to do /me hello without op and the code should prevent that
As I'm fairly new to java this error is probably easy to find, and any help would be much appreciated.
The problem is that AsyncPlayerChatEvent only gets called when actually typing chat messages (not commands). For commands you have to use PlayerCommandPreprocessEvent as wonderfully explained by Mischa in the comments. Changing the event will make it work:
#EventHandler
public void disableMeCommand(PlayerCommandPreprocessEvent event) {
Player p = event.getPlayer();
if(!p.hasPermission("ste999.me")) {
if(event.getMessage().startsWith("/me")) {
event.setCancelled(true);
p.sendMessage("§4Dont me me!");
}
}
}
However, note that PlayerCommandPreprocessEvent should be avoided. Luckily there is another way to disable a command completely in a bukkit server. You should have a commands.yml file located in your server folder. Simply add the "me" alias and set it to null inside the file:
aliases:
me:
- null

About Adding import package in Groovy by customizing compilation process

I am writing a java file in which i am parsing the given groovy file using GroovyClassLoader to find the class in it. To do this, i have to import some class (like org.junit.Test) and add package and add static import also. Since i am using old groovy version 1.6, i can not use compilation customizers as these classes not available in this version. So to import custom classes, i had to write custom groovy class loader by extending groovy class loader class like below,
...
public static class DefaultImportClassLoader extends GroovyClassLoader {
public DefaultImportClassLoader(ClassLoader cl){
super(cl);
}
public CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource codeSource) {
CompilationUnit cu = super.createCompilationUnit(config, codeSource);
cu.addPhaseOperation(new SourceUnitOperation() {
public void call(SourceUnit source) throws CompilationFailedException {
//source.getAST().addImport("Test",ClassHelper.make("org.junit.Test")); //working
source.getAST().addImportPackage("org.junit.");
}}, Phases.CONVERSION);
return cu;
}
}
here add import package is not working. Would any one give right suggestion way of using addImportPackage().
I've tested your code and works perfectly for me. (with groovy-all-1.6.9.jar) (edit: groovy-all-1.6.0.jar works fine too)
How do you use your class DefaultImportClassLoader?
I've done:
public static void main(String[] args) throws InstantiationException, IllegalAccessException{
GroovyClassLoader loader = new DefaultImportClassLoader(new GroovyClassLoader());
Class groovyClass = loader.parseClass(DefaultImportClassLoader.class.getClassLoader().getResourceAsStream("so_22729226/test.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
groovyObject.invokeMethod("run", null);
}
With this Groovy class:
class so_22729226_Test {
def run(){
print Test.class
}
}
And I get the expected output: interface org.junit.Test
If I use the standard loader I get:
Caused by: groovy.lang.MissingPropertyException: No such property: Test for class: so_22729226_Test
Which is the expected behaviour too.

Categories