javascriptminecraftminecraft-forge

KubeJS container item insertion


I have a rather simple problem:
Given the x, y and z coordinates of a barrel/chest, in a PlayerChatDecorateEventJS, I want to insert an ItemStack into it.

I have read through the generated docs for both KubeJS and Forge but couldn't find any way to access a BlockEntity's inventory. Sadly, neither mod has detailed docs, so they weren't all that helpful.

My other approach was doing this via a command ran as the player:
(book is the ItemStack, player is just a Player obtained from the event, the copyx/y/z variables are integers.)

player.runCommand(`execute in minecraft:overworld run item replace block ${copyx} ${copyy} ${copyz} container.0 with ${book.getId()}${book.getNbt()}`);

When logging this command with the variables filled out I can run it from the console or as a player without problems. Weirdly enough, when I try to run it with the player.runCommand, I get the error message:
Target position ... is not a container.

I mean, it obviously is since the command works perfectly when run through the client, so what am I doing wrong? If you find an alternative solution, or find a way to fix the first attempt, to achieve this I'll also take that but I'd still like to know why this doesn't work.

If it's relevant, I'm on Forge 47.3.0 for Minecraft 1.20.1 on Java 17.
KubeJS is version 2001.6.5-build.16+forge.


Solution

  • So I, of course, solved it a few hours after posting the issue here by just scheduling the command to execute later.

    player.getServer().scheduleInTicks(5, () => {
            player.runCommand(`execute in minecraft:overworld run item replace block ${copyx} ${copyy} ${copyz} container.0 with ${book.getId()}${book.getNbt()}`);
        })
    

    My educated guess on why this is happening:
    I assume you can only interact with the world in the tick event, and not in any other event. So, by scheduling it, it gets executed in a later tick event, and thus works.