How to test for minimum amount of items in inventory and execute a command if true
I am using the AmazingKit plugin on my Minecraft server to make inventory kits for players. In a command block I have the following command:
/tellraw @p ["",{"text":"Iron","clickEvent":{"action":"run_command","value":"_____"}},{"text":" / "},{"text":"Gold","clickEvent":{"action":"run_command","value":"_____"}}]
Which prints the following result: Iron / Gold
.
When a player clicks on Iron, what command should I write where the empty space is _____ in order to check if the player has at least (>=) 20 iron ingots in his inventory and if he/she does, remove 20 iron ingots and execute /kit Basic
. If the player has less than 20 iron ingots in inventory, the command won't be executed. Instead, Insufficient amount of iron ingots will be printed out.
Same applies when a player clicks on "Gold".
I'm on 1.14 version
Solution 1:
Firstly, commands ran with run_command
in JSON run as if the person who clicks on it typed it into chat, that's why you need a /
at the beginning and it outputs it as a chat message otherwise and that also means that it runs with the same permissions level as the player. So you need to setup a trigger scoreboard:
/scoreboard objectives add ironTrigger trigger
/scoreboard players enable @a ironTrigger
And the corresponding part of the tellraw
command becomes:
{"text":"Iron","clickEvent":{"action":"run_command","value":"/trigger ironTrigger"}}
You can also use /trigger ironTrigger <number>
, in case you want to use that number for e.g. the number of iron ingots later.
To keep the trigger active all the time, you can put scoreboard players enable @a ironTrigger
and scoreboard players set @a ironTrigger 0
into a repeating command chain.
Then you need to check if the player has at least 20 iron ingots. Since you want to clear them anyway, you could just do /clear @p[scores={ironTrigger=1..}] iron_ingot 20
, but that would also clear for example 10 ingots if there are just 10. You only want to clear 20 or none, so you need to check how many items there are. Ironically, that is done with /clear
as well (needs /scoreboard objectives add ironIngots dummy
before first use):
/execute as @a[scores={ironTrigger=1..}] store result score @s ironIngots run clear @s iron_ingot 0
This removes 0 iron ingots from your inventory, which might seem useless, but the command returns as its result
value the number of iron ingots in your inventory. This can then be stored in a scoreboard with /execute store result
.
And then, finally, actually clear the items if there are enough:
/clear @a[scores={ironIngots=20..}] iron_ingot 20