Using testfor to give a potion effect

How do you use a testfor command to give you a potion effect? I want a command that makes it so when you hold a stick called "Flashlight", you get night vision.

Can anyone help?


/testfor will not be useful as it simply outputs if there was a match and will not allow you to target the one(s) who matched.

You will want to use /scoreboard instead, which can apply a label based on a target's NBT data either in the form of a score or "tag". Tag labels are much more efficient to use for simple boolean situations like this one.


The SelectedItem compound holds a copy of the player's currently-held item on the hotbar, minus the Slot tag. You can apply a label based on that, though it must be removed first in the event the player is no longer holding the item:

Repeating > Chain > Chain

All command blocks are set to "Always Active" and "Unconditional".

  1. Remove the label from players first, so that if they are no longer holding the item they will not receive the effect anymore.

    /scoreboard players tag @a[tag=flashlight] remove flashlight
    
  2. Add a "flashlight" label to players that are holding a stick named "Flashlight".

    /scoreboard players tag @a add flashlight {SelectedItem:{id:"minecraft:stick",tag:{display:{Name:"Flashlight"}}}}
    
  3. And you can then use the /effect command to correctly target the players who matched, as they will have a "flashlight" label now:

    /effect @a[tag=flashlight] minecraft:night_vision