Не работает команда

Baraban4ik

Разработчик
Пользователь
Сообщения
270
Решения
1
Я сделал команду а она не работает вызывает ошибки при использовании
Java:
package com.sp3ctr0.ecolobby.utils;

import lombok.experimental.UtilityClass;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.List;
import net.md_5.bungee.api.ChatColor;

@UtilityClass
public class Chat {

    public void message(CommandSender sender, Iterable<String> playerMessage, Iterable<String> consoleMessage) {
        if (sender instanceof Player) {
            playerMessage.forEach((string) -> sender.sendMessage(colorize(string)));
            return;
        }

        consoleMessage.forEach(sender::sendMessage);
    }

    public void message(CommandSender sender, String playerMessage, String consoleMessage) {
        sender.sendMessage(sender instanceof Player ? colorize(playerMessage) : consoleMessage);
    }

    public static String colorize(String string) {
        List<String> formatCodes = Arrays.asList("&k", "&l", "&m", "&n", "&o", "&r");

        for (String code : formatCodes) {
            string = string.replaceAll(code, ChatColor.getByChar(code.charAt(1)).toString());
        }

        return string;
    }
}

Java:
package com.sp3ctr0.ecolobby.commands;

import com.sp3ctr0.ecolobby.Ecolobby;
import com.sp3ctr0.ecolobby.configurations.Configurations;
import com.sp3ctr0.ecolobby.utils.Chat;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import java.util.Arrays;
import java.util.List;

public class EcoLobbyCommand implements CommandExecutor {

    private Configurations configurations;
    private Ecolobby plugin;

    private static final List<String> CONSOLE_INFO_MESSAGE = Arrays.asList
            (
                    "§7§m=-=-=-=-§a§lEco§f§lLobby§7§m-=-=-=-=",
                    "",
                    "   Version: §a{version}",
                    "   Author: §a{author}",
                    "",
                    "§7§m=-=-=-=-§a§lEco§f§lLobby§7§m-=-=-=-="
            );

    private static final String CONSOLE_PLUGIN_RELOADED_MESSAGE = "Plugin successfully reloaded!";

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (command.getName().equalsIgnoreCase("ecolobby")) {
            if (args[0].equalsIgnoreCase("reload")) {
                this.reload(sender);
            }
            if (args.length == 0) {
                this.sendInfo(sender);
            }
        }
        return true;
    }

    private void reload(CommandSender sender)
    {
        if (!sender.hasPermission("elobby.reload"))
        {
            sender.sendMessage(this.configurations.get("messages.yml").getString("no-permissions"));
            return;
        }

        this.plugin.reload();

        Chat.message(sender, this.configurations.get("messages.yml").getString("plugin-reloaded"), CONSOLE_PLUGIN_RELOADED_MESSAGE);
    }

    private void sendInfo(CommandSender sender)
    {
        if (!sender.hasPermission("elobby.help"))
        {
            sender.sendMessage(this.configurations.get("messages.yml").getString("no-permissions"));
            return;
        }

        Chat.message(sender, this.configurations.get("messages.yml").getStringList("info"), CONSOLE_INFO_MESSAGE);
    }
}
Java:
package com.sp3ctr0.ecolobby;

import com.sp3ctr0.ecolobby.commands.EcoLobbyCommand;
import com.sp3ctr0.ecolobby.configurations.Configurations;
import com.sp3ctr0.ecolobby.handler.SimpleEventHandler;
import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;

public class Ecolobby extends JavaPlugin {

    private Configurations configurations = new Configurations(this, "config.yml", "messages.yml");

    @Override
    public void onEnable() {
        System.out.println(ChatColor.GREEN + "EcoLobby plugin is enabled");
        this.configurations.loadConfigurations();
        getServer().getPluginCommand("ecolobby").setExecutor(new EcoLobbyCommand());

        getServer().getPluginManager().registerEvents(new SimpleEventHandler(), this);
    }

    @Override
    public void onDisable() {
        System.out.println(ChatColor.RED + "EcoLobby plugin is disabled");
        this.configurations = null;
    }

    public void reload() {
        this.configurations.reloadConfigurations();
    }
}

Java:
package com.sp3ctr0.ecolobby.configurations;

import java.io.File;
import java.io.IOException;
import java.util.*;

import com.google.common.collect.Lists;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;

public class Configurations
{
    private Map<String, Map.Entry<FileConfiguration, File>> configurations = new HashMap<> ();

    private List<String> configurationsNames;

    private Plugin plugin;

    public Configurations(Plugin plugin, String... configurationsNames)
    {
        this.plugin = plugin;

        this.configurationsNames = Lists.newArrayList(configurationsNames);

        this.loadConfigurations();
    }

    private File generateDefaultFile(String name)
    {
        File file = new File(this.plugin.getDataFolder(), name);

        if (!file.exists())
        {
            this.plugin.saveResource(name, false);
        }

        return file;
    }

    public void loadConfigurations()
    {
        for (String configurationName : this.configurationsNames)
        {
            if (this.configurations.containsKey(configurationName))
            {
                continue;
            }

            File configurationFile = this.generateDefaultFile(configurationName);

            FileConfiguration configuration = YamlConfiguration.loadConfiguration(configurationFile);

            this.configurations.put(configurationName, new AbstractMap.SimpleEntry<> (configuration, configurationFile));
        }
    }

    public void reloadConfigurations()
    {
        this.configurations.clear();

        this.loadConfigurations();
    }

    private Optional<Map.Entry<FileConfiguration, File>> getEntry(String configurationName)
    {
        return Optional.ofNullable(this.configurations.get(configurationName));
    }

    public FileConfiguration get(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getKey)
                .orElse(null);
    }

    private File getFile(String configurationName)
    {
        return this.getEntry(configurationName)
                .map(Map.Entry::getValue)
                .orElse(null);
    }

    public void save(String configurationName)
    {
        this.getEntry(configurationName).ifPresent((entry) ->
        {
            try {
                entry.getKey().save(entry.getValue());
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
Авто объединение сообщений:


Код:
[16:10:01 WARN]: Unexpected exception while parsing console command "ecolobby"
org.bukkit.command.CommandException: Unhandled exception executing command 'ecolobby' in plugin EcoLobby v1.0-SNAPSHOT
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:46) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:152) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchCommand(CraftServer.java:685) ~[patched_1.12.2.jar:git-Paper-1618]
        at org.bukkit.craftbukkit.v1_12_R1.CraftServer.dispatchServerCommand(CraftServer.java:648) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.aP(DedicatedServer.java:463) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:424) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:774) ~[patched_1.12.2.jar:git-Paper-1618]
        at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:666) ~[patched_1.12.2.jar:git-Paper-1618]
        at java.lang.Thread.run(Thread.java:834) [?:?]
Caused by: java.lang.ClassCastException: class com.destroystokyo.paper.console.TerminalConsoleCommandSender cannot be cast to class org.bukkit.entity.Player (com.destroystokyo.paper.console.TerminalConsoleCommandSender and org.bukkit.entity.Player are in unnamed module of loader 'app')
        at com.sp3ctr0.ecolobby.commands.EcoLobbyCommand.onCommand(EcoLobbyCommand.java:33) ~[?:?]
        at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) ~[patched_1.12.2.jar:git-Paper-1618]
        ... 8 more
 
Caused by: java.lang.ClassCastException: class com.destroystokyo.paper.console.TerminalConsoleCommandSender cannot be cast to class org.bukkit.entity.Player (com.destroystokyo.paper.console.TerminalConsoleCommandSender and org.bukkit.entity.Player are in unnamed module of loader 'app')
Ошибка кроется в описании

Смотришь, на какую строчку указывает ошибка:

Ошибка заключается в том, что ты используешь команду из консоли, но используешь методы как для игрока. Консоль к игроку приравнять невозможно, отсюда выскакивает это исключение.

offtop
Ну тогда ждать кодеров )
Я прошу не лезть в те темы, где вы не разбираетесь. Так только сильнее запутываете автора темы.
 
Ошибка кроется в описании

Смотришь, на какую строчку указывает ошибка:


Ошибка заключается в том, что ты используешь команду из консоли, но используешь методы как для игрока. Консоль к игроку приравнять невозможно, отсюда выскакивает это исключение.

offtop
Я прошу не лезть в те темы, где вы не разбираетесь. Так только сильнее запутываете автора темы.
Кароче просто зделать доступ к команде только игроку или изменить методы которые я использовал
Авто объединение сообщений:

Короче я перепишу код ну чтоб с консоли команда работала
offtop Это не знаешь у меня начала Intellij IDEA вылетать
Таже когда не работаю в ней

Авто объединение сообщений:

Так я немного не понимаю ошибка указывает на сторчки
33: this.plugin.reload();
21: this.reload(sender);
Я не понимаю как они связаны с игроком
Авто объединение сообщений:

Я же просто тут пытаюсь перезагрузить конфиги плагина
Авто объединение сообщений:

Ошибка кроется в описании

Смотришь, на какую строчку указывает ошибка:


Ошибка заключается в том, что ты используешь команду из консоли, но используешь методы как для игрока. Консоль к игроку приравнять невозможно, отсюда выскакивает это исключение.
Я не знаю как перезагрузка относиться к игроку
Авто объединение сообщений:

Я проверил эту команду будучи игроком и все равно тадже ошибка
Авто объединение сообщений:

Короче я починил проблема была в том что надо было конструктор добавить
 
Последнее редактирование:
Назад
Сверху Снизу