Search in sources :

Example 6 with CommandManager

use of com.velocitypowered.api.command.CommandManager in project Plan by plan-player-analytics.

the class PlanVelocity method registerCommand.

@Override
public void registerCommand(Subcommand command) {
    if (command == null) {
        logger.warn("Attempted to register a null command!");
        return;
    }
    CommandManager commandManager = proxy.getCommandManager();
    commandManager.register(commandManager.metaBuilder(command.getPrimaryAlias()).aliases(command.getAliases().toArray(new String[0])).build(), new VelocityCommand(runnableFactory, system.getErrorLogger(), command));
}
Also used : CommandManager(com.velocitypowered.api.command.CommandManager) VelocityCommand(com.djrapitops.plan.commands.use.VelocityCommand)

Example 7 with CommandManager

use of com.velocitypowered.api.command.CommandManager in project InteractiveChat by LOOHP.

the class CommandsVelocity method createBrigadierCommand.

public static void createBrigadierCommand() {
    LiteralCommandNode<CommandSource> backendinfoNode = LiteralArgumentBuilder.<CommandSource>literal("backendinfo").requires(sender -> {
        return sender.hasPermission("interactivechat.backendinfo");
    }).executes(command -> {
        try {
            CommandSource sender = command.getSource();
            if (InteractiveChatVelocity.hasPermission(sender, "interactivechat.backendinfo").get()) {
                InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.AQUA + "Proxy -> InteractiveChat: " + InteractiveChatVelocity.plugin.getDescription().getVersion() + " (PM Protocol: " + Registry.PLUGIN_MESSAGING_PROTOCOL_VERSION + ")"));
                InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.AQUA + "Expected latency: " + InteractiveChatVelocity.delay + " ms"));
                InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.AQUA + "Backends under this proxy:"));
                InteractiveChatVelocity.plugin.getServer().getAllServers().stream().sorted(Comparator.comparing(each -> each.getServerInfo().getName())).forEach(server -> {
                    String name = server.getServerInfo().getName();
                    BackendInteractiveChatData data = InteractiveChatVelocity.serverInteractiveChatInfo.get(name);
                    if (data == null) {
                        InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.RED + name + " -> Attempting to retrieve data from backend..."));
                    } else {
                        String minecraftVersion = data.getExactMinecraftVersion();
                        if (data.isOnline()) {
                            if (!data.hasInteractiveChat()) {
                                InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.YELLOW + name + " -> InteractiveChat: NOT INSTALLED (PM Protocol: -1) | Minecraft: " + minecraftVersion + " | Ping: " + (data.getPing() < 0 ? "N/A" : (data.getPing() + " ms"))));
                            } else {
                                InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.GREEN + name + " -> InteractiveChat: " + data.getVersion() + " (PM Protocol: " + data.getProtocolVersion() + ") | Minecraft: " + minecraftVersion + " | Ping: " + (data.getPing() < 0 ? "N/A" : (data.getPing() + " ms"))));
                            }
                        } else {
                            InteractiveChatVelocity.sendMessage(sender, Component.text(TextColor.RED + name + " -> Status: OFFLINE"));
                        }
                    }
                });
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return 1;
    }).build();
    LiteralCommandNode<CommandSource> rootNode = LiteralArgumentBuilder.<CommandSource>literal("interactivechatproxy").then(backendinfoNode).executes(command -> {
        defaultMessage(command.getSource());
        return 1;
    }).build();
    LiteralCommandNode<CommandSource> aliasNode1 = LiteralArgumentBuilder.<CommandSource>literal("icp").then(backendinfoNode).executes(command -> {
        defaultMessage(command.getSource());
        return 1;
    }).build();
    BrigadierCommand command = new BrigadierCommand(rootNode);
    BrigadierCommand alias1 = new BrigadierCommand(aliasNode1);
    CommandManager commandManager = InteractiveChatVelocity.plugin.getServer().getCommandManager();
    commandManager.register(command);
    commandManager.register(alias1);
}
Also used : ExecutionException(java.util.concurrent.ExecutionException) TextComponent(net.kyori.adventure.text.TextComponent) LiteralCommandNode(com.mojang.brigadier.tree.LiteralCommandNode) CommandManager(com.velocitypowered.api.command.CommandManager) Component(net.kyori.adventure.text.Component) BackendInteractiveChatData(com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData) Registry(com.loohp.interactivechat.registry.Registry) BrigadierCommand(com.velocitypowered.api.command.BrigadierCommand) ClickEvent(net.kyori.adventure.text.event.ClickEvent) CommandSource(com.velocitypowered.api.command.CommandSource) Comparator(java.util.Comparator) LiteralArgumentBuilder(com.mojang.brigadier.builder.LiteralArgumentBuilder) CommandManager(com.velocitypowered.api.command.CommandManager) BackendInteractiveChatData(com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData) CommandSource(com.velocitypowered.api.command.CommandSource) BrigadierCommand(com.velocitypowered.api.command.BrigadierCommand)

Example 8 with CommandManager

use of com.velocitypowered.api.command.CommandManager in project MiraiMC by DreamVoid.

the class VelocityPlugin method onProxyInitialization.

@Subscribe
public void onProxyInitialization(ProxyInitializeEvent event) {
    // load 阶段2
    try {
        new VelocityConfig(this).loadConfig();
        if (Config.Gen_MiraiCoreVersion.equalsIgnoreCase("latest")) {
            MiraiLoader.loadMiraiCore();
        } else {
            MiraiLoader.loadMiraiCore(Config.Gen_MiraiCoreVersion);
        }
        MiraiEvent = new MiraiEvent(this);
    } catch (Exception e) {
        getLogger().warn("An error occurred while loading plugin.");
        e.printStackTrace();
    }
    // enable
    getLogger().info("Mirai working dir: " + Config.Gen_MiraiWorkingDir);
    if (Config.Gen_AddProperties_MiraiNoDesktop)
        System.setProperty("mirai.no-desktop", "MiraiMC");
    if (Config.Gen_AddProperties_MiraiSliderCaptchaSupported)
        System.setProperty("mirai.slider.captcha.supported", "MiraiMC");
    getLogger().info("Starting Mirai-Events listener.");
    MiraiEvent.startListenEvent();
    // getLogger().info("Loading auto-login file.");
    // MiraiAutoLogin.loadFile();
    // MiraiAutoLogin.doStartUpAutoLogin(); // 服务器启动完成后执行自动登录机器人
    getLogger().info("Registering commands.");
    CommandManager manager = server.getCommandManager();
    CommandMeta mirai = manager.metaBuilder("mirai").build();
    CommandMeta miraimc = manager.metaBuilder("miraimc").build();
    CommandMeta miraiverify = manager.metaBuilder("miraiverify").build();
    manager.register(mirai, new MiraiCommand(this));
    manager.register(miraimc, new MiraiMcCommand(this));
    manager.register(miraiverify, new MiraiVerifyCommand());
    if (Config.Bot_LogEvents) {
        getLogger().info("Registering events.");
        server.getEventManager().register(this, new Events());
    }
    switch(Config.DB_Type.toLowerCase()) {
        case "sqlite":
        default:
            {
                getLogger().info("Initializing SQLite database.");
                try {
                    Utils.initializeSQLite();
                } catch (SQLException | ClassNotFoundException ex) {
                    getLogger().warn("Failed to initialize SQLite database, reason: " + ex);
                }
                break;
            }
        case "mysql":
            {
                getLogger().info("Initializing MySQL database.");
                Utils.initializeMySQL();
                break;
            }
    }
    // bStats统计
    if (Config.Gen_AllowBStats) {
        getLogger().info("Initializing bStats metrics.");
        int pluginId = 13887;
        metricsFactory.make(this, pluginId);
    }
    // 安全警告
    if (!(Config.Gen_DisableSafeWarningMessage)) {
        getLogger().warn("确保您正在使用开源的MiraiMC插件,未知来源的插件可能会盗取您的账号!");
        getLogger().warn("请始终从Github或作者指定的其他途径下载插件: https://github.com/DreamVoid/MiraiMC");
    }
    pluginContainer = server.getPluginManager().getPlugin("miraimc").orElse(null);
    getLogger().info("All tasks done. Welcome to use MiraiMC!");
}
Also used : CommandManager(com.velocitypowered.api.command.CommandManager) MiraiCommand(me.dreamvoid.miraimc.velocity.commands.MiraiCommand) MiraiMcCommand(me.dreamvoid.miraimc.velocity.commands.MiraiMcCommand) MiraiVerifyCommand(me.dreamvoid.miraimc.velocity.commands.MiraiVerifyCommand) CommandMeta(com.velocitypowered.api.command.CommandMeta) SQLException(java.sql.SQLException) Subscribe(com.velocitypowered.api.event.Subscribe)

Example 9 with CommandManager

use of com.velocitypowered.api.command.CommandManager in project GrandModeration by Ciph3r-Zer0.

the class Model method register.

public void register() {
    if (isEnabled()) {
        proxyServer.getEventManager().register(GrandModeration.getInst(), this);
        CommandManager manager = proxyServer.getCommandManager();
        if (getCommandName() != null) {
            if (getAliases() == null) {
                CommandMeta meta = manager.metaBuilder(getCommandName()).build();
                manager.register(meta, this);
            } else {
                CommandMeta meta = manager.metaBuilder(getCommandName()).aliases(getAliases()).build();
                manager.register(meta, this);
            }
        }
    }
}
Also used : CommandManager(com.velocitypowered.api.command.CommandManager) CommandMeta(com.velocitypowered.api.command.CommandMeta)

Example 10 with CommandManager

use of com.velocitypowered.api.command.CommandManager in project LimboAuth by Elytrium.

the class LimboAuth method reload.

@SuppressWarnings("SwitchStatementWithTooFewBranches")
public void reload() throws Exception {
    Settings.IMP.reload(new File(this.dataDirectory.toFile().getAbsoluteFile(), "config.yml"));
    if (this.floodgateApi == null && !Settings.IMP.MAIN.FLOODGATE_NEED_AUTH) {
        throw new IllegalStateException("If you don't need to auth floodgate players please install floodgate plugin.");
    }
    if (Settings.IMP.MAIN.CHECK_PASSWORD_STRENGTH) {
        this.unsafePasswords.clear();
        Path unsafePasswordsPath = Paths.get(this.dataDirectory.toFile().getAbsolutePath(), Settings.IMP.MAIN.UNSAFE_PASSWORDS_FILE);
        if (!unsafePasswordsPath.toFile().exists()) {
            Files.copy(Objects.requireNonNull(this.getClass().getResourceAsStream("/unsafe_passwords.txt")), unsafePasswordsPath);
        }
        this.unsafePasswords.addAll(Files.lines(unsafePasswordsPath).collect(Collectors.toSet()));
    }
    this.cachedAuthChecks.clear();
    Settings.DATABASE dbConfig = Settings.IMP.DATABASE;
    // requireNonNull prevents the shade plugin from excluding the drivers in minimized jar.
    switch(dbConfig.STORAGE_TYPE.toLowerCase(Locale.ROOT)) {
        case "h2":
            {
                Objects.requireNonNull(org.h2.Driver.class);
                Objects.requireNonNull(org.h2.engine.Engine.class);
                this.connectionSource = new JdbcPooledConnectionSource("jdbc:h2:" + this.dataDirectory.toFile().getAbsoluteFile() + "/limboauth");
                break;
            }
        case "mysql":
            {
                Objects.requireNonNull(com.mysql.cj.jdbc.Driver.class);
                Objects.requireNonNull(com.mysql.cj.conf.url.SingleConnectionUrl.class);
                this.connectionSource = new JdbcPooledConnectionSource("jdbc:mysql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD);
                break;
            }
        case "postgresql":
            {
                Objects.requireNonNull(org.postgresql.Driver.class);
                this.connectionSource = new JdbcPooledConnectionSource("jdbc:postgresql://" + dbConfig.HOSTNAME + "/" + dbConfig.DATABASE + dbConfig.CONNECTION_PARAMETERS, dbConfig.USER, dbConfig.PASSWORD);
                break;
            }
        default:
            {
                this.getLogger().error("WRONG DATABASE TYPE.");
                this.server.shutdown();
                return;
            }
    }
    TableUtils.createTableIfNotExists(this.connectionSource, RegisteredPlayer.class);
    this.playerDao = DaoManager.createDao(this.connectionSource, RegisteredPlayer.class);
    this.nicknameValidationPattern = Pattern.compile(Settings.IMP.MAIN.ALLOWED_NICKNAME_REGEX);
    this.migrateDb(this.playerDao);
    CommandManager manager = this.server.getCommandManager();
    manager.unregister("unregister");
    manager.unregister("premium");
    manager.unregister("forceunregister");
    manager.unregister("changepassword");
    manager.unregister("forcechangepassword");
    manager.unregister("destroysession");
    manager.unregister("2fa");
    manager.unregister("limboauth");
    manager.register("unregister", new UnregisterCommand(this, this.playerDao), "unreg");
    manager.register("premium", new PremiumCommand(this, this.playerDao));
    manager.register("forceunregister", new ForceUnregisterCommand(this, this.server, this.playerDao), "forceunreg");
    manager.register("changepassword", new ChangePasswordCommand(this.playerDao), "changepass");
    manager.register("forcechangepassword", new ForceChangePasswordCommand(this.server, this.playerDao), "forcechangepass");
    manager.register("destroysession", new DestroySessionCommand(this));
    if (Settings.IMP.MAIN.ENABLE_TOTP) {
        manager.register("2fa", new TotpCommand(this.playerDao), "totp");
    }
    manager.register("limboauth", new LimboAuthCommand(this), "la", "auth", "lauth");
    Settings.MAIN.AUTH_COORDS authCoords = Settings.IMP.MAIN.AUTH_COORDS;
    VirtualWorld authWorld = this.factory.createVirtualWorld(Dimension.valueOf(Settings.IMP.MAIN.DIMENSION), authCoords.X, authCoords.Y, authCoords.Z, (float) authCoords.YAW, (float) authCoords.PITCH);
    if (Settings.IMP.MAIN.LOAD_WORLD) {
        try {
            Path path = this.dataDirectory.resolve(Settings.IMP.MAIN.WORLD_FILE_PATH);
            WorldFile file;
            switch(Settings.IMP.MAIN.WORLD_FILE_TYPE) {
                case "schematic":
                    {
                        file = new SchematicFile(path);
                        break;
                    }
                default:
                    {
                        this.getLogger().error("Incorrect world file type.");
                        this.server.shutdown();
                        return;
                    }
            }
            Settings.MAIN.WORLD_COORDS coords = Settings.IMP.MAIN.WORLD_COORDS;
            file.toWorld(this.factory, authWorld, coords.X, coords.Y, coords.Z);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    this.authServer = this.factory.createLimbo(authWorld).setName("LimboAuth").registerCommand(new AuthCommandMeta(this, this.filterCommands(Settings.IMP.MAIN.REGISTER_COMMAND)), new AuthCommand()).registerCommand(new AuthCommandMeta(this, this.filterCommands(Settings.IMP.MAIN.LOGIN_COMMAND)), new AuthCommand()).registerCommand(new AuthCommandMeta(this, this.filterCommands(Settings.IMP.MAIN.TOTP_COMMAND)), new AuthCommand());
    this.server.getEventManager().unregisterListeners(this);
    this.server.getEventManager().register(this, new AuthListener(this, this.playerDao, this.floodgateApi));
    Executors.newScheduledThreadPool(1, task -> new Thread(task, "purge-cache")).scheduleAtFixedRate(() -> this.checkCache(this.cachedAuthChecks, Settings.IMP.MAIN.PURGE_CACHE_MILLIS), Settings.IMP.MAIN.PURGE_CACHE_MILLIS, Settings.IMP.MAIN.PURGE_CACHE_MILLIS, TimeUnit.MILLISECONDS);
    this.server.getEventManager().fireAndForget(new AuthPluginReloadEvent());
}
Also used : WorldFile(net.elytrium.limboapi.api.file.WorldFile) DestroySessionCommand(net.elytrium.limboauth.command.DestroySessionCommand) SimpleCommand(com.velocitypowered.api.command.SimpleCommand) Inject(com.google.inject.Inject) JdbcPooledConnectionSource(com.j256.ormlite.jdbc.JdbcPooledConnectionSource) PreEvent(net.elytrium.limboauth.event.PreEvent) TaskEvent(net.elytrium.limboauth.event.TaskEvent) SimplePie(org.bstats.charts.SimplePie) Dependency(com.velocitypowered.api.plugin.Dependency) FloodgateApiHolder(net.elytrium.limboauth.floodgate.FloodgateApiHolder) InetAddress(java.net.InetAddress) LimboAuthCommand(net.elytrium.limboauth.command.LimboAuthCommand) UpdatesChecker(net.elytrium.limboauth.utils.UpdatesChecker) FieldType(com.j256.ormlite.field.FieldType) Locale(java.util.Locale) Player(com.velocitypowered.api.proxy.Player) Map(java.util.Map) Limbo(net.elytrium.limboapi.api.Limbo) ProxyInitializeEvent(com.velocitypowered.api.event.proxy.ProxyInitializeEvent) TableUtils(com.j256.ormlite.table.TableUtils) PluginContainer(com.velocitypowered.api.plugin.PluginContainer) DaoManager(com.j256.ormlite.dao.DaoManager) URI(java.net.URI) Path(java.nio.file.Path) HttpResponse(java.net.http.HttpResponse) CommandMeta(com.velocitypowered.api.command.CommandMeta) Plugin(com.velocitypowered.api.plugin.Plugin) AuthListener(net.elytrium.limboauth.listener.AuthListener) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Dao(com.j256.ormlite.dao.Dao) PremiumCommand(net.elytrium.limboauth.command.PremiumCommand) SingleLineChart(org.bstats.charts.SingleLineChart) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) PreAuthorizationEvent(net.elytrium.limboauth.event.PreAuthorizationEvent) List(java.util.List) LimboFactory(net.elytrium.limboapi.api.LimboFactory) QueryBuilder(com.j256.ormlite.stmt.QueryBuilder) Subscribe(com.velocitypowered.api.event.Subscribe) ForceChangePasswordCommand(net.elytrium.limboauth.command.ForceChangePasswordCommand) RegisteredPlayer(net.elytrium.limboauth.model.RegisteredPlayer) Pattern(java.util.regex.Pattern) AuthSessionHandler(net.elytrium.limboauth.handler.AuthSessionHandler) HttpRequest(java.net.http.HttpRequest) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) SchematicFile(net.elytrium.limboapi.api.file.SchematicFile) AuthPluginReloadEvent(net.elytrium.limboauth.event.AuthPluginReloadEvent) SQLException(java.sql.SQLException) Title(net.kyori.adventure.title.Title) Metrics(org.bstats.velocity.Metrics) ProxyServer(com.velocitypowered.api.proxy.ProxyServer) HttpClient(java.net.http.HttpClient) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) Nullable(org.checkerframework.checker.nullness.qual.Nullable) Logger(org.slf4j.Logger) Files(java.nio.file.Files) Dimension(net.elytrium.limboapi.api.chunk.Dimension) VirtualWorld(net.elytrium.limboapi.api.chunk.VirtualWorld) IOException(java.io.IOException) UnregisterCommand(net.elytrium.limboauth.command.UnregisterCommand) File(java.io.File) DataDirectory(com.velocitypowered.api.plugin.annotation.DataDirectory) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) PreRegisterEvent(net.elytrium.limboauth.event.PreRegisterEvent) URLEncoder(java.net.URLEncoder) CommandManager(com.velocitypowered.api.command.CommandManager) Paths(java.nio.file.Paths) TotpCommand(net.elytrium.limboauth.command.TotpCommand) ChangePasswordCommand(net.elytrium.limboauth.command.ChangePasswordCommand) CommandNode(com.mojang.brigadier.tree.CommandNode) CommandSource(com.velocitypowered.api.command.CommandSource) ForceUnregisterCommand(net.elytrium.limboauth.command.ForceUnregisterCommand) Collections(java.util.Collections) VirtualWorld(net.elytrium.limboapi.api.chunk.VirtualWorld) DestroySessionCommand(net.elytrium.limboauth.command.DestroySessionCommand) UnregisterCommand(net.elytrium.limboauth.command.UnregisterCommand) ForceUnregisterCommand(net.elytrium.limboauth.command.ForceUnregisterCommand) ForceUnregisterCommand(net.elytrium.limboauth.command.ForceUnregisterCommand) SchematicFile(net.elytrium.limboapi.api.file.SchematicFile) AuthListener(net.elytrium.limboauth.listener.AuthListener) CommandManager(com.velocitypowered.api.command.CommandManager) PremiumCommand(net.elytrium.limboauth.command.PremiumCommand) WorldFile(net.elytrium.limboapi.api.file.WorldFile) LimboAuthCommand(net.elytrium.limboauth.command.LimboAuthCommand) Path(java.nio.file.Path) LimboAuthCommand(net.elytrium.limboauth.command.LimboAuthCommand) ForceChangePasswordCommand(net.elytrium.limboauth.command.ForceChangePasswordCommand) ChangePasswordCommand(net.elytrium.limboauth.command.ChangePasswordCommand) IOException(java.io.IOException) RegisteredPlayer(net.elytrium.limboauth.model.RegisteredPlayer) TotpCommand(net.elytrium.limboauth.command.TotpCommand) ForceChangePasswordCommand(net.elytrium.limboauth.command.ForceChangePasswordCommand) JdbcPooledConnectionSource(com.j256.ormlite.jdbc.JdbcPooledConnectionSource) WorldFile(net.elytrium.limboapi.api.file.WorldFile) SchematicFile(net.elytrium.limboapi.api.file.SchematicFile) File(java.io.File) AuthPluginReloadEvent(net.elytrium.limboauth.event.AuthPluginReloadEvent)

Aggregations

CommandManager (com.velocitypowered.api.command.CommandManager)11 Subscribe (com.velocitypowered.api.event.Subscribe)6 CommandMeta (com.velocitypowered.api.command.CommandMeta)5 IOException (java.io.IOException)3 Inject (com.google.inject.Inject)2 CommandSource (com.velocitypowered.api.command.CommandSource)2 ProxyInitializeEvent (com.velocitypowered.api.event.proxy.ProxyInitializeEvent)2 Dependency (com.velocitypowered.api.plugin.Dependency)2 Plugin (com.velocitypowered.api.plugin.Plugin)2 PluginContainer (com.velocitypowered.api.plugin.PluginContainer)2 DataDirectory (com.velocitypowered.api.plugin.annotation.DataDirectory)2 Player (com.velocitypowered.api.proxy.Player)2 ProxyServer (com.velocitypowered.api.proxy.ProxyServer)2 File (java.io.File)2 InetAddress (java.net.InetAddress)2 Path (java.nio.file.Path)2 SQLException (java.sql.SQLException)2 Map (java.util.Map)2 SimplePie (org.bstats.charts.SimplePie)2 Metrics (org.bstats.velocity.Metrics)2