Solved Run commands as op

  • After careful consideration and due to limited usage, we’ve made the decision to discontinue the PaperMC forums. Moving forward, we recommend using Hangar for plugin uploads, and for all other community discussions and support, please join us on Discord.

Noy

New member
Jan 8, 2023
23
1
0
1
I've already googled. Use try ... finally to give op temporarily is a bad idea, and use the console sender will misperform the target selector (like @s).

If I use execute as Name run kill @s in console, it works well. But when it comes to our custom command, we can only use the following codes to select the targets
Code:
Bukkit.getServer().selectEntities(sender, args[i]);
but even if it executes as player, the command sender is still console (otherwise the permisson check will fail).

Is there any way to run a command as op? And how can I get the identity (not sender) in CommandExecutor.onCommand?

Thank you!
 
Solution
EDIT: Can be achieved in a more elegant way by using Brigadier command system

Solved by making a dummy sender:

Java:
public class CmdHelper {
    public static CommandSender asOpSender(Player player) {
        return new AsOpSender(player);
    }

    public static List<Entity> selectEntities(CommandSender sender, String selector) {
        if (sender instanceof AsOpSender op) {
            return op.selectEntities(selector);
        } else {
            return Bukkit.selectEntities(sender, selector);
        }
    }

    public static void performCommandAsOp(Player player, String command) {
        Bukkit.dispatchCommand(asOpSender(player), "execute as " + player.getName() + " at @s run " + command);
    }

    private static...

Noy

New member
Jan 8, 2023
23
1
0
1
EDIT: Can be achieved in a more elegant way by using Brigadier command system

Solved by making a dummy sender:

Java:
public class CmdHelper {
    public static CommandSender asOpSender(Player player) {
        return new AsOpSender(player);
    }

    public static List<Entity> selectEntities(CommandSender sender, String selector) {
        if (sender instanceof AsOpSender op) {
            return op.selectEntities(selector);
        } else {
            return Bukkit.selectEntities(sender, selector);
        }
    }

    public static void performCommandAsOp(Player player, String command) {
        Bukkit.dispatchCommand(asOpSender(player), "execute as " + player.getName() + " at @s run " + command);
    }

    private static class AsOpSender implements ConsoleCommandSender {
        private final Player player;
        private final PermissibleBase perm = new PermissibleBase(this);

        public AsOpSender(Player player) {
            this.player = player;
        }

        public List<Entity> selectEntities(@NotNull String selector) {
            return Bukkit.selectEntities(player, selector);
        }

        public boolean isOp() {
            return true;
        }

        // details omitted
    }
}
 
Last edited:
Solution