Minecraft – Test if player has specific item in specific hotbar slot [1.8]

minecraft-commandsminecraft-java-edition

How can I test for a player that has a wooden button in his 1st hotbar slot?
(no matter if selected or not).

I tried:

/testfor @a {Inventory:[{Slot:0,id:"minecraft:wooden_button"}]}

But the command block outputs:

[player name] did not match the required data structure

Best Answer

When accessing pre-existing NBT data, you have to specify it exactly as it's stored. This includes the name, value, and the datatype. The Slot tag is stored as a Byte, while you've declared it as an Integer. You can append the numerical value with a "b" to declare it as a Byte:

/testfor @a {Inventory:[{Slot:0b,id:"minecraft:wooden_button"}]}

To mention, while the command will output whether or any there is any player at all with a wooden button in that slot, it does not allow you to target that player afterwards.

You can instead assign a label based on the player's NBT data and then target them based on that label:

1.8:

Objective required.

/scoreboard objectives add HasItem dummy

Detection commands.

/scoreboard players set @a HasItem 0
/scoreboard players set @a HasItem 1 {Inventory:[{Slot:0b,id:"minecraft:wooden_button"}]}
/say @a[score_HasItem_min=1]

1.9:

No objective needed, only detection commands.

/scoreboard players tag @a[tag=HasItem] remove HasItem
/scoreboard players tag @a[tag=!HasItem] add HasItem {Inventory:[{Slot:0b,id:"minecraft:wooden_button"}]}
/say @a[tag=HasItem]