How do I make command blocks teleport players away from an area when they don't have a specific item?

How do I make command blocks that teleports players away from an area, like 2 blocks or so, repeatedly, when they don't have a specific item? I'm trying to make an adventure map that would require certain items to proceed to the next portion of the map.

I want the command blocks to search players inventory for a diamond. If they have a diamond nothing happens. If they do not have diamond it teleports the player backwards 2 blocks. The issue is the first block is a repeating block that searches the players inventory within 2 block range. The second block is a chain block for testforblock (repeating block) successcount:0. Third block tp's ~ ~ ~2. I want the teleport to happen once unless the player reenters the radius. As it is, it teleports infinitely backwards and I have to disable command blocks to fix it.


This is a good place to use scoreboard tags. This will allow you to tag any player that has diamond and use that tag to target them within the tp command.


Use 3 command blocks in a chain. The first command block removes the tag from all players. The second command block tags any players who have a diamond in their inventory. The third command block teleports any player within the boundaries of the target selector who do not have the tag.

These command blocks have to remain loaded. I recommend putting them in the spawn chunk. I also recommend stopping command block output to prevent chat spam for op players. Use command:

/gamerule commandBlockOutput false

The first command block is RepeatUnconditionalAlways Active with command:

scoreboard players tag @a remove Obtained

The second command block is ChainUnconditionalAlways Active with command:

scoreboard players tag @a add Obtained {Inventory:[{id:"minecraft:diamond"}]}

The Third command block is ChainUnconditionalAlways Active with command:

tp @a[x=X,y=Y,z=Z,r=R,tag=!Obtained] ~ ~ ~2

Replace X, Y, and Z with the coordinates of your gate area. Replace R with the desired radius for that area.