Force player to close their inventory

I want to either close a players inventory with a/some command(s) or detect when they don´t have their inventory open. I already know some ways to do this but they are not easy to use or near perfect.

1. My first idea was to simply switch gamemode to spectator and then back to survival because i thought you didn't have an inventory in spectator mode but it didn't work at all and i was wrong.

2. By changing the players spawnpoint to their current location and then killing them, will close the inventory. You also need to set doImmediateRespawn and keepInventory to true. But not only that i also need to disable my death counter and the death system. For me it isnt a problem that their old respawn location will be changed. showDeathMessages should be false so the chat don´t get spammed.

3. Sense you can´t sprint/walk/jump when your inventory is open you can detect if the player does any of that and if it does you know their inventory is closed. This isnt perfect either because the player must move before it will detect. Exemple: scoreboard objectives add jump minecraft.custom:minecraft.jump

4. I also tried with nbt. When running this command /data get entity @s. You will see example isFurnaceGuiOpen or isSmokerGuiOpen. One of them is just isGuiOpen and sense there isnt a isInventoryGuiOpen i thought that was for the inventory but it wasn't. When putting this command on repeat execute if entity @a[nbt={isGuiOpen:1b}] run say hi nothing happens even if i have my inventory open or not :(

Is there any other way to do this? (Java 1.16.1)


Solution 1:

This was an answer from a reddit post 5 years ago...

/execute a /setblock replace at the player's head location to change air to a portal block there. Then one tick later, /setblock back to air. That way the player doesn't have to move at all.

The user who posted at the time didnt update to a more refined method, and I equally do not have access to minecraft at the moment to test to confirm.