Mqtt sensor if attribute is present?

How do I create a custom mqtt sensor where the json attribute I want is not always present?

    - name: "Valve3 Position"
      state_topic: "tele/esp32-dev-05/+"
      value_template: >
        {% set pos = (value_json.Valve.Position | int | bitwise_and(3) ) %}
        {{ ["X", "H", "W", "H+W"][pos] }}

This works, but it throws an error for messages which don’t include Valve.
A good message looks like this {"Time":"2024-03-10T18:05:37","Valve":{"Position": 1}}

I guess I need to test for the presence of Valve, but I can’t see how to do that.

Another approach could be to tighten the topic, but I want to catch both tele/esp32-dev-05/RESULT and tele/esp32-dev-05/SENSOR. The problem with + is that I also catch tele/esp32-dev-05/STATE, and that does not include Valve.

As you can see, this is Tasmota. I have created a custom sensor because the default Tasmota sensor only updates in HA on tele/node/SENSOR messages, which is every 5 mins by default. I want it to update on change, which means I need to catch the tele/+/RESULT message.

Many thanks to anyone who can help.

         {% if (value_json.Valve is defined) %}
                 {% set pos = (value_json.Valve.Position | int | bitwise_and(3) ) %}
                 {{ ["X", "H", "W", "H+W"][pos] }}
         {% else %}
           {{ states('sensor.valve3_position') }}
         {% endif %}

Thanks, that helped a lot!