'Why this code can't execute command in Minecraft?

Environment: Minecraft 1.16.5, Fabric 0.11.6

I write these code to try to execute command in Minecraft.

@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
    if (entity instanceof final PlayerEntity player) {
        if (player.getEquippedStack(EquipmentSlot.CHEST) == stack) {
            CommandDispatcher<PlayerEntity> cDispatcher = new CommandDispatcher<PlayerEntity>();
            final String command = "/time set 0";
            try {
                cDispatcher.execute(command, player);
            } catch (CommandSyntaxException e) {
                e.printStackTrace();
            }
        }
    }
}

But Minecraft throw these errors:

[main/INFO] (Minecraft) [STDERR]: com.mojang.brigadier.exceptions.CommandSyntaxException: Unknown or incomplete command, see below for error at position 0: <--[HERE]
[Server thread/INFO] (Minecraft) [STDERR]: com.mojang.brigadier.exceptions.CommandSyntaxException: Unknown or incomplete command, see below for error at position 0: <--[HERE]

I have try a lot of commands but it only give these same errors. So how to execute commands in game?



Solution 1:[1]

Such as the error said Unknown or incomplete command, see below for error at position 0: The issue is on the first char of your config.

It's because you're telling "I want to run a command", so you don't have to use the /.

Also, such as you can config it (even if everyone keep /), it can create issue. That's why you don't have to enter it here ...

Solution 2:[2]

Ok i finally know how to send command correctly.

//"source" is ServerCommandSource
String command="time set 0";
source.getMinecraftServer().getCommandManager().execute(source.getMinecraftServer().getCommandSource(),command);
//Execute command with server permission level

Or use this to get Minecraft Server Instance, then execute command

// @Mixin(MinecraftServer.class)
public MinecraftServer getServer(){
  return (MinecraftServer) (Object) this;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elikill58
Solution 2 IAFEnvoy