Contingency
As part of this spell, cast a spell of 5th-level or lower that has a casting time of 1 action, expending spell slots for both. The second spell must target you, and doesn’t target others even if it normally would.
Describe the circumstances under which the second spell should be cast. It is automatically triggered the first time these circumstances are met. This spell ends when the second spell is triggered, when you cast contingency again, or if the material component for it is not on your person. For example, when you cast contingency with blur as a second spell you might make the trigger be when you see a creature target you with a weapon attack, or you might make it be when you make a weapon attack against a creature, or you could choose for it to be when you see an ally make a weapon attack against a creature.